<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use App\Security\LoginFormAuthenticator;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use Orc\BookingBundle\Entity\Crew;
use Orc\BookingBundle\Entity\Region;
use Orc\BookingBundle\Entity\Location;
use Orc\BookingBundle\Entity\Boundary;
use Orc\BookingBundle\Entity\Booking;
use Orc\BookingBundle\Entity\BookingStatus;
use Orc\BookingBundle\Entity\BookingServiceField;
use Orc\BookingBundle\Entity\Customer;
use Orc\BookingBundle\Entity\CustomerBilling;
use Orc\BookingBundle\Entity\Service;
use Orc\BookingBundle\Entity\ServiceField;
use Orc\BookingBundle\Booking\PointInPolygon;
use Orc\BookingBundle\Schedule\Scheduler\StrictScheduler\Scheduler;
use Orc\BookingBundle\Schedule\Scheduler\StrictScheduler\DayScheduler;
use Orc\BookingBundle\Twig\Extension\CalendarExtension;
use Orc\BookingBundle\Repository\BookingRepository;
use Orc\BookingBundle\Repository\HoursOfOperationRepository;
use Orc\BookingBundle\Repository\HoursChangeRepository;
use Orc\BookingBundle\Booking\EndTimeCalculator;
use Orc\BookingBundle\Repository\RegionRepository;
use Orc\BookingBundle\Repository\CustomerRepository;
use Orc\BookingBundle\Mailer\ConfirmationMailer;
use Orc\BookingBundle\Mailer\ConfirmationMailerForProcess;
use Orc\BookingBundle\Mailer\ChangeMailer;
use Orc\BookingBundle\Mailer\NotificationMailer;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Address;
use Orc\SaasBundle\Entity\Client;
use Orc\UserBundle\Entity\User;
use App\Controller\BaseController;
use App\Entity\BookingProcess;
use App\Entity\BookingProcessBooking;
use App\Entity\BookingProcessLocation;
use App\Entity\BookingProcessCustomer;
use App\Entity\BookingProcessCustomerBilling;
use App\Entity\BookingProcessBookingNote;
use App\Entity\BookingProcessBookingRegion;
use App\Entity\BookingProcessBookingServiceAnswer;
use App\Model\EntityModel\ClientEntityModel;
use App\Model\EntityModel\EmailsEntityModel;
use App\Service\BaseService;
use App\Service\IpStackService;
use App\Service\ColorUtilsService;
use App\Service\Mapservice;
use App\Service\WebhookService;
use App\Service\ScheduleAvailabilityCMMVP1Service;
use App\Service\RoutezillaDebugger;
use App\Service\SalesForceI360AppointmentsService;
use App\Model\GoogleCalendarModel;
use App\Model\Google\GoogleClient;
use App\Model\EntityModel\WorkerEnityModel;
use Orc\BookingBundle\Mailer\GoogleCalendarNotificationMailer;
use Ramsey\Uuid\Uuid;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Orc\BookingBundle\Booking\RadiusUpdater;
use \Orc\BookingBundle\Booking\DistanceCalculator;
use App\Model\EntityModel\BookingEntityModel;
use Mobile_Detect;
class BookingProcessCMMVP1Controller extends BaseController
{
protected $doctrine = null;
protected $entityManager = null;
protected $userRepository = null;
protected $bookingProcessRepository = null;
protected $regionRepository = null;
protected $serviceRepository = null;
protected $customerRepository = null;
protected $loginFormAuthenticator = null;
protected $guardAuthenticatorHandler = null;
protected $request = null;
protected $pointInPolygon = null;
protected $baseService = null;
protected $client = null;
protected $clientEntityModel = null;
protected $stepoutput = [ 'code' => 0, 'message' => '', 'exception' => null ];
protected $endTimeCalculator = null;
protected $dayScheduler = null;
protected $scheduler = null;
protected $ipStackService = null;
protected $ipStackInfo = null;
protected $confirmationMailer = null;
protected $confirmationMailerForProcess = null;
protected $changeMailer = null;
protected $notificationMailer = null;
protected $colorUtilsService = null;
protected $emailsEntityModel = null;
protected $googleClient = null;
protected $googleCalendarModel = null;
protected $googleCalendarNotificationMailer = null;
protected $workerEnityModel = null;
protected $radiusUpdater = null;
protected $container = null;
protected $mapservice = null;
protected $distanceCalculator = null;
protected $scheduleAvailabilityCMMVP1Service = null;
protected $bookingEntityModel = null;
protected $httpClient = null;
protected $webhookService = null;
protected $salesForceI360AppointmentsService = null;
public function __construct(ManagerRegistry $doctrine, UserPasswordEncoderInterface $passwordEncoder, LoginFormAuthenticator $loginFormAuthenticator, GuardAuthenticatorHandler $guardAuthenticatorHandler, RequestStack $requestStack, PointInPolygon $pointInPolygon, BaseService $baseService, ClientEntityModel $clientEntityModel, EndTimeCalculator $endTimeCalculator, DayScheduler $dayScheduler, Scheduler $scheduler, IpStackService $ipStackService, ConfirmationMailer $confirmationMailer, ConfirmationMailerForProcess $confirmationMailerForProcess, ChangeMailer $changeMailer, NotificationMailer $notificationMailer, ColorUtilsService $colorUtilsService, EmailsEntityModel $emailsEntityModel, GoogleClient $googleClient, GoogleCalendarModel $googleCalendarModel, GoogleCalendarNotificationMailer $googleCalendarNotificationMailer, WorkerEnityModel $workerEnityModel, RadiusUpdater $radiusUpdater, ContainerInterface $container, Mapservice $mapservice, DistanceCalculator $distanceCalculator, BookingRepository $bookingRepository, BookingEntityModel $bookingEntityModel, ScheduleAvailabilityCMMVP1Service $scheduleAvailabilityCMMVP1Service, HttpClientInterface $httpClient, WebhookService $webhookService, CustomerRepository $customerRepository, SalesForceI360AppointmentsService $salesForceI360AppointmentsService, MailerInterface $mailerInterface) {
//throw new \Exception("This MVP is not available anymore");
$this->doctrine = $doctrine;
$this->entityManager = $doctrine->getManager();
$this->userRepository = $doctrine->getRepository(User::class);
$this->bookingProcessRepository = $doctrine->getRepository(BookingProcess::class);
$this->regionRepository = $doctrine->getRepository(Region::class);
$this->serviceRepository = $doctrine->getRepository(Service::class);
$this->serviceFieldRepository = $doctrine->getRepository(ServiceField::class);
$this->customerRepository = $customerRepository;
$this->passwordEncoder = $passwordEncoder;
$this->loginFormAuthenticator = $loginFormAuthenticator;
$this->guardAuthenticationHandler = $guardAuthenticatorHandler;
$this->pointInPolygon = $pointInPolygon;
$this->baseService = $baseService;
$this->clientEntityModel = $clientEntityModel;
$this->endTimeCalculator = $endTimeCalculator;
$this->scheduler = $scheduler;
$this->dayScheduler = $dayScheduler;
$this->ipStackService = $ipStackService;
$this->confirmationMailer = $confirmationMailer;
$this->confirmationMailerForProcess = $confirmationMailerForProcess;
$this->changeMailer = $changeMailer;
$this->notificationMailer = $notificationMailer;
$this->colorUtilsService = $colorUtilsService;
$this->emailsEntityModel = $emailsEntityModel;
$this->client = $baseService->getClient();
$this->request = $requestStack->getCurrentRequest();
$this->encoders = [new XmlEncoder(), new JsonEncoder()];
$this->normalizers = [new ObjectNormalizer()];
$this->serializer = new Serializer($this->normalizers, $this->encoders);
$this->ipStackInfo = $this->ipStackService->getLocationFromIp($this->request->getClientIp());
$this->googleClient = $googleClient;
$this->googleCalendarModel = $googleCalendarModel;
$this->googleCalendarNotificationMailer = $googleCalendarNotificationMailer;
$this->workerEnityModel = $workerEnityModel;
$this->radiusUpdater = $radiusUpdater;
$this->container = $container;
$this->mapservice = $mapservice;
$this->distanceCalculator = $distanceCalculator;
$this->bookingRepository = $bookingRepository;
$this->bookingEntityModel = $bookingEntityModel;
$this->scheduleAvailabilityCMMVP1Service = $scheduleAvailabilityCMMVP1Service;
$this->httpClient = $httpClient;
$this->webhookService = $webhookService;
$this->salesForceI360AppointmentsService = $salesForceI360AppointmentsService;
$this->mailerInterface = $mailerInterface;
}
protected $screens = [
'message',
'input-location-callback',
'input-location',
'input-confirmlocation',
'input-service',
'input-servicefields',
//'input-schedule-type',
'input-datetime',
'input-contact',
'input-billing',
'commit',
'commit-confirm',
'complete',
'complete-callback'
];
protected $screensmap = [
'input-location-callback' => 'booking_process_cm_mvp1_step_input_location_callback',
'input-location' => 'booking_process_cm_mvp1_step_input_location',
'input-confirmlocation' => 'booking_process_cm_mvp1_step_input_confirmlocation',
'input-service' => 'booking_process_cm_mvp1_step_input_service',
'input-servicefields' => 'booking_process_cm_mvp1_step_input_servicefields',
//'input-schedule-type' => 'booking_process_cm_mvp1_step_input_schedule_type',
'input-datetime' => 'booking_process_cm_mvp1_step_input_datetime',
'input-contact' => 'booking_process_cm_mvp1_step_input_contact',
'input-billing' => 'booking_process_cm_mvp1_step_input_billing',
'commit' => 'booking_process_cm_mvp1_step_commit',
'complete' => 'booking_process_cm_mvp1_step_complete',
'complete-callback' => 'booking_process_cm_mvp1_step_complete_callback'
];
private function assertBookingProcess($request, $create_new_process = true) {
$booking = null;
$booking_id = $request->query->get('booking');
$newbooking = ($request->query->get('new') != null);
if ($booking_id != null) {
$booking = $this->bookingRepository->find($booking_id);
}
$cpo = [ 'message' => '' ];
if (!$this->client->isActive()) {
$cpo['booking_process'] = null;
$cpo['set_cookie'] = false;
//$cpo['message'] = 'This account is inactive';
//$cpo['message'] = sprintf('__redirect: %s', $this->client->getWebsite());
if ($this->client->getIsBookingRedirect() && $this->client->getWebsite() != null && preg_match('/^(ftp|http|https):\/\/[^ "]+$/', $this->client->getWebsite())) {
$cpo['message'] = sprintf('__redirect: %s', $this->client->getWebsite());
} else {
$cpo['message'] = sprintf('__inactive: %s', 'We apologize for the incovenience. This page has not been activated. Please click the button to complete your request.');
}
} else {
$nbBookings = $this->bookingEntityModel->getNumberOfBookings($this->client);
$maxBookings = $this->clientEntityModel->getMaxBookings($this->client);
$nBookings = $totalNumberOfBookings = array_sum($nbBookings);
if ($maxBookings > 0 && $nBookings >= $maxBookings) {
//if (true) {
$cpo['booking_process'] = null;
$cpo['set_cookie'] = false;
if ($this->getUser() !== null) {
$cpo['message'] = sprintf('__redirect: %s', $this->generateUrl('billing', []));
} else {
$cpo['message'] = sprintf('__inactive: %s', 'We apologize for the incovenience. This account has reached the maximum number of bookings.');
}
try {
$from = new Address(
$this->container->getParameter('orc_booking.mail.from.address'),
$this->container->getParameter('orc_booking.mail.from.name')
);
$to = new Address($this->client->getEmail(), $this->client->getName());
$email = (new Email())
->from($from)
->to($to)
->subject('You are getting accesses but no more bookings left on your plan cycle!')
->text(sprintf('You are getting accesses on your Routezilla site, but your current plan cycle has no more bookings available! Please check your billing page if you want to change your plan.'))
->html(sprintf('You are getting accesses on your Routezilla site, but your current plan cycle has no more bookings available! Please check your billing page if you want to change your plan.'));
$this->mailerInterface->send($email);
} catch (\Throwable $throwable) {
// NOTHINIG
}
} else if ($newbooking) {
$cpo['booking_process'] = $this->generateBookingProcess($request);
$cpo['set_cookie'] = true;
} else if ($booking != null) {
$cpo['booking_process'] = $this->checkEditBookingProcessWithType($request, 'edit');
if ($cpo['booking_process'] == null || $cpo['booking_process']->getBooking() == null || $cpo['booking_process']->getMaterialBooking()->getId() != $booking->getId()) {
$bp = $this->checkEditBookingProcessByBookingId($request, $booking_id);
if ($bp != null) {
$currentUser = $this->getUser();
$bpbUser = $bp->getBooking() !== null && $bp->getBooking()->getUser() !== null ? $bp->getBooking()->getUser() : null;
$allowedit = false;
if ($bpbUser == null && $currentUser !== null) { $allowedit = true; }
if ($bpbUser != null && $currentUser !== null && $currentUser->getId() == $bpbUser->getId()) { $allowedit = true; }
if ($allowedit) {
$cpo['booking_process'] = $this->generateBookingProcessFromBooking($booking, $request);
$cpo['set_cookie'] = true;
} else {
$cpo['booking_process'] = null;
$cpo['set_cookie'] = false;
$cpo['message'] = 'This booking is blocked for edit / reschedule because there is already an ongoing process for it.';
}
} else {
$cpo['booking_process'] = $this->generateBookingProcessFromBooking($booking, $request);
$cpo['set_cookie'] = true;
}
} else {
$cpo['set_cookie'] = false;
}
} else {
$cpo['booking_process'] = $this->checkBookingProcess($request);
if ($cpo['booking_process'] == null) {
if ($create_new_process) {
$cpo['booking_process'] = $this->generateBookingProcess($request);
$cpo['set_cookie'] = true;
} else {
$cpo['booking_process'] = null;
$cpo['set_cookie'] = false;
}
} else {
$cpo['set_cookie'] = false;
}
}
}
return $cpo;
}
private function checkBookingProcess($request) {
$bookingProcess = null;
$_booking_process_code_ = $request->cookies->get('_booking_process_code_');
$_booking_process_restrictions_ = $request->query->get('restrictions');
if ($_booking_process_code_ == null || $_booking_process_restrictions_ !== null) {
$bookingProcess = null;
} else {
$bookingProcess = $this->bookingProcessRepository->findOneBy(['code' => $_booking_process_code_, 'status' => 'form']);
}
return $bookingProcess;
}
private function checkEditBookingProcessWithType($request, $type) {
$bookingProcess = null;
$_booking_process_code_ = $request->cookies->get('_booking_process_code_');
if ($_booking_process_code_ == null) {
$bookingProcess = null;
} else {
$bookingProcess = $this->bookingProcessRepository->findOneBy(['code' => $_booking_process_code_, 'status' => 'form', 'type' => $type]);
}
return $bookingProcess;
}
private function checkEditBookingProcessByBookingId($request, $booking_id) {
$bookingProcess = $this->bookingProcessRepository->findOneBy(['status' => 'form', 'type' => 'edit', 'material_booking' => $booking_id]);
return $bookingProcess;
}
private function generateBookingProcess($request) {
$now = new \DateTime();
$nowPlus48h = clone $now;
$nowPlus48h->add(new \DateInterval('PT48H'));
$uuid = Uuid::uuid4();
$suuid = $uuid->toString();
$_booking_process_code_ = $suuid;
$bookingProcess = new BookingProcess();
$bookingProcess->setType('create');
$bookingProcess->setScope('cm_mvp1');
$bookingProcess->setCode($_booking_process_code_);
$bookingProcess->setStatus('form');
$bookingProcess->setEmbeddedStatus('');
$bookingProcess->setShowHeader('');
$bookingProcess->setScreen('input-location');
$bookingProcess->setStep('input-location');
$bookingProcess->setAllowedCrews($this->extractStringRestrictions('allowedCrews', $request->query->get('restrictions')));
$bookingProcess->setAllowedServices($this->extractStringRestrictions('allowedServices', $request->query->get('restrictions')));
$bookingProcess->setAllowedRegions($this->extractStringRestrictions('allowedRegions', $request->query->get('restrictions')));
$bookingProcessBooking = new BookingProcessBooking();
$bookingProcessBooking->setScope('cm_mvp1');
$bookingProcessBooking->setClient($this->client);
$user = null;
if ($this->getUser() !== null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId())) {
$user = $this->userRepository->findOneBy(['id' => $this->getUser()->getId()]);
$bookingProcessBooking->setUser($user);
}
$bookingProcess->setBooking($bookingProcessBooking);
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
$bookingProcess->setCreatedAt($now);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setExpiresAt($nowPlus48h);
$bookingProcess->setIpAddress($request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
return $bookingProcess;
}
private function extractStringRestrictions(string $restrictionKey, ?string $restrictions): ?string {
if (!$restrictions) {
return null;
}
$decodedRestrictions = json_decode(base64_decode($restrictions), true);
if (!isset($decodedRestrictions[$restrictionKey]) || !is_array($decodedRestrictions[$restrictionKey])) {
return null;
}
return implode(', ', $decodedRestrictions[$restrictionKey]);
}
private function generateBookingProcessFromBooking($booking, $request) {
$now = new \DateTime();
$nowPlus48h = clone $now;
$nowPlus48h->add(new \DateInterval('PT48H'));
$uuid = Uuid::uuid4();
$suuid = $uuid->toString();
$_booking_process_code_ = $suuid;
$customer = $booking->getCustomer();
$customerLocation = $customer->getLocation();
$customerBilling = $customer->getBilling();
$customerBillingLocation = ($customerBilling != null ? $customerBilling->getLocation() : null);
$location = $booking->getLocation();
$bookingProcess = new BookingProcess();
$bookingProcess->setType('edit');
$bookingProcess->setScope('cm_mvp1');
$bookingProcess->setMaterialBooking($booking);
$bookingProcess->setCode($_booking_process_code_);
$bookingProcess->setStatus('form');
$bookingProcess->setEmbeddedStatus('');
$bookingProcess->setShowHeader('');
$bookingProcess->setScreen('input-location');
$bookingProcess->setStep('input-billing');
$bookingProcessBooking = new BookingProcessBooking();
$bookingProcessBooking->setScope('cm_mvp1');
// POPULATE BOOKING PROCESS FROM BOOKING
$bookingProcessBookingCustomerBilling = null;
if ($customerBilling != null) {
$bookingProcessBookingCustomerBillingLocation = null;
if ($customerBillingLocation != null) {
$bookingProcessBookingCustomerBillingLocation = new BookingProcessLocation();
$bookingProcessBookingCustomerBillingLocation->setStreet($customerBillingLocation->getStreet());
$bookingProcessBookingCustomerBillingLocation->setCity($customerBillingLocation->getCity());
$bookingProcessBookingCustomerBillingLocation->setCode($customerBillingLocation->getCode());
$bookingProcessBookingCustomerBillingLocation->setProvince($customerBillingLocation->getProvince());
$bookingProcessBookingCustomerBillingLocation->setCountry($customerBillingLocation->getCountry());
$bookingProcessBookingCustomerBillingLocation->setLatitude($customerBillingLocation->getLatitude());
$bookingProcessBookingCustomerBillingLocation->setLongitude($customerBillingLocation->getLongitude());
$bookingProcessBookingCustomerBillingLocation->setLine2($customerBillingLocation->getLine2());
$bookingProcessBookingCustomerBillingLocation->buildInput();
$bookingProcessBookingCustomerBillingLocation->buildFormattedAddress();
$this->entityManager->persist($bookingProcessBookingCustomerBillingLocation);
}
$bookingProcessBookingCustomerBilling = new BookingProcessCustomerBilling();
$bookingProcessBookingCustomerBilling->setLocation($bookingProcessBookingCustomerBillingLocation);
$bookingProcessBookingCustomerBilling->setName($customerBilling->getName());
$bookingProcessBookingCustomerBilling->setEmail($customerBilling->getEmail());
$bookingProcessBookingCustomerBilling->setPhone($customerBilling->getPhone());
$bookingProcessBookingCustomerBilling->setPhoneCanonical($customerBilling->getPhoneCanonical());
$this->entityManager->persist($bookingProcessBookingCustomerBilling);
}
$bookingProcessBookingCustomerLocation = new BookingProcessLocation();
$bookingProcessBookingCustomerLocation->setStreet($customerLocation->getStreet());
$bookingProcessBookingCustomerLocation->setCity($customerLocation->getCity());
$bookingProcessBookingCustomerLocation->setCode($customerLocation->getCode());
$bookingProcessBookingCustomerLocation->setProvince($customerLocation->getProvince());
$bookingProcessBookingCustomerLocation->setCountry($customerLocation->getCountry());
$bookingProcessBookingCustomerLocation->setLatitude($customerLocation->getLatitude());
$bookingProcessBookingCustomerLocation->setLongitude($customerLocation->getLongitude());
$bookingProcessBookingCustomerLocation->setLine2($customerLocation->getLine2());
$bookingProcessBookingCustomerLocation->buildInput();
$bookingProcessBookingCustomerLocation->buildFormattedAddress();
$bookingProcessBookingCustomer = new BookingProcessCustomer();
$bookingProcessBookingCustomer->setLocation($bookingProcessBookingCustomerLocation);
$bookingProcessBookingCustomer->setEmail($customer->getEmail());
$bookingProcessBookingCustomer->setName($customer->getName());
$bookingProcessBookingCustomer->setPhone($customer->getPhone());
$bookingProcessBookingCustomer->setPhoneCanonical($customer->getPhoneCanonical());
$bookingProcessBookingCustomer->setClient($customer->getClient());
$bookingProcessBookingCustomer->setPhoneDescription($customer->getPhoneDescription());
$bookingProcessBookingCustomer->setBilling($bookingProcessBookingCustomerBilling);
$bookingProcessBookingLocation = null;
if ($location != null) {
$bookingProcessBookingLocation = new BookingProcessLocation();
$bookingProcessBookingLocation->setStreet($customerLocation->getStreet());
$bookingProcessBookingLocation->setCity($customerLocation->getCity());
$bookingProcessBookingLocation->setCode($customerLocation->getCode());
$bookingProcessBookingLocation->setProvince($customerLocation->getProvince());
$bookingProcessBookingLocation->setCountry($customerLocation->getCountry());
$bookingProcessBookingLocation->setLatitude($customerLocation->getLatitude());
$bookingProcessBookingLocation->setLongitude($customerLocation->getLongitude());
$bookingProcessBookingLocation->setLine2($customerLocation->getLine2());
$bookingProcessBookingLocation->buildInput();
$bookingProcessBookingLocation->buildFormattedAddress();
$this->entityManager->persist($bookingProcessBookingLocation);
}
$bookingProcessBooking->setClient($booking->getClient());
$bookingProcessBooking->setCustomer($bookingProcessBookingCustomer);
$bookingProcessBooking->setService($booking->getService());
$bookingProcessBooking->setServiceType($booking->getServiceType());
$bookingProcessBooking->setLocation($bookingProcessBookingLocation);
$bookingProcessBooking->setSelectedRegion($booking->getSelectedRegion());
$bookingProcessBooking->setCrew($booking->getCrew());
//$bookingProcessBooking->setRadius($booking->getRadius());
$bookingProcessBooking->setDateStart($booking->getDateStart());
$bookingProcessBooking->setDateEnd($booking->getDateEnd());
$bookingProcessBooking->setStatus($booking->getStatus());
$bookingProcessBooking->setAdditionalInformation($booking->getAdditionalInformation());
$bookingProcessBooking->setNotes($booking->getNotes());
$bookingProcessBooking->setBilled($booking->getBilled());
$bookingProcessBooking->setDatePosted($booking->getDatePosted());
$bookingProcessBooking->setDateUpdated($booking->getDateUpdated());
$bookingProcessBooking->setUser($booking->getUser());
$bookingProcessBooking->setAdditionalMinutes($booking->getAdditionalMinutes());
//$workerNotes
$regions = $booking->getRegions();
foreach($regions as $region) {
$bookingProcessBooking->addRegion($region);
}
$fields = $booking->getFields();
foreach ($fields as $field) {
$bookingProcessBookingServiceAnswer = new BookingProcessBookingServiceAnswer();
$bookingProcessBookingServiceAnswer->setBooking($bookingProcessBooking);
$bookingProcessBookingServiceAnswer->setField($field->getField());
$bookingProcessBookingServiceAnswer->setSlug($field->getSlug());
$bookingProcessBookingServiceAnswer->setAnswer($field->getAnswer());
$this->entityManager->persist($bookingProcessBookingServiceAnswer);
}
$bookingProcess->setBooking($bookingProcessBooking);
$this->entityManager->persist($bookingProcessBookingCustomer);
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
$bookingProcess->setCreatedAt($now);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setExpiresAt($nowPlus48h);
$bookingProcess->setIpAddress($request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
return $bookingProcess;
}
private function setCookie($request, $response, $value) {
$now = new \DateTime();
$dt = clone $now;
$dt->add(new \DateInterval('PT24H'));
$scheme = $request->getScheme();
if ($scheme == 'https') {
//$response->headers->setCookie(new Cookie('_booking_process_code_', $value, $dt, '/booking/process', null, true, true, false, Cookie::SAMESITE_NONE));
$response->headers->setCookie(new Cookie('_booking_process_code_', $value, $dt, '/', null, true, true, false, Cookie::SAMESITE_NONE));
} else {
//$response->headers->setCookie(new Cookie('_booking_process_code_', $value, $dt, '/booking/process'));
$response->headers->setCookie(new Cookie('_booking_process_code_', $value, $dt, '/'));
}
}
private function unsetCookie($response) {
$response->headers->clearCookie('_booking_process_code_', '/', null);
}
private function doIncrementGmbClicks($request) {
$rwg_token = $request->query->get('rwg_token');
if ($rwg_token != null) {
$countGmbClicks = $this->client->getCountGmbClicks();
if ($countGmbClicks === null) {
$countGmbClicks = 0;
}
$countGmbClicks++;
$this->client->setCountGmbClicks($countGmbClicks);
$this->entityManager->persist($this->client);
$this->entityManager->flush();
}
}
private function addPreProcessHeaders($request, $response, $bookingProcess) {
$rwg_token = $request->query->get('rwg_token');
$entity_id = $request->query->get('entity_id');
$scheme = $request->getScheme();
if ($rwg_token != null) {
$now = new \DateTime();
$dt = clone $now;
$dt->add(new \DateInterval('P30D'));
$gmbPage = null;
if ($entity_id != null) {
$a_entity_id = explode('-', $entity_id);
$gmb_page_id = null;
if (count($a_entity_id) >= 3) {
$gmb_page_id = $a_entity_id[2];
} else if (count($a_entity_id) >= 2) {
$gmb_page_id = $a_entity_id[1];
}
if ($gmb_page_id !== null) {
$gmbPage = $this->client->getGmbPage($gmb_page_id);
}
}
if ($scheme == 'https') {
//$response->headers->setCookie(new Cookie('_booking_process_code_', $value, $dt, '/booking/process', null, true, true, false, Cookie::SAMESITE_NONE));
$response->headers->setCookie(new Cookie('_rwg_token', $rwg_token, $dt, '/', null, true, true, false, Cookie::SAMESITE_NONE));
if ($entity_id != null) {
$response->headers->setCookie(new Cookie('_merchant_id', $entity_id, $dt, '/', null, true, true, false, Cookie::SAMESITE_NONE));
}
} else {
//$response->headers->setCookie(new Cookie('_booking_process_code_', $value, $dt, '/booking/process'));
$response->headers->setCookie(new Cookie('_rwg_token', $rwg_token, $dt, '/'));
if ($entity_id != null) {
$response->headers->setCookie(new Cookie('_merchant_id', $rwg_token, $dt, '/'));
}
}
$bookingProcess->setRwgToken($rwg_token);
$bookingProcess->setEntityId($entity_id);
$countGmbClicks = $this->client->getCountGmbClicks();
if ($countGmbClicks === null) {
$countGmbClicks = 0;
}
$countGmbClicks++;
$this->client->setCountGmbClicks($countGmbClicks);
if ($gmbPage !== null) {
$countGmbPageClicks = $gmbPage->getCountGmbClicks();
if ($countGmbPageClicks === null) {
$countGmbPageClicks = 0;
}
$countGmbPageClicks++;
$gmbPage->setCountGmbClicks($countGmbPageClicks);
}
$this->entityManager->persist($bookingProcess);
$this->entityManager->persist($this->client);
if ($gmbPage !== null) {
$this->entityManager->persist($gmbPage);
}
$this->entityManager->flush();
}
}
private function doStepRedirectionGET($request, $bookingProcess) {
switch ($bookingProcess->getScreen()) {
case 'input-location':
{
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
}
break;
case 'input-location-callback':
{
return $this->redirect($this->generateUrl($this->screensmap['input-location-callback']));
}
break;
case 'input-confirmlocation':
{
return $this->redirect($this->generateUrl($this->screensmap['input-confirmlocation']));
}
break;
case 'input-service':
{
return $this->redirect($this->generateUrl($this->screensmap['input-service']));
}
break;
case 'input-servicefields':
{
return $this->redirect($this->generateUrl($this->screensmap['input-servicefields']));
}
break;
case 'input-datetime':
{
return $this->redirect($this->generateUrl($this->screensmap['input-datetime']));
}
break;
case 'input-contact':
{
return $this->redirect($this->generateUrl($this->screensmap['input-contact']));
}
break;
case 'input-billing':
{
return $this->redirect($this->generateUrl($this->screensmap['input-billing']));
}
break;
default:
{
//return $this->step_company($request);
//return $this->forward('App\Controller\SignUpController::step_company', array());
return new Response(
'INVALID STEP',
Response::HTTP_OK,
['content-type' => 'text/html']
);
}
}
}
private function setGoToScreenOnBookingProcess($bookingProcess, $newscreen) {
$now = new \DateTime();
$newposition = array_search($newscreen, $this->screens);
if ($newposition === false) {
return;
}
$currentstep = array_search($bookingProcess->getStep(), $this->screens);
if ($newposition > $currentstep) {
$bookingProcess->setStep($newscreen);
}
$bookingProcess->setScreen($newscreen);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
private function redirectOnInvalidStep($request, $bookingProcess, $screen, $setCookie = false) {
$response = null;
$position = array_search($screen, $this->screens);
if ($position === false) {
//return $this->redirect($this->generateUrl($this->screensmap[$bookingProcess->getStep()]));
$response = new RedirectResponse($this->generateUrl($this->screensmap[$bookingProcess->getStep()]));
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
}
$currentstep = array_search($bookingProcess->getStep(), $this->screens);
if ($position > $currentstep) {
//return $this->redirect($this->generateUrl($this->screensmap[$bookingProcess->getStep()]));
$response = new RedirectResponse($this->generateUrl($this->screensmap[$bookingProcess->getStep()]));
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
}
return $response;
}
/**
* @Route("/booking/process/cm/mvp1", name="booking_process_cm_mvp1")
* @Route("/booking/process", name="booking_process_cm_mvp1_default", condition="(((context.getHost() not in %app.beta.clients%) and ('%booking_process.scope%' == 'cm_mvp1')) or ((context.getHost() in %app.beta.clients%) and ('%booking_process.beta.scope%' == 'cm_mvp1')))")
*/
public function index(Request $request): Response
{
$booking_id = $request->query->get('booking');
if ($booking_id != null) {
return $this->redirect($this->generateUrl($this->screensmap['input-location'], array('booking' => $booking_id)));
} else {
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
}
// return $this->render('booking_process_cm_mvp1/index.html.twig', [
// 'controller_name' => 'BookingProcessController',
// ]);
}
/**
* @Route("/booking/process/cm/mvp1/cancel", name="booking_process_cm_mvp1_cancel")
*/
public function cancel(Request $request)
{
$booking_process = $this->checkBookingProcess($request);
$response = $this->getUser() ? new RedirectResponse($this->generateUrl('book_admin')) : new RedirectResponse($this->generateUrl('booking_process_cm_mvp1'));
if ($booking_process != null) {
$this->unsetCookie($response);
}
return $response;
}
public function doStepInputLocation($request, $bookingProcess) {
$now = new \DateTime();
$bookingProcessBooking = $bookingProcess->getBooking();
$bookingProcessLocation = null;
$existing_customer_id = $request->request->get('customer-id');
if ($existing_customer_id != null && $existing_customer_id != '') {
$actual_customer = $this->customerRepository->findOneBy(['id' => intval($existing_customer_id)]);
$customer = $bookingProcess->getBooking()->getCustomer();
if ($customer == null) {
$customer = new BookingProcessCustomer();
$bookingProcessBooking->setCustomer($customer);
}
$customer->setEmail($actual_customer->getEmail());
$customer->setName($actual_customer->getName());
$customer->setPhone($actual_customer->getPhone());
$customer->setPhoneCanonical($actual_customer->getPhone());
$customer->setClient($this->client);
$customer->setDeleted(false);
$customer->setPhoneDescription('');
$this->entityManager->persist($customer);
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
}
if ($request->request->get('id') == "") {
if ($request->request->get('type') === 'fixed') {
$bookingProcessLocation = $bookingProcessBooking->getLocation();
if ($bookingProcessLocation != null) {
$bookingProcessBooking->setLocation(null);
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->remove($bookingProcessLocation);
$this->entityManager->flush();
}
$bookingProcessLocation = new BookingProcessLocation();
$region_id = intval($request->request->get('fixed_region_id'));
$region = $this->regionRepository->find($region_id);
//$location = $region->getBoundaries()[0]->getLocation();
$bookingProcessLocation->setInput($region->getAddress());
$bookingProcessLocation->setFormattedAddress($region->getAddress());
$bookingProcessLocation->setStreet($region->getStreet());
$bookingProcessLocation->setCity($region->getCity());
$bookingProcessLocation->setProvince($region->getProvince());
$bookingProcessLocation->setCountry($region->getCountry());
$bookingProcessLocation->setCode($region->getCode());
$bookingProcessLocation->setLatitude($region->getLatitude());
$bookingProcessLocation->setLongitude($region->getLongitude());
//$ad = $this->mapservice->getAddressDetailsFromLatLng($location->getLatitude(), $location->getLongitude());
// $bookingProcessLocation->setInput('');
// $bookingProcessLocation->setFormattedAddress('');
// $bookingProcessLocation->setStreet(property_exists($ad, 'street') ? $ad->street : '');
// $bookingProcessLocation->setCity(property_exists($ad, 'city') ? $ad->city : '');
// $bookingProcessLocation->setProvince(property_exists($ad, 'province') ? $ad->province : '');
// $bookingProcessLocation->setCountry(property_exists($ad, 'country') ? $ad->country : '');
// $bookingProcessLocation->setCode(property_exists($ad, 'code') ? $ad->code : '');
// $bookingProcessLocation->setLatitude(property_exists($ad, 'latitude') ? $ad->latitude : null);
// $bookingProcessLocation->setLongitude(property_exists($ad, 'longitude') ? $ad->longitude : null);
$this->entityManager->persist($bookingProcessLocation);
$this->entityManager->flush();
$bookingProcessBooking->setLocation($bookingProcessLocation);
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
$bookingRegions = $bookingProcessBooking->getRegions();
$bookingRegionsIds = [];
if ($bookingRegions) {
foreach($bookingRegions as $bookingRegion) {
$bookingRegionsIds[] = $bookingRegion->getId();
}
}
$bookingProcessBooking->setServiceType('fixed');
$bookingProcessBooking->setSelectedRegion($region);
$bookingProcessBooking->setDateStart(null);
$bookingProcessBooking->setDateEnd(null);
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
foreach ($bookingRegions as $bookingRegion) {
$bookingProcessBooking->removeRegion($bookingRegion);
}
//$locationRegions = $this->getRegionsFromLocation($bookingProcessLocation, $bookingProcess->getAllowedRegions());
// if (!$locationRegions || count($locationRegions) < 1) {
// $bookingProcessBooking->addRegion($region);
// } else {
// foreach ($locationRegions as $locationRegion) {
// $bookingProcessBooking->addRegion($locationRegion);
// }
// }
$bookingProcessBooking->addRegion($region);
// TODO: REMOVE THIS
// foreach($locationRegions as $locationRegion) {
// if (!in_array($locationRegion->getId(), $bookingRegionsIds)) {
// $bookingProcessBooking->addRegion($locationRegion);
// }
// }
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
} else {
$bookingProcessLocation = $bookingProcessBooking->getLocation();
if ($request->request->get('input') == "") {
if ($bookingProcessLocation != null) {
$bookingProcessBooking->setLocation(null);
$this->entityManager->remove($bookingProcessLocation);
}
throw new \Exception("Location is empty!");
}
if ($bookingProcessLocation != null) {
$bookingProcessBooking->setLocation(null);
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->remove($bookingProcessLocation);
$this->entityManager->flush();
}
$bookingProcessLocation = new BookingProcessLocation();
if ($request->request->get('geolocation') == 'true') {
$bookingProcessLocation->setInput($request->request->get('input'));
$bookingProcessLocation->setFormattedAddress($request->request->get('formatted_address'));
$bookingProcessLocation->setStreet($request->request->get('street'));
$bookingProcessLocation->setCity($request->request->get('city'));
$bookingProcessLocation->setProvince($request->request->get('province'));
$bookingProcessLocation->setCountry($request->request->get('country'));
$bookingProcessLocation->setCode($request->request->get('code'));
$bookingProcessLocation->setLatitude(doubleval($request->request->get('latitude')));
$bookingProcessLocation->setLongitude(doubleval($request->request->get('longitude')));
} else {
$ad = $this->mapservice->getAddressDetails($request->request->get('input'));
if ($ad == null) {
$bookingProcessLocation->setInput($request->request->get('input'));
$this->entityManager->persist($bookingProcessLocation);
$this->entityManager->flush();
$bookingProcessBooking->setLocation($bookingProcessLocation);
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
throw new \Exception("Please select from search suggestions!");
}
$bookingProcessLocation->setInput($request->request->get('input'));
$bookingProcessLocation->setFormattedAddress(property_exists($ad, 'formatted_address') ? $ad->formatted_address : '');
$bookingProcessLocation->setStreet(property_exists($ad, 'street') ? $ad->street : '');
$bookingProcessLocation->setCity(property_exists($ad, 'city') ? $ad->city : '');
$bookingProcessLocation->setProvince(property_exists($ad, 'province') ? $ad->province : '');
$bookingProcessLocation->setCountry(property_exists($ad, 'country') ? $ad->country : '');
$bookingProcessLocation->setCode(property_exists($ad, 'code') ? $ad->code : '');
$bookingProcessLocation->setLatitude(property_exists($ad, 'latitude') ? $ad->latitude : null);
$bookingProcessLocation->setLongitude(property_exists($ad, 'longitude') ? $ad->longitude : null);
}
$this->entityManager->persist($bookingProcessLocation);
$this->entityManager->flush();
$bookingProcessBooking->setLocation($bookingProcessLocation);
$bookingProcessBooking->setSelectedRegion(null);
$bookingProcessBooking->setServiceType('onsite');
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
$bookingRegions = $bookingProcessBooking->getRegions();
$bookingRegionsIds = [];
if ($bookingRegions) {
foreach($bookingRegions as $bookingRegion) {
$bookingRegionsIds[] = $bookingRegion->getId();
}
}
$bookingProcessBooking->setDateStart(null);
$bookingProcessBooking->setDateEnd(null);
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
$locationRegions = $this->getRegionsFromLocation($bookingProcessLocation, $bookingProcess->getAllowedRegions());
if (!$locationRegions || count($locationRegions) < 1) {
throw new \Exception("Location is out of bounds!");
}
foreach ($bookingRegions as $bookingRegion) {
$bookingProcessBooking->removeRegion($bookingRegion);
}
foreach ($locationRegions as $locationRegion) {
$bookingProcessBooking->addRegion($locationRegion);
}
// TODO: REMOVE THIS
// foreach($locationRegions as $locationRegion) {
// if (!in_array($locationRegion->getId(), $bookingRegionsIds)) {
// $bookingProcessBooking->addRegion($locationRegion);
// }
// }
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
}
} else {
$bookingProcessLocation = $bookingProcess->getBooking()->getLocation();
$bookingRegions = $bookingProcessBooking->getRegions();
$bookingRegionsIds = [];
if ($bookingRegions) {
foreach($bookingRegions as $bookingRegion) {
$bookingRegionsIds[] = $bookingRegion->getId();
}
}
$locationRegions = $this->getRegionsFromLocation($bookingProcessLocation, $bookingProcess->getAllowedRegions());
if ($request->request->get('type') === 'fixed') {
$region_id = intval($request->request->get('fixed_region_id'));
$region = $this->regionRepository->find($region_id);
// dump($request->request->get('id'));
// dump($request->request->get('type'));
// dump($region_id);
// dd($region);
foreach ($bookingRegions as $bookingRegion) {
$bookingProcessBooking->removeRegion($bookingRegion);
}
// if (!$locationRegions || count($locationRegions) < 1) {
// $bookingProcessBooking->addRegion($region);
// } else {
// foreach ($locationRegions as $locationRegion) {
// $bookingProcessBooking->addRegion($locationRegion);
// }
// }
$bookingProcessLocation->setInput($region->getAddress());
$bookingProcessLocation->setFormattedAddress($region->getAddress());
$bookingProcessLocation->setStreet($region->getStreet());
$bookingProcessLocation->setCity($region->getCity());
$bookingProcessLocation->setProvince($region->getProvince());
$bookingProcessLocation->setCountry($region->getCountry());
$bookingProcessLocation->setCode($region->getCode());
$bookingProcessLocation->setLatitude($region->getLatitude());
$bookingProcessLocation->setLongitude($region->getLongitude());
$this->entityManager->persist($bookingProcessLocation);
$this->entityManager->flush();
$bookingProcessBooking->addRegion($region);
$bookingProcessBooking->setSelectedRegion($region);
} else {
if (!$locationRegions) {
throw new \Exception("Location is out of bounds!");
}
foreach ($bookingRegions as $bookingRegion) {
$bookingProcessBooking->removeRegion($bookingRegion);
}
foreach ($locationRegions as $locationRegion) {
$bookingProcessBooking->addRegion($locationRegion);
}
}
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
}
return true;
}
public function doStepInputLocationCallback($request, $bookingProcess) {
$now = new \DateTime();
$bookingProcessBooking = $bookingProcess->getBooking();
$bookingProcessBooking->setStatus(BookingStatus::STATUS_REQUESTED);
$bookingProcessBooking->setAdditionalMinutes(0);
$bookingProcessBooking->setAdditionalInformation('');
//$bookingProcessBooking->setDateStart(clone $now);
//$bookingProcessBooking->setService($this->client->getServices()[0]);
$bookingProcessLocation = $bookingProcessBooking->getLocation();
$bookingProcessCustomer = $bookingProcessBooking->getCustomer();
if ($bookingProcessCustomer == null) {
$bookingProcessCustomer = new BookingProcessCustomer();
$bookingProcessBooking->setCustomer($bookingProcessCustomer);
}
$bookingProcessCustomer->setEmail($request->request->get('contact-email'));
$bookingProcessCustomer->setName($request->request->get('contact-name'));
$bookingProcessCustomer->setPhone($request->request->get('contact-phone'));
$bookingProcessCustomer->setPhoneCanonical($request->request->get('contact-phone'));
$bookingProcessCustomer->setClient($this->client);
$bookingProcessCustomer->setDeleted(false);
$bookingProcessCustomer->setPhoneDescription('');
$bookingProcessCustomerLocation = $bookingProcessCustomer->getLocation();
if ($bookingProcessCustomerLocation == null) {
$bookingProcessCustomerLocation = new BookingProcessLocation();
$bookingProcessCustomer->setLocation($bookingProcessCustomerLocation);
}
$bookingProcessCustomerLocation->setStreet($request->request->get('contact-street'));
$bookingProcessCustomerLocation->setCity($request->request->get('contact-city'));
$bookingProcessCustomerLocation->setCode($request->request->get('contact-code'));
$bookingProcessCustomerLocation->setProvince($request->request->get('contact-province'));
$bookingProcessCustomerLocation->setCountry($request->request->get('contact-country'));
$bookingProcessCustomerLocation->setLatitude(0);
$bookingProcessCustomerLocation->setLongitude(0);
$bookingProcessCustomerLocation->setLine2($request->request->get('contact-line2'));
$bookingProcessCustomerLocation->setInput('');
$bookingProcessCustomerLocation->setFormattedAddress('');
$isBillingSame = ($request->request->get('contact-billing-same') != null);
$bookingProcessCustomerBilling = null;
if ($isBillingSame) {
// $bookingProcessCustomerBilling = $bookingProcessCustomer->getBilling();
// $bookingProcessCustomerBillingLocation = null;
// if ($bookingProcessCustomerBilling != null) {
// $bookingProcessCustomer->setBilling(null);
// $this->entityManager->remove($bookingProcessCustomerBilling);
// }
$bookingProcessCustomerBilling = $bookingProcessCustomer->getBilling();
$bookingProcessCustomerBillingLocation = null;
if ($bookingProcessCustomerBilling == null) {
$bookingProcessCustomerBilling = new BookingProcessCustomerBilling();
$bookingProcessCustomerBillingLocation = $bookingProcessCustomerBilling->getLocation();
if ($bookingProcessCustomerBillingLocation == null) {
$bookingProcessCustomerBillingLocation = new BookingProcessLocation();
$bookingProcessCustomerBilling->setLocation($bookingProcessCustomerBillingLocation);
}
} else {
$bookingProcessCustomerBillingLocation = $bookingProcessCustomerBilling->getLocation();
if ($bookingProcessCustomerBillingLocation == null) {
$bookingProcessCustomerBillingLocation = new BookingProcessLocation();
$bookingProcessCustomerBilling->setLocation($bookingProcessCustomerBillingLocation);
}
}
$bookingProcessCustomerBilling->setName($bookingProcessCustomer->getName());
$bookingProcessCustomerBilling->setEmail($bookingProcessCustomer->getEmail());
$bookingProcessCustomerBilling->setPhone($bookingProcessCustomer->getPhone());
$bookingProcessCustomerBillingLocation->setStreet($bookingProcessCustomerLocation->getStreet());
$bookingProcessCustomerBillingLocation->setCity($bookingProcessCustomerLocation->getCity());
$bookingProcessCustomerBillingLocation->setCode($bookingProcessCustomerLocation->getCode());
$bookingProcessCustomerBillingLocation->setProvince($bookingProcessCustomerLocation->getProvince());
$bookingProcessCustomerBillingLocation->setCountry($bookingProcessCustomerLocation->getCountry());
$bookingProcessCustomerBillingLocation->setLatitude($bookingProcessCustomerLocation->getLatitude());
$bookingProcessCustomerBillingLocation->setLongitude($bookingProcessCustomerLocation->getLongitude());
$bookingProcessCustomerBillingLocation->setLine2($bookingProcessCustomerLocation->getLine2());
$bookingProcessCustomerBillingLocation->setInput($bookingProcessCustomerLocation->getInput());
$bookingProcessCustomerBillingLocation->setFormattedAddress($bookingProcessCustomerLocation->getFormattedAddress());
$bookingProcessCustomer->setBilling($bookingProcessCustomerBilling);
} else {
$bookingProcessCustomerBilling = $bookingProcessCustomer->getBilling();
$bookingProcessCustomerBillingLocation = null;
if ($bookingProcessCustomerBilling == null) {
$bookingProcessCustomerBilling = new BookingProcessCustomerBilling();
$bookingProcessCustomerBillingLocation = $bookingProcessCustomerBilling->getLocation();
if ($bookingProcessCustomerBillingLocation == null) {
$bookingProcessCustomerBillingLocation = new BookingProcessLocation();
$bookingProcessCustomerBilling->setLocation($bookingProcessCustomerBillingLocation);
}
} else {
$bookingProcessCustomerBillingLocation = $bookingProcessCustomerBilling->getLocation();
if ($bookingProcessCustomerBillingLocation == null) {
$bookingProcessCustomerBillingLocation = new BookingProcessLocation();
$bookingProcessCustomerBilling->setLocation($bookingProcessCustomerBillingLocation);
}
}
$bookingProcessCustomerBilling->setName($request->request->get('billing-street'));
$bookingProcessCustomerBilling->setEmail($request->request->get('billing-email'));
$bookingProcessCustomerBilling->setPhone($request->request->get('billing-phone'));
$bookingProcessCustomerBillingLocation->setStreet($request->request->get('billing-street'));
$bookingProcessCustomerBillingLocation->setCity($request->request->get('billing-city'));
$bookingProcessCustomerBillingLocation->setCode($request->request->get('billing-code'));
$bookingProcessCustomerBillingLocation->setProvince($request->request->get('billing-province'));
$bookingProcessCustomerBillingLocation->setCountry($request->request->get('billing-country'));
$bookingProcessCustomerBillingLocation->setLatitude(doubleval($request->request->get('billing-latitude')));
$bookingProcessCustomerBillingLocation->setLongitude(doubleval($request->request->get('billing-longitude')));
$bookingProcessCustomerBillingLocation->setLine2($request->request->get('billing-line2'));
$bookingProcessCustomerBillingLocation->setInput('');
$bookingProcessCustomerBillingLocation->setFormattedAddress('');
$bookingProcessCustomer->setBilling($bookingProcessCustomerBilling);
}
if ($bookingProcessCustomerBilling != null) {
$this->entityManager->persist($bookingProcessCustomerBilling);
}
$this->entityManager->persist($bookingProcessLocation);
$this->entityManager->persist($bookingProcessCustomer);
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
$booking = new Booking();
$customer_location = new Location();
if ($bookingProcessBooking->getServiceType() === 'fixed' && false) {
$customer_location->setStreet('');
$customer_location->setCity('');
$customer_location->setProvince('');
$customer_location->setCountry('');
$customer_location->setCode('');
$customer_location->setLatitude(null);
$customer_location->setLongitude(null);
$customer_location->setLine2('');
} else {
$customer_location->setStreet($bookingProcessCustomerLocation->getStreet());
$customer_location->setCity($bookingProcessCustomerLocation->getCity());
$customer_location->setProvince($bookingProcessCustomerLocation->getProvince());
$customer_location->setCountry($bookingProcessCustomerLocation->getCountry());
$customer_location->setCode($bookingProcessCustomerLocation->getCode());
$customer_location->setLatitude($bookingProcessCustomerLocation->getLatitude());
$customer_location->setLongitude($bookingProcessCustomerLocation->getLongitude());
$customer_location->setLine2($bookingProcessCustomerLocation->getLine2());
}
$customer_billing_location = null;
$customer_billing = null;
$bookingProcessBookingCustomerBilling = $bookingProcessCustomer->getBilling();
if ($bookingProcessBookingCustomerBilling != null) {
$bookingProcessBookingCustomerBillingLocation = $bookingProcessBookingCustomerBilling->getLocation();
if ($bookingProcessBookingCustomerBillingLocation != null) {
$customer_billing_location = new Location();
if ($bookingProcessBooking->getServiceType() === 'fixed' && false) {
$customer_billing_location->setStreet('');
$customer_billing_location->setCity('');
$customer_billing_location->setProvince('');
$customer_billing_location->setCountry('');
$customer_billing_location->setCode('');
$customer_billing_location->setLatitude(null);
$customer_billing_location->setLongitude(null);
$customer_billing_location->setLine2('');
} else {
$customer_billing_location->setStreet($bookingProcessBookingCustomerBillingLocation->getStreet());
$customer_billing_location->setCity($bookingProcessBookingCustomerBillingLocation->getCity());
$customer_billing_location->setProvince($bookingProcessBookingCustomerBillingLocation->getProvince());
$customer_billing_location->setCountry($bookingProcessBookingCustomerBillingLocation->getCountry());
$customer_billing_location->setCode($bookingProcessBookingCustomerBillingLocation->getCode());
$customer_billing_location->setLatitude($bookingProcessBookingCustomerBillingLocation->getLatitude());
$customer_billing_location->setLongitude($bookingProcessBookingCustomerBillingLocation->getLongitude());
$customer_billing_location->setLine2($bookingProcessBookingCustomerBillingLocation->getLine2());
}
}
$customer_billing = new CustomerBilling();
$customer_billing->setLocation($customer_billing_location);
$customer_billing->setName($bookingProcessBookingCustomerBilling->getName());
$customer_billing->setEmail($bookingProcessBookingCustomerBilling->getEmail());
$customer_billing->setPhone($bookingProcessBookingCustomerBilling->getPhone());
$customer_billing->setPhoneCanonical($bookingProcessBookingCustomerBilling->getPhoneCanonical());
}
$customer = new Customer();
$customer->setLocation($customer_location);
if ($customer_billing != null) {
$customer->setBilling($customer_billing);
}
$customer->setEmail($bookingProcessCustomer->getEmail());
$customer->setName($bookingProcessCustomer->getName());
$customer->setPhone($bookingProcessCustomer->getPhone());
$customer->setPhoneCanonical($bookingProcessCustomer->getPhoneCanonical());
$customer->setClient($bookingProcessCustomer->getClient());
$customer->setDeleted($bookingProcessCustomer->getDeleted());
$customer->setPhoneDescription($bookingProcessCustomer->getPhoneDescription());
$location = new Location();
$location->setStreet($bookingProcessLocation->getStreet());
$location->setCity($bookingProcessLocation->getCity());
$location->setProvince($bookingProcessLocation->getProvince());
$location->setCountry($bookingProcessLocation->getCountry());
$location->setCode($bookingProcessLocation->getCode());
$location->setLatitude($bookingProcessLocation->getLatitude());
$location->setLongitude($bookingProcessLocation->getLongitude());
$location->setLine2($bookingProcessLocation->getLine2());
$booking->setScope('cm_mvp1');
$booking->setClient($bookingProcessBooking->getClient());
$booking->setCustomer($customer);
$booking->setService($bookingProcessBooking->getService());
$booking->setLocation($location);
$booking->setServiceType($bookingProcessBooking->getServiceType());
$booking->setSelectedRegion($bookingProcessBooking->getSelectedRegion());
$booking->setCrew($bookingProcessBooking->getCrew());
$booking->setRadius($bookingProcessBooking->getRadius());
$booking->setDateStart($bookingProcessBooking->getDateStart());
$booking->setDateEnd($bookingProcessBooking->getDateEnd());
$booking->setAdditionalInformation($bookingProcessBooking->getAdditionalInformation());
//$booking->setNotes($bookingProcessBooking->getNotes());
$booking->setDatePosted(clone $now);
$booking->setDateUpdated(clone $now);
//$booking->setUser(null);
$booking->setAdditionalMinutes($bookingProcessBooking->getAdditionalMinutes());
$booking->setStatus($bookingProcessBooking->getStatus());
$bookingProcessBookingRegions = $bookingProcessBooking->getRegions();
foreach ($bookingProcessBookingRegions as $bookingProcessBookingRegion) {
$booking->addRegion($bookingProcessBookingRegion);
}
if ($customer_billing_location != null) {
$this->entityManager->persist($customer_billing_location);
}
if ($customer_billing != null) {
$this->entityManager->persist($customer_billing);
}
if ($customer_location != null) {
$this->entityManager->persist($customer_location);
}
if ($customer != null) {
$this->entityManager->persist($customer);
}
if ($location != null) {
$this->entityManager->persist($location);
}
if ($booking != null) {
$this->entityManager->persist($booking);
}
$this->entityManager->flush();
if ($region = $this->getRegion($booking->getLocation())) {
$regions = $booking->getRegions();
$regionIds = [];
if ($regions != null) {
foreach($regions as $region) {
$regionIds[] = $region->getId();
}
}
if (!in_array($region->getId(), $regionIds)) {
$booking->addRegion($region);
}
$this->entityManager->persist($booking);
$this->entityManager->flush();
}
$notificationMailer = $this->notificationMailer;
try {
$notificationMailer->send($booking);
}
catch (TransportException $e) {
//$this->emailErrors[] = 'Failed to send you an e-mail confirmation at ' . htmlspecialchars($customer->getEmail()) . '. It seems that this e-mail is not valid.';
//$result = self::FAILED_TO_SEND_EMAIL;
}
try {
$notificationMailer->sendSMS($booking);
}
catch (\Throwable $e) {
//$this->emailErrors[] = 'Failed to send you an SMS confirmation to ' . htmlspecialchars($customer->getPhone()) . '.';
//$result = self::FAILED_TO_SEND_EMAIL;
}
return true;
}
public function doStepInputConfirmLocation($request, $bookingProcess) {
$now = new \DateTime();
$bookingProcessBooking = $bookingProcess->getBooking();
$bookingProcessLocation = $bookingProcess->getBooking()->getLocation();
$address = $this->getAddress($request);
$ad = $this->mapservice->getAddressDetails($address);
if ($ad != null) {
$bookingProcessLocation->setInput($address);
$bookingProcessLocation->setLine2($request->request->get('line2'));
$bookingProcessLocation->setFormattedAddress(property_exists($ad, 'formatted_address') ? $ad->formatted_address : '');
$bookingProcessLocation->setStreet(property_exists($ad, 'street') ? $ad->street : $request->request->get('street'));
$bookingProcessLocation->setCity(property_exists($ad, 'city') ? $ad->city : $request->request->get('city'));
$bookingProcessLocation->setProvince(property_exists($ad, 'province') ? $ad->province : $request->request->get('province'));
$bookingProcessLocation->setCountry(property_exists($ad, 'country') ? $ad->country : $request->request->get('country'));
$bookingProcessLocation->setCode(property_exists($ad, 'code') ? $ad->code : $request->request->get('code'));
$bookingProcessLocation->setLatitude(property_exists($ad, 'latitude') ? $ad->latitude : null);
$bookingProcessLocation->setLongitude(property_exists($ad, 'longitude') ? $ad->longitude : null);
} else {
$bookingProcessLocation->setStreet($request->request->get('street'));
$bookingProcessLocation->setLine2($request->request->get('line2'));
$bookingProcessLocation->setCity($request->request->get('city'));
$bookingProcessLocation->setCode($request->request->get('code'));
$bookingProcessLocation->setProvince($request->request->get('province'));
$bookingProcessLocation->setCountry($request->request->get('country'));
$bookingProcessLocation->setLatitude(null);
$bookingProcessLocation->setLongitude(null);
}
$this->entityManager->persist($bookingProcessLocation);
$this->entityManager->flush();
$bookingRegions = $bookingProcessBooking->getRegions();
$bookingRegionsIds = [];
if ($bookingRegions) {
foreach($bookingRegions as $bookingRegion) {
$bookingRegionsIds[] = $bookingRegion->getId();
}
}
$locationRegions = $this->getRegionsFromLocation($bookingProcessLocation, $bookingProcess->getAllowedRegions());
if (!$locationRegions) {
throw new \Exception("Location is out of bounds!");
}
foreach ($bookingRegions as $bookingRegion) {
$bookingProcessBooking->removeRegion($bookingRegion);
}
foreach ($locationRegions as $locationRegion) {
$bookingProcessBooking->addRegion($locationRegion);
}
// TODO: REMOVE THIS
// foreach($locationRegions as $locationRegion) {
// if (!in_array($locationRegion->getId(), $bookingRegionsIds)) {
// $bookingProcessBooking->addRegion($locationRegion);
// }
// }
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
return true;
}
public function doStepInputService($request, $bookingProcess, ?string $serviceId = null) {
$now = new \DateTime();
if ($serviceId) {
$newId = intval($serviceId);
} else {
$newId = intval($request->request->get('service_id'));
}
$bookingProcessBooking = $bookingProcess->getBooking();
$bookingProcessBookingService = $bookingProcessBooking->getService();
if ($bookingProcessBookingService == null || $bookingProcessBookingService->getId() != $newId) {
$service = $this->serviceRepository->findOneById($newId);
$bookingProcessBooking->setService($service);
$bookingProcessBooking->setAdditionalInformation('');
$a = $bookingProcessBooking->emptyBookingProcessBookingServiceAnswers();
foreach ($a as $bookingProcessBookingServiceAnswer) {
$this->entityManager->remove($bookingProcessBookingServiceAnswer);
}
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
}
return true;
}
public function doStepInputServiceFields($request, $bookingProcess) {
$now = new \DateTime();
$bookingProcessBooking = $bookingProcess->getBooking();
$answers = $bookingProcessBooking->getBookingProcessBookingServiceAnswers();
foreach ($answers as $answer) {
$this->entityManager->remove($answer);
}
$this->entityManager->flush();
$sfields = $request->request->get('fields');
$afields = explode(',', $sfields);
foreach ($afields as $field_id) {
$serviceField = $this->serviceFieldRepository->find($field_id);
if ($serviceField == null) {
continue;
}
$bookingProcessBookingServiceAnswer = new BookingProcessBookingServiceAnswer();
$bookingProcessBookingServiceAnswer->setBooking($bookingProcessBooking);
$bookingProcessBookingServiceAnswer->setField($serviceField);
$bookingProcessBookingServiceAnswer->setSlug($serviceField->getSlug());
$bookingProcessBookingServiceAnswer->setAnswer($request->request->get("field_${field_id}"));
$this->entityManager->persist($bookingProcessBookingServiceAnswer);
$this->entityManager->flush();
}
$additionalMinutes = 0;
$bookingProcessBooking->setAdditionalInformation($request->request->get('comments'));
$bookingProcessBooking->setAdditionalMinutes($additionalMinutes);
$this->entityManager->persist($bookingProcessBooking);
return true;
}
public function doStepInputScheduleType($request, $bookingProcess) {
// TODO
return true;
}
public function doStepInputDateTime($request, $bookingProcess) {
$now = new \DateTime();
$bookingProcessBooking = $bookingProcess->getBooking();
$sdate = $request->request->get('date');
$ssstart = $request->request->get('start');
$astart = explode('|', $ssstart);
$sscheduletype = 'exact';
$sstarttype = count($astart) > 0 ? $astart[0] : '';
$sstart = count($astart) > 1 ? $astart[1] : '';
$previousCrew = $bookingProcessBooking->getCrew();
$previousDateStart = $bookingProcessBooking->getDateStart();
$previousDateEnd = $bookingProcessBooking->getDateEnd();
$isValueNull = true;
$date = null;
$available_times = [];
try {
$adate = explode('-', $sdate);
if (count($adate) < 3) {
throw new \Exception('Invalid date');
}
$idateyear = intval($adate[0]);
$idatemonth = intval($adate[1]);
$idateday = intval($adate[2]);
$date = \DateTime::createFromFormat('Y-m-d', $sdate);
switch ($sstarttype) {
case 'gap':
{
$sscheduletype = $sstart;
$available_times = $this->ptimeAvailability($date, $sscheduletype, $bookingProcessBooking);
$istarthour = 0;
$istartminute = 0;
foreach ($available_times as $available_time) {
$aoption = explode('|', $available_time);
if ($aoption[0] == 'time') {
$aaoption = explode(':', $aoption[1]);
$istarthour = intval($aaoption[0]);
$istartminute = intval($aaoption[1]);
break;
}
}
}
break;
case 'time':
default:
{
$sscheduletype = 'exact';
RoutezillaDebugger::setMark(false, 'START');
$available_times = $this->ptimeAvailability($date, $sscheduletype, $bookingProcessBooking);
RoutezillaDebugger::setMark(false, [
'label' => 'CHECKPOINT 1',
'$available_times' => $available_times
]);
$astart = explode(':', $sstart);
if (count($astart) < 2) {
throw new \Exception('Invalid time');
}
$istarthour = intval($astart[0]);
$istartminute = intval($astart[1]);
}
break;
}
$isValueNull = false;
} catch (\Throwable $throwable) {
$isValueNull = true;
}
if (!$isValueNull) {
if ($bookingProcessBooking->getDateStart() == null) {
$bookingProcessBooking->setDateStart(new \DateTime());
}
$bookingProcessBooking->getDateStart()->setDate(
$idateyear,
$idatemonth,
$idateday
);
$bookingProcessBooking->getDateStart()->setTime(
$istarthour,
$istartminute
);
$bookingProcessBooking->setDateStart(clone $bookingProcessBooking->getDateStart());
$bookingProcessBooking->setScheduleType($sscheduletype);
if ($sscheduletype == 'exact') {
$bookingProcessBooking->setScheduleStatus('locked');
} else {
//$bookingProcessBooking->setScheduleStatus('unlocked');
$bookingProcessBooking->setScheduleStatus('locked');
}
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
$start = clone $bookingProcessBooking->getDateStart();
$start->setTime(0, 0);
$start->modify('-1 day');
$end = clone $start;
$end->modify('+2 days');
$bookingProcessBooking->setDateEnd($this->endTimeCalculator->getEndTimeForProcess($bookingProcessBooking));
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
$this->scheduler->setRange($start, $end);
$availableCrew = $this->scheduler->getAvailableCrewForProcess($bookingProcessBooking, $this->client);
RoutezillaDebugger::setMark(false, [
'label' => 'CREWS',
$availableCrew
]);
//RoutezillaDebugger::stop();
//dd($availableCrew != null ? $availableCrew->getId() : '-- NULL --');
if ($availableCrew == null) {
if ($previousCrew != null && $previousDateStart != null && $previousDateEnd != null) {
$dtup = clone ($previousDateStart);
$dtup->setTime(0, 0, 0);
$this->scheduleAvailabilityCMMVP1Service->buildScheduleAvailability($bookingProcessBooking->getClient(), $previousCrew, $dtup);
}
throw new \Exception("Date / Time not available anymore");
}
$bookingProcessBooking->setCrew($availableCrew);
$additionalMinutes = $this->endTimeCalculator->getAdditionalMinutesForProcess($bookingProcessBooking);
$bookingProcessBooking->setAdditionalMinutes($additionalMinutes);
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
$bookableHours = $this->getBookableHours($request);
$hour = $bookingProcessBooking->getDateStart();
if ($previousCrew != null && $previousDateStart != null && $previousDateEnd != null) {
$dtup = clone ($previousDateStart);
$dtup->setTime(0, 0, 0);
$this->scheduleAvailabilityCMMVP1Service->buildScheduleAvailability($bookingProcessBooking->getClient(), $previousCrew, $dtup);
}
if ($bookingProcessBooking->getCrew() != null) {
$dtu = clone ($bookingProcessBooking->getDateStart());
$dtu->setTime(0, 0, 0);
$this->scheduleAvailabilityCMMVP1Service->buildScheduleAvailability($bookingProcessBooking->getClient(), $bookingProcessBooking->getCrew(), $dtu);
}
// if (!in_array($hour, $bookableHours)) {
// throw new \Exception("Date / Time not available anymore");
// }
if (!in_array($ssstart, $available_times)) {
throw new \Exception("Date / Time not available anymore");
}
} else if ($previousCrew != null && $previousDateStart != null && $previousDateEnd != null) {
$dtup = clone ($previousDateStart);
$dtup->setTime(0, 0, 0);
$this->scheduleAvailabilityCMMVP1Service->buildScheduleAvailability($bookingProcessBooking->getClient(), $previousCrew, $dtup);
}
return true;
}
public function doStepInputContact($request, $bookingProcess) {
$now = new \DateTime();
$bookingProcessBooking = $bookingProcess->getBooking();
$bookingProcessBookingLocation = $bookingProcessBooking->getLocation();
if ($this->getUser() != null) {
$bookingProcessBooking->setNotes($request->request->get('admin-notes'));
}
#$customer_id = $request->request->get('customer-id');
$customer = $bookingProcess->getBooking()->getCustomer();
if ($customer == null) {
$customer = new BookingProcessCustomer();
$bookingProcessBooking->setCustomer($customer);
}
$customer->setEmail($request->request->get('customer-email'));
$customer->setName($request->request->get('customer-name'));
$customer->setPhone($request->request->get('customer-phone'));
$customer->setPhoneCanonical($request->request->get('customer-phone'));
$customer->setClient($this->client);
$customer->setDeleted(false);
$customer->setPhoneDescription('');
$location = $customer->getLocation();
if ($location == null) {
$location = new BookingProcessLocation();
$customer->setLocation($location);
}
if ($bookingProcessBooking->getServiceType() === 'fixed') {
$location->setStreet('');
$location->setCity('');
$location->setCode('');
$location->setProvince('');
$location->setCountry('');
$location->setLatitude(null);
$location->setLongitude(null);
$location->setLine2('');
$location->setInput('');
$location->setFormattedAddress('');
} else {
$location->setStreet($bookingProcessBookingLocation->getStreet());
$location->setCity($bookingProcessBookingLocation->getCity());
$location->setCode($bookingProcessBookingLocation->getCode());
$location->setProvince($bookingProcessBookingLocation->getProvince());
$location->setCountry($bookingProcessBookingLocation->getCountry());
$location->setLatitude($bookingProcessBookingLocation->getLatitude());
$location->setLongitude($bookingProcessBookingLocation->getLongitude());
$location->setLine2($bookingProcessBookingLocation->getLine2());
$location->setInput($bookingProcessBookingLocation->getInput());
$location->setFormattedAddress($bookingProcessBookingLocation->getFormattedAddress());
}
$billing = null;
$billing_location = null;
$isBillingSame = ($request->request->get('customer-billing-same') != null);
if ($isBillingSame) {
$billing = $customer->getBilling();
if ($billing != null) {
$customer->setBilling(null);
$this->entityManager->remove($billing);
$this->entityManager->flush();
}
$billing = new BookingProcessCustomerBilling();
$billing_location = new BookingProcessLocation();
$billing->setLocation($billing_location);
$billing_location->setStreet($location->getStreet());
$billing_location->setCity($location->getCity());
$billing_location->setCode($location->getCode());
$billing_location->setProvince($location->getProvince());
$billing_location->setCountry($location->getCountry());
$billing_location->setLatitude($location->getLatitude());
$billing_location->setLongitude($location->getLongitude());
$billing_location->setLine2($location->getLine2());
$billing_location->setInput($location->getInput());
$billing_location->setFormattedAddress($location->getFormattedAddress());
$billing->setName($customer->getName());
$billing->setPhone($customer->getPhone());
$billing->setEmail($customer->getEmail());
$customer->setBilling($billing);
} else {
$billing = $customer->getBilling();
if ($billing == null) {
$billing = new BookingProcessCustomerBilling();
$billing_location = new BookingProcessLocation();
$billing->setLocation($billing_location);
}
$customer->setBilling($billing);
}
if ($billing != null) {
if ($billing_location != null) {
$this->entityManager->persist($billing_location);
}
$this->entityManager->persist($billing);
}
$this->entityManager->persist($location);
$this->entityManager->persist($customer);
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
return true;
}
public function doStepInputBilling($request, $bookingProcess) {
$now = new \DateTime();
if (!$bookingProcess || !$bookingProcess->getBooking() || !$bookingProcess->getBooking()->getCustomer() || !$bookingProcess->getBooking()->getCustomer()->getBilling() || !$bookingProcess->getBooking()->getCustomer()->getBilling()->getLocation()) {
return false;
}
$bookingProcessBooking = $bookingProcess->getBooking();
$bookingProcessBookingCustomer = $bookingProcessBooking->getCustomer();
$bookingProcessBookingCustomerBilling = $bookingProcessBookingCustomer->getBilling();
$bookingProcessBookingCustomerBillingLocation = $bookingProcessBookingCustomerBilling->getLocation();
$bookingProcessBookingCustomerBillingLocation->setStreet($request->request->get('street'));
$bookingProcessBookingCustomerBillingLocation->setCity($request->request->get('city'));
$bookingProcessBookingCustomerBillingLocation->setCode($request->request->get('code'));
$bookingProcessBookingCustomerBillingLocation->setProvince($request->request->get('province'));
$bookingProcessBookingCustomerBillingLocation->setCountry($request->request->get('country'));
$bookingProcessBookingCustomerBillingLocation->setLatitude(doubleval($request->request->get('latitude')));
$bookingProcessBookingCustomerBillingLocation->setLongitude(doubleval($request->request->get('longitude')));
$bookingProcessBookingCustomerBillingLocation->setLine2($request->request->get('line2'));
$bookingProcessBookingCustomerBillingLocation->setInput('');
$bookingProcessBookingCustomerBillingLocation->setFormattedAddress('');
$bookingProcessBookingCustomerBilling->setName($request->request->get('name'));
$bookingProcessBookingCustomerBilling->setPhone($request->request->get('phone'));
$bookingProcessBookingCustomerBilling->setEmail($request->request->get('email'));
$this->entityManager->persist($bookingProcessBookingCustomerBillingLocation);
$this->entityManager->persist($bookingProcessBookingCustomerBilling);
$this->entityManager->flush();
return true;
}
public function doStepConfirm($request, $bookingProcess) {
$now = new \DateTime();
// TODO - IMPLEMENT COMMIT ON EDIT
switch ($bookingProcess->getType()) {
case "create":
{
$bookingProcessBooking = $bookingProcess->getBooking();
$bookingProcessLocation = $bookingProcessBooking->getLocation();
$bookingProcessCustomer = $bookingProcessBooking->getCustomer();
$bookingProcessCustomerLocation = $bookingProcessCustomer->getLocation();
$customer = $this->customerRepository->findLastCustomerEmail($bookingProcessCustomer->getEmail());
if ($customer !== null) {
$bookingProcess->setStatus("commit-confirm");
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
try {
$this->confirmationMailerForProcess->send($bookingProcessBooking);
}
catch (TransportException $e) {
//$this->emailErrors[] = 'Failed to send you an e-mail confirmation at ' . htmlspecialchars($customer->getEmail()) . '. It seems that this e-mail is not valid.';
//$result = self::FAILED_TO_SEND_EMAIL;
}
// try {
// $this->confirmationMailerForProcess->sendSMS($booking);
// }
// catch (\Throwable $e) {
// //$this->emailErrors[] = 'Failed to send you an SMS confirmation to ' . htmlspecialchars($customer->getPhone()) . '.';
// //$result = self::FAILED_TO_SEND_EMAIL;
// }
return 'commit-confirm';
} else {
return $this->doStepCommit($request, $bookingProcess) ? 'commit-success' : 'commit-failure';
}
}
break;
case "edit":
{
$bookingProcessBooking = $bookingProcess->getBooking();
$bookingProcessLocation = $bookingProcessBooking->getLocation();
$bookingProcessCustomer = $bookingProcessBooking->getCustomer();
$bookingProcessCustomerLocation = $bookingProcessCustomer->getLocation();
$booking = $bookingProcess->getMaterialBooking();
if ($booking == null) {
$booking = new Booking();
}
$customer = $this->customerRepository->findLastCustomerEmail($bookingProcessCustomer->getEmail());
if ($booking->getCustomer() !== null && $customer !== null && $booking->getCustomer()->getId() !== $customer->getId()) {
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
try {
$this->confirmationMailerForProcess->send($bookingProcessBooking);
}
catch (TransportException $e) {
//$this->emailErrors[] = 'Failed to send you an e-mail confirmation at ' . htmlspecialchars($customer->getEmail()) . '. It seems that this e-mail is not valid.';
//$result = self::FAILED_TO_SEND_EMAIL;
}
// try {
// $this->confirmationMailerForProcess->sendSMS($booking);
// }
// catch (\Throwable $e) {
// //$this->emailErrors[] = 'Failed to send you an SMS confirmation to ' . htmlspecialchars($customer->getPhone()) . '.';
// //$result = self::FAILED_TO_SEND_EMAIL;
// }
return 'commit-confirm';
} else {
return $this->doStepCommit($request, $bookingProcess) ? 'commit-success' : 'commit-failure';
}
}
break;
}
}
public function doStepCommit($request, $bookingProcess) {
$now = new \DateTime();
// TODO - IMPLEMENT COMMIT ON EDIT
switch ($bookingProcess->getType()) {
case "create":
{
$bookingProcessBooking = $bookingProcess->getBooking();
$bookingProcessLocation = $bookingProcessBooking->getLocation();
$bookingProcessCustomer = $bookingProcessBooking->getCustomer();
$bookingProcessCustomerLocation = $bookingProcessCustomer->getLocation();
$booking = new Booking();
$customer = null;
$isnewcustomer = false;
$customer_mode_find = $this->client->getPropertyValue('booking.customer.mode.find');
if (!empty($customer_mode_find) && in_array($customer_mode_find, ['true', '1'])) {
$customer = $this->customerRepository->findLastCustomerEmail($bookingProcessCustomer->getEmail());
if ($customer === null) {
$customer = new Customer();
$isnewcustomer = true;
}
} else {
$customer = new Customer();
$isnewcustomer = true;
}
$customer_location = null;
if ($isnewcustomer || $customer->getLocation() === null) {
$customer_location = new Location();
} else {
$customer_location = $customer->getLocation();
}
$customer_location->setStreet($bookingProcessCustomerLocation->getStreet());
$customer_location->setCity($bookingProcessCustomerLocation->getCity());
$customer_location->setProvince($bookingProcessCustomerLocation->getProvince());
$customer_location->setCountry($bookingProcessCustomerLocation->getCountry());
$customer_location->setLatitude($bookingProcessCustomerLocation->getLatitude());
$customer_location->setLongitude($bookingProcessCustomerLocation->getLongitude());
$customer_location->setLine2($bookingProcessCustomerLocation->getLine2());
$customer_location->setCode($bookingProcessCustomerLocation->getCode());
$customer_billing_location = null;
$customer_billing = null;
$bookingProcessBookingCustomerBilling = $bookingProcessCustomer->getBilling();
if ($bookingProcessBookingCustomerBilling != null) {
$bookingProcessBookingCustomerBillingLocation = $bookingProcessBookingCustomerBilling->getLocation();
if ($bookingProcessBookingCustomerBillingLocation != null) {
$customer_billing_location = $isnewcustomer || $customer->getBilling() === null ? new Location() : $customer->getBilling()->getLocation();
$customer_billing_location->setStreet($bookingProcessBookingCustomerBillingLocation->getStreet());
$customer_billing_location->setCity($bookingProcessBookingCustomerBillingLocation->getCity());
$customer_billing_location->setProvince($bookingProcessBookingCustomerBillingLocation->getProvince());
$customer_billing_location->setCountry($bookingProcessBookingCustomerBillingLocation->getCountry());
$customer_billing_location->setLatitude($bookingProcessBookingCustomerBillingLocation->getLatitude());
$customer_billing_location->setLongitude($bookingProcessBookingCustomerBillingLocation->getLongitude());
$customer_billing_location->setLine2($bookingProcessBookingCustomerBillingLocation->getLine2());
$customer_billing_location->setCode($bookingProcessBookingCustomerBillingLocation->getCode());
}
$customer_billing = $isnewcustomer || $customer->getBilling() === null ? new CustomerBilling() : $customer->getBilling();
$customer_billing->setLocation($customer_billing_location);
$customer_billing->setName($bookingProcessBookingCustomerBilling->getName());
$customer_billing->setEmail($bookingProcessBookingCustomerBilling->getEmail());
$customer_billing->setPhone($bookingProcessBookingCustomerBilling->getPhone());
$customer_billing->setPhoneCanonical($bookingProcessBookingCustomerBilling->getPhoneCanonical());
}
$customer->setLocation($customer_location);
if ($customer_billing != null) {
$customer->setBilling($customer_billing);
}
$customer->setEmail($bookingProcessCustomer->getEmail());
$customer->setName($bookingProcessCustomer->getName());
$customer->setPhone($bookingProcessCustomer->getPhone());
$customer->setPhoneCanonical($bookingProcessCustomer->getPhoneCanonical());
$customer->setClient($bookingProcessCustomer->getClient());
$customer->setDeleted($bookingProcessCustomer->getDeleted());
$customer->setPhoneDescription($bookingProcessCustomer->getPhoneDescription());
$location = new Location();
$location->setStreet($bookingProcessLocation->getStreet());
$location->setCity($bookingProcessLocation->getCity());
$location->setProvince($bookingProcessLocation->getProvince());
$location->setCountry($bookingProcessLocation->getCountry());
$location->setLatitude($bookingProcessLocation->getLatitude());
$location->setLongitude($bookingProcessLocation->getLongitude());
$location->setLine2($bookingProcessLocation->getLine2());
$location->setCode($bookingProcessLocation->getCode());
$booking->setScope('cm_mvp1');
$booking->setClient($bookingProcessBooking->getClient());
$booking->setCustomer($customer);
$booking->setService($bookingProcessBooking->getService());
$booking->setLocation($location);
$booking->setServiceType($bookingProcessBooking->getServiceType());
$booking->setSelectedRegion($bookingProcessBooking->getSelectedRegion());
$booking->setCrew($bookingProcessBooking->getCrew());
//$booking->setRadius($bookingProcessBooking->getRadius());
$booking->setDateStart($bookingProcessBooking->getDateStart());
$booking->setDateEnd($bookingProcessBooking->getDateEnd());
$booking->setScheduleType($bookingProcessBooking->getScheduleType());
$booking->setScheduleStatus($bookingProcessBooking->getScheduleStatus());
$booking->setStatus(BookingStatus::STATUS_ASSIGNED);
$booking->setAdditionalInformation($bookingProcessBooking->getAdditionalInformation());
$booking->setNotes($bookingProcessBooking->getNotes());
$booking->setDatePosted(clone $now);
$booking->setDateUpdated(clone $now);
//$booking->setUser(null);
$booking->setUser($bookingProcessBooking->getUser());
$booking->setAdditionalMinutes($bookingProcessBooking->getAdditionalMinutes());
$bookingProcessBookingRegions = $bookingProcessBooking->getRegions();
foreach ($bookingProcessBookingRegions as $bookingProcessBookingRegion) {
$booking->addRegion($bookingProcessBookingRegion);
}
$bookingProcessBookingServiceAnswers = $bookingProcessBooking->getBookingProcessBookingServiceAnswers();
foreach ($bookingProcessBookingServiceAnswers as $bookingProcessBookingServiceAnswer) {
$field = new BookingServiceField();
$field->setBooking($booking);
$field->setField($bookingProcessBookingServiceAnswer->getField());
$field->setSlug($bookingProcessBookingServiceAnswer->getSlug());
$field->setAnswer($bookingProcessBookingServiceAnswer->getAnswer());
$booking->addField($field);
}
if ($customer_billing_location != null) {
$customer_billing_location->setKeepChanges(true);
$this->entityManager->persist($customer_billing_location);
}
if ($customer_billing != null) {
$this->entityManager->persist($customer_billing);
}
if ($customer_location != null) {
$customer_location->setKeepChanges(true);
$this->entityManager->persist($customer_location);
}
if ($customer != null) {
$this->entityManager->persist($customer);
}
if ($location != null) {
$this->entityManager->persist($location);
}
if ($booking != null) {
$this->entityManager->persist($booking);
}
$bookingProcess->setMaterialBooking($booking);
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
$this->radiusUpdater->setEntityManager($this->entityManager);
$this->radiusUpdater->updateRadius($booking, null, $booking->getCrew());
if ($this->getUser() == null) {
$customerMailer = $this->confirmationMailer;
try {
$customerMailer->send($booking);
}
catch (TransportException $e) {
//$this->emailErrors[] = 'Failed to send you an e-mail confirmation at ' . htmlspecialchars($customer->getEmail()) . '. It seems that this e-mail is not valid.';
//$result = self::FAILED_TO_SEND_EMAIL;
}
try {
$customerMailer->sendSMS($booking);
}
catch (\Throwable $e) {
//$this->emailErrors[] = 'Failed to send you an SMS confirmation to ' . htmlspecialchars($customer->getPhone()) . '.';
//$result = self::FAILED_TO_SEND_EMAIL;
}
}
$companyMailer = $this->notificationMailer;
try {
$companyMailer->send($booking);
}
catch (TransportException $e) {
//$this->emailErrors[] = 'Failed to send an email notification to the company. It seems that there is some issue with this compny email address. You may contact them by phone to make sure they received your request.';
//$result = self::FAILED_TO_SEND_EMAIL;
}
if ($booking->getCrew() != null) {
$dtu = clone ($booking->getDateStart());
$dtu->setTime(0, 0, 0);
$this->scheduleAvailabilityCMMVP1Service->buildScheduleAvailability($booking->getClient(), $booking->getCrew(), $dtu);
}
// FINAL TASKS
{
if ( $this->googleClient->setRedirectUrl(
$this->getGoogleOauthRedirectUrl()
)->authenticate($request->getUri())
) {
try{
$this->googleCalendarModel->setGoogleModels(
new \Google_Service_Calendar($this->googleClient->getClient()),
$this->getWatchGoogleChannelParams($this->client)
);
$this->addOrUpdateGoogleEvent(
$request, $this->googleClient, $this->googleCalendarModel, $booking
);
}
catch(\Google\Service\Exception $ex){
}
}
$crew = $booking->getCrew();
if ($crew) {
$workers = $this->workerEnityModel->findByCrew($crew);
foreach($workers as $worker) {
$workerEmail = $worker->getUser()->getEmail();
if ($worker->isNotify()) {
try {
$this->googleCalendarNotificationMailer->send(
$booking, $worker
);
}
catch (TransportException $e) {
error_log(__FILE__ . ': ' . __LINE__ . ': ignored email error ');
}
}
}
}
}
$_rwg_token = $request->cookies->get('_rwg_token');
if ($_rwg_token != null) {
$gmbeurls = [
'production' => 'https://www.google.com/maps/conversion/collect',
'sandbox' => 'https://www.google.com/maps/conversion/debug/collect'
];
$gmbeaccid = '20001772';
try {
$response = $this->httpClient->request(
'POST',
$gmbeurls['production'],
[
'headers' => [
'Content-Type' => 'application/json'
],
'body' => json_encode([
'conversion_partner_id' => $gmbeaccid,
'rwg_token' => $_rwg_token,
'merchant_changed' => 2
])
]
);
} catch (\Throwable $e) {
// NOTHING
}
}
//$this->webhookService->setClient(1320);
try {
$this->webhookService->__trigger_event_create_booking($booking);
} catch (\Throwable $throwable) {
// NOTHING
if ($this->client !== null && $this->client->getEnvType() !== 'production') {
dd([
'message' => $throwable->getMessage(),
'file' => $throwable->getFile(),
'line' => $throwable->getLine(),
'trace' => $throwable->getTrace()
]);
}
}
return true;
}
break;
case "edit":
{
$bookingProcessBooking = $bookingProcess->getBooking();
$bookingProcessLocation = $bookingProcessBooking->getLocation();
$bookingProcessCustomer = $bookingProcessBooking->getCustomer();
$bookingProcessCustomerLocation = $bookingProcessCustomer->getLocation();
$booking = $bookingProcess->getMaterialBooking();
if ($booking == null) {
$booking = new Booking();
}
$previousCrew = $booking->getCrew();
$previousDateStart = $booking->getDateStart();
$previousDateEnd = $booking->getDateEnd();
$crew = $booking->getCrew();
$customer = null;
$isnewcustomer = false;
$customer_mode_find = $this->client->getPropertyValue('booking.customer.mode.find');
if (!empty($customer_mode_find) && in_array($customer_mode_find, ['true', '1'])) {
$customer = $this->customerRepository->findLastCustomerEmail($bookingProcessCustomer->getEmail());
if ($customer === null) {
$customer = new Customer();
$isnewcustomer = true;
}
} else {
$customer = new Customer();
$isnewcustomer = true;
}
$customer_location = null;
if ($isnewcustomer || $customer->getLocation() === null) {
$customer_location = new Location();
} else {
$customer_location = $customer->getLocation();
}
$customer_location->setStreet($bookingProcessCustomerLocation->getStreet());
$customer_location->setCity($bookingProcessCustomerLocation->getCity());
$customer_location->setProvince($bookingProcessCustomerLocation->getProvince());
$customer_location->setCountry($bookingProcessCustomerLocation->getCountry());
$customer_location->setLatitude($bookingProcessCustomerLocation->getLatitude());
$customer_location->setLongitude($bookingProcessCustomerLocation->getLongitude());
$customer_location->setLine2($bookingProcessCustomerLocation->getLine2());
$customer_location->setCode($bookingProcessCustomerLocation->getCode());
$customer_billing_location = null;
$customer_billing = null;
$bookingProcessBookingCustomerBilling = $bookingProcessCustomer->getBilling();
if ($bookingProcessBookingCustomerBilling != null) {
$bookingProcessBookingCustomerBillingLocation = $bookingProcessBookingCustomerBilling->getLocation();
if ($bookingProcessBookingCustomerBillingLocation != null) {
$customer_billing_location = $isnewcustomer || $customer->getBilling() === null ? new Location() : $customer->getBilling()->getLocation();
$customer_billing_location->setStreet($bookingProcessBookingCustomerBillingLocation->getStreet());
$customer_billing_location->setCity($bookingProcessBookingCustomerBillingLocation->getCity());
$customer_billing_location->setProvince($bookingProcessBookingCustomerBillingLocation->getProvince());
$customer_billing_location->setCountry($bookingProcessBookingCustomerBillingLocation->getCountry());
$customer_billing_location->setLatitude($bookingProcessBookingCustomerBillingLocation->getLatitude());
$customer_billing_location->setLongitude($bookingProcessBookingCustomerBillingLocation->getLongitude());
$customer_billing_location->setLine2($bookingProcessBookingCustomerBillingLocation->getLine2());
$customer_billing_location->setCode($bookingProcessBookingCustomerBillingLocation->getCode());
}
$customer_billing = $isnewcustomer || $customer->getBilling() === null ? new CustomerBilling() : $customer->getBilling();
$customer_billing->setLocation($customer_billing_location);
$customer_billing->setName($bookingProcessBookingCustomerBilling->getName());
$customer_billing->setEmail($bookingProcessBookingCustomerBilling->getEmail());
$customer_billing->setPhone($bookingProcessBookingCustomerBilling->getPhone());
$customer_billing->setPhoneCanonical($bookingProcessBookingCustomerBilling->getPhoneCanonical());
}
$customer->setLocation($customer_location);
if ($customer_billing != null) {
$customer->setBilling($customer_billing);
}
$customer->setEmail($bookingProcessCustomer->getEmail());
$customer->setName($bookingProcessCustomer->getName());
$customer->setPhone($bookingProcessCustomer->getPhone());
$customer->setPhoneCanonical($bookingProcessCustomer->getPhoneCanonical());
$customer->setClient($bookingProcessCustomer->getClient());
$customer->setDeleted($bookingProcessCustomer->getDeleted());
$customer->setPhoneDescription($bookingProcessCustomer->getPhoneDescription());
$location = new Location();
$location->setStreet($bookingProcessLocation->getStreet());
$location->setCity($bookingProcessLocation->getCity());
$location->setProvince($bookingProcessLocation->getProvince());
$location->setCountry($bookingProcessLocation->getCountry());
$location->setLatitude($bookingProcessLocation->getLatitude());
$location->setLongitude($bookingProcessLocation->getLongitude());
$location->setLine2($bookingProcessLocation->getLine2());
$location->setCode($bookingProcessLocation->getCode());
$booking->setScope('cm_mvp1');
$booking->setClient($bookingProcessBooking->getClient());
$booking->setCustomer($customer);
$booking->setService($bookingProcessBooking->getService());
$booking->setLocation($location);
$booking->setServiceType($bookingProcessBooking->getServiceType());
$booking->setSelectedRegion($bookingProcessBooking->getSelectedRegion());
$booking->setCrew($bookingProcessBooking->getCrew());
//$booking->setRadius($bookingProcessBooking->getRadius());
$booking->setDateStart($bookingProcessBooking->getDateStart());
$booking->setDateEnd($bookingProcessBooking->getDateEnd());
$booking->setScheduleType($bookingProcessBooking->getScheduleType());
$booking->setScheduleStatus($bookingProcessBooking->getScheduleStatus());
$booking->setStatus(BookingStatus::STATUS_ASSIGNED);
$booking->setAdditionalInformation($bookingProcessBooking->getAdditionalInformation());
$booking->setNotes($bookingProcessBooking->getNotes());
//$booking->setDatePosted(clone $now);
$booking->setDateUpdated(clone $now);
//$booking->setUser(null);
$booking->setAdditionalMinutes($bookingProcessBooking->getAdditionalMinutes());
$bookingProcessBookingRegions = $bookingProcessBooking->getRegions();
$booking->getRegions()->clear();
foreach ($bookingProcessBookingRegions as $bookingProcessBookingRegion) {
$booking->addRegion($bookingProcessBookingRegion);
}
$bookingProcessBookingServiceAnswers = $bookingProcessBooking->getBookingProcessBookingServiceAnswers();
foreach ($bookingProcessBookingServiceAnswers as $bookingProcessBookingServiceAnswer) {
$field = new BookingServiceField();
$field->setBooking($booking);
$field->setField($bookingProcessBookingServiceAnswer->getField());
$field->setSlug($bookingProcessBookingServiceAnswer->getSlug());
$field->setAnswer($bookingProcessBookingServiceAnswer->getAnswer());
$booking->addField($field);
}
if ($customer_billing_location != null) {
$customer_billing_location->setKeepChanges(true);
$this->entityManager->persist($customer_billing_location);
}
if ($customer_billing != null) {
$this->entityManager->persist($customer_billing);
}
if ($customer_location != null) {
$customer_location->setKeepChanges(true);
$this->entityManager->persist($customer_location);
}
if ($customer != null) {
$this->entityManager->persist($customer);
}
if ($location != null) {
$this->entityManager->persist($location);
}
if ($booking != null) {
$this->entityManager->persist($booking);
}
$bookingProcess->setMaterialBooking($booking);
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
$this->radiusUpdater->setEntityManager($this->entityManager);
$this->radiusUpdater->updateRadius($booking, $crew, $booking->getCrew());
$customerMailer = $this->changeMailer;
try {
$customerMailer->send($booking);
}
catch (TransportException $e) {
//$this->emailErrors[] = 'Failed to send you an e-mail confirmation at ' . htmlspecialchars($customer->getEmail()) . '. It seems that this e-mail is not valid.';
//$result = self::FAILED_TO_SEND_EMAIL;
}
try {
$customerMailer->sendSMS($booking);
}
catch (\Throwable $e) {
//$this->emailErrors[] = 'Failed to send you an SMS confirmation to ' . htmlspecialchars($customer->getPhone()) . '.';
//$result = self::FAILED_TO_SEND_EMAIL;
}
$companyMailer = $this->notificationMailer;
try {
$companyMailer->send($booking);
}
catch (TransportException $e) {
//$this->emailErrors[] = 'Failed to send an email notification to the company. It seems that there is some issue with this compny email address. You may contact them by phone to make sure they received your request.';
//$result = self::FAILED_TO_SEND_EMAIL;
}
if ($previousCrew != null && $previousDateStart != null && $previousDateEnd != null) {
$dtup = clone ($previousDateStart);
$dtup->setTime(0, 0, 0);
$this->scheduleAvailabilityCMMVP1Service->buildScheduleAvailability($booking->getClient(), $previousCrew, $dtup);
}
if ($booking->getCrew() != null) {
$dtu = clone ($booking->getDateStart());
$dtu->setTime(0, 0, 0);
$this->scheduleAvailabilityCMMVP1Service->buildScheduleAvailability($booking->getClient(), $booking->getCrew(), $dtu);
}
// FINAL TASKS
{
if ( $this->googleClient->setRedirectUrl(
$this->getGoogleOauthRedirectUrl()
)->authenticate($request->getUri())
) {
try{
$this->googleCalendarModel->setGoogleModels(
new \Google_Service_Calendar($this->googleClient->getClient()),
$this->getWatchGoogleChannelParams($this->client)
);
$this->addOrUpdateGoogleEvent(
$request, $this->googleClient, $this->googleCalendarModel, $booking
);
if ($previousCrew) {
$this->googleCalendarModel->removeBookingEventFromCrew(
$booking, $previousCrew
);
}
}
catch(\Google\Service\Exception $ex){
}
}
$crew = $booking->getCrew();
if ($crew) {
$workers = $this->workerEnityModel->findByCrew($crew);
foreach($workers as $worker) {
$workerEmail = $worker->getUser()->getEmail();
if ($worker->isNotify()) {
try {
$this->googleCalendarNotificationMailer->send(
$booking, $worker
);
}
catch (TransportException $e) {
error_log(__FILE__ . ': ' . __LINE__ . ': ignored email error ');
}
}
}
}
}
if ($previousDateStart !== null && $previousDateEnd && $booking->getDateStart() !== null && $booking->getDateEnd() !== null && ($previousDateStart !== $booking->getDateStart() || $previousDateEnd !== $booking->getDateEnd())) {
try {
$this->webhookService->__trigger_event_reschedule_booking($booking);
} catch (\Throwable $throwable) {
// NOTHING
}
}
try {
$this->webhookService->__trigger_event_update_booking($booking);
} catch (\Throwable $throwable) {
// NOTHING
}
return true;
}
break;
}
}
public function doStepCommitConfirm($request, $bookingProcess) {
$now = new \DateTime();
$bookingProcess->setStatus('commit-confirm');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
return true;
}
public function doStepComplete($request, $bookingProcess) {
$now = new \DateTime();
$bookingProcess->setStatus('complete');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
return true;
}
private function doStepRedirectionPOST($request, $bookingProcess) {
$go = $request->request->get('go');
$now = new \DateTime();
$embedded_status = $request->request->get('embedded-status');
if ($embedded_status != null) {
$bookingProcess->setEmbeddedStatus($embedded_status);
}
$show_header = $request->request->get('show-header');
if ($show_header != null) {
$bookingProcess->setShowHeader($show_header);
}
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
switch ($bookingProcess->getScreen()) {
case 'input-location-callback':
{
$b = false;
try {
$b = $this->doStepInputLocationCallback($request, $bookingProcess);
if (!$b) {
throw new \Exception("Unexpected error!");
}
$warningbody = json_encode([
'code' => 0,
'message' => '',
'trace' => null
]);
$bookingProcess->setWarningstatus(0);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
} catch (\Throwable $throwable) {
throw $throwable;
$warningbody = json_encode([
'code' => $throwable->getCode(),
'line' => $throwable->getLine(),
'file' => $throwable->getFile(),
'message' => $throwable->getMessage(),
'trace' => $throwable->getTrace()
]);
$bookingProcess->setWarningstatus(1);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
switch ($go) {
case 'previous':
case 'back';
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-location');
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
break;
case 'next':
default:
if ($b) {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'complete-callback');
return $this->redirect($this->generateUrl($this->screensmap['complete-callback']));
}
break;
}
return $this->redirect($this->generateUrl($this->screensmap['input-location-callback']));
}
break;
case 'input-location':
{
$b = false;
try {
$b = $this->doStepInputLocation($request, $bookingProcess);
if (!$b) {
throw new \Exception("Unexpected error!");
}
$warningbody = json_encode([
'code' => 0,
'message' => '',
'trace' => null
]);
$bookingProcess->setWarningstatus(0);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
} catch (\Throwable $throwable) {
$warningbody = json_encode([
'code' => $throwable->getCode(),
'line' => $throwable->getLine(),
'file' => $throwable->getFile(),
'message' => $throwable->getMessage(),
'trace' => $throwable->getTrace()
]);
$bookingProcess->setWarningstatus(1);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
switch ($go) {
case 'previous':
case 'back';
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-location');
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
break;
case 'next':
default:
if ($b) {
if ($request->request->get('type') == 'fixed') {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-service');
return $this->redirect($this->generateUrl($this->screensmap['input-service']));
} else {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-confirmlocation');
return $this->redirect($this->generateUrl($this->screensmap['input-confirmlocation']));
}
}
break;
}
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
}
break;
case 'input-confirmlocation':
{
$b = false;
try {
$b = $this->doStepInputConfirmLocation($request, $bookingProcess);
if (!$b) {
throw new \Exception("Unexpected error!");
}
$warningbody = json_encode([
'code' => 0,
'message' => '',
'trace' => null
]);
$bookingProcess->setWarningstatus(0);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
} catch (\Throwable $throwable) {
$warningbody = json_encode([
'code' => $throwable->getCode(),
'line' => $throwable->getLine(),
'file' => $throwable->getFile(),
'message' => $throwable->getMessage(),
'trace' => $throwable->getTrace()
]);
$bookingProcess->setWarningstatus(1);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
switch ($go) {
case 'previous':
case 'back';
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-location');
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
break;
case 'next':
default:
if ($b) {
if ($bookingProcess->getAllowedServices()) {
$arrayAllowedServices = explode(',', str_replace(', ', ',', $bookingProcess->getAllowedServices()));
if (count($arrayAllowedServices) == 1) {
$b = $this->doStepInputService($request, $bookingProcess, current($arrayAllowedServices));
if (!$b) {
throw new \Exception("Unexpected error!");
}
return $this->verifyServiceFieldsNext($bookingProcess);
}
}
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-service');
return $this->redirect($this->generateUrl($this->screensmap['input-service']));
}
break;
}
return $this->redirect($this->generateUrl($this->screensmap['input-confirmlocation']));
}
break;
case 'input-service':
{
$b = false;
try {
$b = $this->doStepInputService($request, $bookingProcess);
if (!$b) {
throw new \Exception("Unexpected error!");
}
$warningbody = json_encode([
'code' => 0,
'message' => '',
'trace' => null
]);
$bookingProcess->setWarningstatus(0);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
} catch (\Throwable $throwable) {
$warningbody = json_encode([
'code' => $throwable->getCode(),
'line' => $throwable->getLine(),
'file' => $throwable->getFile(),
'message' => $throwable->getMessage(),
'trace' => $throwable->getTrace()
]);
$bookingProcess->setWarningstatus(1);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
if ($b) {
switch ($go) {
case 'previous':
case 'back';
if ($bookingProcess->getBooking()->getServiceType() == 'fixed') {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-location');
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
} else {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-location');
return $this->redirect($this->generateUrl($this->screensmap['input-confirmlocation']));
}
break;
case 'next':
default:
$allfields = $bookingProcess->getBooking()->getService()->getFields();
$fields = [];
foreach ($allfields as $field) {
if ($field->getIsActive() && $field->getQuestion() != null && $field->getQuestion() != '') {
$fields[] = $field;
}
}
if (count($fields) > 0) {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-servicefields');
return $this->redirect($this->generateUrl($this->screensmap['input-servicefields']));
} else {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-datetime');
return $this->redirect($this->generateUrl($this->screensmap['input-datetime']));
}
break;
}
}
return $this->redirect($this->generateUrl($this->screensmap['input-service']));
}
break;
case 'input-servicefields':
{
$b = false;
try {
$b = $this->doStepInputServiceFields($request, $bookingProcess);
if (!$b) {
throw new \Exception("Unexpected error!");
}
$warningbody = json_encode([
'code' => 0,
'message' => '',
'trace' => null
]);
$bookingProcess->setWarningstatus(0);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
} catch (\Throwable $throwable) {
$warningbody = json_encode([
'code' => $throwable->getCode(),
'line' => $throwable->getLine(),
'file' => $throwable->getFile(),
'message' => $throwable->getMessage(),
'trace' => $throwable->getTrace()
]);
$bookingProcess->setWarningstatus(1);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
if ($b) {
switch ($go) {
case 'previous':
case 'back';
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-service');
return $this->redirect($this->generateUrl($this->screensmap['input-service']));
break;
case 'next':
default:
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-datetime');
return $this->redirect($this->generateUrl($this->screensmap['input-datetime']));
break;
}
}
return $this->redirect($this->generateUrl($this->screensmap['input-servicefields']));
}
break;
case 'input-schedule-type':
{
$b = false;
try {
$b = $this->doStepInputScheduleType($request, $bookingProcess);
if (!$b) {
throw new \Exception("Unexpected error!");
}
$warningbody = json_encode([
'code' => 0,
'message' => '',
'trace' => null
]);
$bookingProcess->setWarningstatus(0);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
} catch (\Throwable $throwable) {
$warningbody = json_encode([
'code' => $throwable->getCode(),
'line' => $throwable->getLine(),
'file' => $throwable->getFile(),
'message' => $throwable->getMessage(),
'trace' => $throwable->getTrace()
]);
$bookingProcess->setWarningstatus(1);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
if ($b) {
switch ($go) {
case 'previous':
case 'back';
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-servicefields');
return $this->redirect($this->generateUrl($this->screensmap['input-servicefields']));
break;
case 'next':
default:
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-datetime');
return $this->redirect($this->generateUrl($this->screensmap['input-datetime']));
break;
}
}
return $this->redirect($this->generateUrl($this->screensmap['input-schedule-type']));
}
break;
case 'input-datetime':
{
$b = false;
try {
$b = $this->doStepInputDateTime($request, $bookingProcess);
if (!$b) {
throw new \Exception("Unexpected error!");
}
$warningbody = json_encode([
'code' => 0,
'message' => '',
'trace' => null
]);
$bookingProcess->setWarningstatus(0);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
} catch (\Throwable $throwable) {
$warningbody = json_encode([
'code' => $throwable->getCode(),
'line' => $throwable->getLine(),
'file' => $throwable->getFile(),
'message' => $throwable->getMessage(),
'trace' => $throwable->getTrace()
]);
$bookingProcess->setWarningstatus(1);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
if ($b) {
switch ($go) {
case 'previous':
case 'back';
$allfields = $bookingProcess->getBooking()->getService()->getFields();
$fields = [];
foreach ($allfields as $field) {
if ($field->getIsActive() && $field->getQuestion() != null && $field->getQuestion() != '') {
$fields[] = $field;
}
}
if (count($fields) > 0) {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-servicefields');
return $this->redirect($this->generateUrl($this->screensmap['input-servicefields']));
} else {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-service');
return $this->redirect($this->generateUrl($this->screensmap['input-service']));
}
break;
case 'next':
default:
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-contact');
return $this->redirect($this->generateUrl($this->screensmap['input-contact']));
break;
}
}
return $this->redirect($this->generateUrl($this->screensmap['input-datetime']));
}
break;
case 'input-contact':
{
$b = false;
try {
$b = $this->doStepInputContact($request, $bookingProcess);
if (!$b) {
throw new \Exception("Unexpected error!");
}
$warningbody = json_encode([
'code' => 0,
'message' => '',
'trace' => null
]);
$bookingProcess->setWarningstatus(0);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
} catch (\Throwable $throwable) {
$warningbody = json_encode([
'code' => $throwable->getCode(),
'line' => $throwable->getLine(),
'file' => $throwable->getFile(),
'message' => $throwable->getMessage(),
'trace' => $throwable->getTrace()
]);
$bookingProcess->setWarningstatus(1);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
if ($b) {
switch ($go) {
case 'previous':
case 'back';
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-datetime');
return $this->redirect($this->generateUrl($this->screensmap['input-datetime']));
break;
case 'next':
default:
$isBillingSame = ($request->request->get('customer-billing-same') != null);
if ($isBillingSame) {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'commit');
return $this->redirect($this->generateUrl($this->screensmap['commit']));
} else {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-billing');
return $this->redirect($this->generateUrl($this->screensmap['input-billing']));
}
break;
}
}
return $this->redirect($this->generateUrl($this->screensmap['input-contact']));
}
break;
case 'input-billing':
{
$b = false;
try {
$b = $this->doStepInputBilling($request, $bookingProcess);
if (!$b) {
throw new \Exception("Unexpected error!");
}
$warningbody = json_encode([
'code' => 0,
'message' => '',
'trace' => null
]);
$bookingProcess->setWarningstatus(0);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
} catch (\Throwable $throwable) {
$warningbody = json_encode([
'code' => $throwable->getCode(),
'line' => $throwable->getLine(),
'file' => $throwable->getFile(),
'message' => $throwable->getMessage(),
'trace' => $throwable->getTrace()
]);
$bookingProcess->setWarningstatus(1);
$bookingProcess->setWarningbody($warningbody);
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
if ($b) {
switch ($go) {
case 'previous':
case 'back';
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-contact');
return $this->redirect($this->generateUrl($this->screensmap['input-contact']));
break;
case 'next':
default:
//$this->setGoToScreenOnBookingProcess($bookingProcess, 'commit');
//return $this->redirect($this->generateUrl($this->screensmap['commit']));
$this->setGoToScreenOnBookingProcess($bookingProcess, 'commit');
return $this->redirect($this->generateUrl($this->screensmap['commit']));
break;
}
}
return $this->redirect($this->generateUrl($this->screensmap['input-contact']));
}
break;
case 'complete':
{
//$b = $this->doStepComplete($request, $bookingProcess);
$b = true;
if ($b) {
switch ($go) {
case 'previous':
case 'back';
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-billing');
return $this->redirect($this->generateUrl($this->screensmap['input-billing']));
break;
case 'next':
default:
$this->setGoToScreenOnBookingProcess($bookingProcess, 'complete');
return $this->redirect($this->generateUrl($this->screensmap['complete']));
break;
}
}
return $this->redirect($this->generateUrl($this->screensmap['complete']));
}
break;
default:
{
//return $this->step_company($request);
//return $this->forward('App\Controller\SignUpController::step_company', array());
return new Response(
'INVALID STEP',
Response::HTTP_OK,
['content-type' => 'text/html']
);
}
}
}
/**
* @Route("/booking/process/cm/mvp1/step", name="booking_process_cm_mvp1_step")
*/
public function step(Request $request): Response
{
$bookingProcess = $this->checkBookingProcess($request);
if ($bookingProcess == null) {
$response = $this->redirect($this->generateUrl($this->screensmap['input-location']));
$this->unsetCookie($response);
return $response;
}
$screen = $request->request->get('screen');
if ($screen != null) {
$this->setGoToScreenOnBookingProcess($bookingProcess, $screen);
}
if ($request->getMethod() == 'POST') {
return $this->doStepRedirectionPOST($request, $bookingProcess);
} else {
return $this->doStepRedirectionGET($request, $bookingProcess);
}
}
/**
* @Route("/booking/process/cm/mvp1/iframe", name="booking_process_cm_mvp1_test_iframe")
*/
public function test_iframe(Request $request): Response
{
$response = $this->render('booking_process_cm_mvp1/test_iframe.html.twig', [
'controller_name' => 'BookingProcessController',
'client' => $this->client
]);
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/safari-fix", name="booking_process_cm_mvp1_safari_fix")
* @Route("/booking/process/safari-fix", name="booking_process_cm_mvp1_safari_fix_default", condition="(((context.getHost() not in %app.beta.clients%) and ('%booking_process.scope%' == 'cm_mvp1')) or ((context.getHost() in %app.beta.clients%) and ('%booking_process.beta.scope%' == 'cm_mvp1')))")
*/
public function safari_fix(Request $request): Response
{
$setCookie = false;
$bookingProcess = $this->checkBookingProcess($request);
if ($bookingProcess == null) {
$bookingProcess = $this->generateBookingProcess($request);
$setCookie = true;
}
$sreferrer = $request->query->get('sreferrer');
if ($sreferrer == null) {
$sreferrer = $this->generateUrl('booking_process_cm_mvp1_step_input_location');
}
$response = $this->redirect($sreferrer);
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
protected function checkCanBook(Request $request)
{
$bookingsPercent = $this->clientEntityModel->getBookingsPercent($this->client);
if ( $bookingsPercent >= 100 || $this->client->isExpired() ||
$this->client->isCanceled() || $this->client->isBlocked() ) {
// return $this->redirect(
// //$this->generateUrl('book_online_not_accepted')
// $this->client->getWebsite()
// );
return null;
} else {
return null;
}
}
/**
* @Route("/booking/process/cm/mvp1/step/input-location", name="booking_process_cm_mvp1_step_input_location")
* @Route("/cm/mvp1", name="booking_process_cm_mvp1_step_input_location_alt")
* @Route("/", name="booking_process_cm_mvp1_step_input_location_default", condition="(((context.getHost() not in %app.beta.clients%) and ('%booking_process.scope%' == 'cm_mvp1')) or ((context.getHost() in %app.beta.clients%) and ('%booking_process.beta.scope%' == 'cm_mvp1')))")
*/
public function step_input_location(Request $request, ContainerInterface $container): Response
{
$now = new \DateTime();
//$tesresult = $this->salesForceI360AppointmentsService->findContactByExternalId('somevalue');
//dd($tesresult);
if (strpos($request->server->get('HTTP_HOST'), $container->getParameter('orc_saas.login.domain')) === 0)
{
return $this->forward('orc_saas.controller.login:loginAction');
}
else if (strpos($request->server->get('HTTP_HOST'), $container->getParameter('orc_saas.admin.domain')) === 0) {
return new Response(
'<html><body>Welcome to the administration page!</body></html>'
);
}
try {
$this->getClient();
}
catch(NotFoundHttpException $e){
if ($container->getParameter('marketing_subdomain'). '.' .
$container->getParameter('domain_name') == $request->server->get('HTTP_HOST')
) {
return $this->redirect($this->generateUrl('app_marketing_index'));
}
else {
throw $e;
}
} catch (\Exception $e) {
dd(get_class($e));
}
$canBookResponse = $this->checkCanBook($request);
if ($canBookResponse != null) {
return $canBookResponse;
}
$setCookie = false;
$cpo = $this->assertBookingProcess($request);
$bookingProcess = $cpo['booking_process'];
$setCookie = $cpo['set_cookie'];
$message = $cpo['message'];
if ($message != null and $message != '') {
if (str_starts_with($message, '__redirect: ')) {
$url = substr($message, 12);
$this->doIncrementGmbClicks($request);
return $this->redirect($url);
}
$response = null;
if (str_starts_with($message, '__inactive: ')) {
$response = $this->render('booking_process_cm_mvp1/message_inactive.html.twig', [
'screen' => 'inactive',
'headersteps' => true,
'complete' => true,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => '',
'message' => substr($cpo['message'], 12)
]);
$this->doIncrementGmbClicks($request);
} else {
$response = $this->render('booking_process_cm_mvp1/message.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => $cpo['message']
]);
}
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
$o = $this->redirectOnInvalidStep($request, $bookingProcess, 'input-location');
if ($o != null) {
return $o;
} else {
$bookingProcess->setScreen('input-location');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
$warningbody = ($bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null);
$response = $this->render('booking_process_cm_mvp1/step_input_location.html.twig', [
'screen' => 'input-location',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'next' => $this->generateUrl($this->screensmap['input-confirmlocation']),
'client' => $this->client,
'regions' => $this->getRegionsGroupedByServiceType(),
'rawRegions' => $this->regionRepository->findByClient($this->client),
'bookingProcess' => $bookingProcess,
'displaywarning' => $warningbody != null && $warningbody->message != 'Location is out of bounds!' ? true : false,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $warningbody,
'ipStackInfo' => $this->ipStackInfo
]);
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
$this->addPreProcessHeaders($request, $response, $bookingProcess);
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/step/input-location-callback", name="booking_process_cm_mvp1_step_input_location_callback")
*/
public function step_input_location_callback(Request $request): Response
{
$now = new \DateTime();
$canBookResponse = $this->checkCanBook($request);
if ($canBookResponse != null) {
return $canBookResponse;
}
$cpo = $this->assertBookingProcess($request);
$bookingProcess = $cpo['booking_process'];
$setCookie = $cpo['set_cookie'];
$message = $cpo['message'];
if ($message != null and $message != '') {
if (str_starts_with($message, '__redirect: ')) {
$url = substr($message, 12);
$this->doIncrementGmbClicks($request);
return $this->redirect($url);
}
$response = null;
if (str_starts_with($message, '__inactive: ')) {
$response = $this->render('booking_process_cm_mvp1/message_inactive.html.twig', [
'screen' => 'inactive',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => '',
'message' => substr($cpo['message'], 12)
]);
$this->doIncrementGmbClicks($request);
} else {
$response = $this->render('booking_process_cm_mvp1/message.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => $cpo['message']
]);
}
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
if ($bookingProcess == null) {
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
} else {
$o = $this->redirectOnInvalidStep($request, $bookingProcess, 'input-location-callback', $cpo['set_cookie']);
if ($o != null) {
return $o;
} else {
$bookingProcess->setScreen('input-location-callback');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
}
$response = $this->render('booking_process_cm_mvp1/step_input_location_callback.html.twig', [
'screen' => 'input-location-callback',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'next' => $this->generateUrl($this->screensmap['input-confirmlocation']),
'nextlabel' => 'REQUEST CALLBACK',
'client' => $this->client,
'bookingProcess' => $bookingProcess,
'displaywarning' => false,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null,
'ipStackInfo' => $this->ipStackInfo
]);
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
$this->addPreProcessHeaders($request, $response, $bookingProcess);
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/step/input-confirmlocation", name="booking_process_cm_mvp1_step_input_confirmlocation")
*/
public function step_input_confirmlocation(Request $request): Response
{
$now = new \DateTime();
$canBookResponse = $this->checkCanBook($request);
if ($canBookResponse != null) {
return $canBookResponse;
}
$cpo = $this->assertBookingProcess($request);
$bookingProcess = $cpo['booking_process'];
$setCookie = $cpo['set_cookie'];
$message = $cpo['message'];
if ($message != null and $message != '') {
if (str_starts_with($message, '__redirect: ')) {
$url = substr($message, 12);
$this->doIncrementGmbClicks($request);
return $this->redirect($url);
}
$response = null;
if (str_starts_with($message, '__inactive: ')) {
$response = $this->render('booking_process_cm_mvp1/message_inactive.html.twig', [
'screen' => 'inactive',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => '',
'message' => substr($cpo['message'], 12)
]);
$this->doIncrementGmbClicks($request);
} else {
$response = $this->render('booking_process_cm_mvp1/message.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'title' => 'THERE WAS A PROBLEM',
'message' => $cpo['message']
]);
}
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
if ($bookingProcess == null) {
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
} else {
$o = $this->redirectOnInvalidStep($request, $bookingProcess, 'input-confirmlocation', $cpo['set_cookie']);
if ($o != null) {
return $o;
} else {
$bookingProcess->setScreen('input-confirmlocation');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
}
$response = $this->render('booking_process_cm_mvp1/step_input_confirmlocation.html.twig', [
'screen' => 'input-confirmlocation',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'previous' => $this->generateUrl($this->screensmap['input-location']),
'next' => $this->generateUrl($this->screensmap['input-service']),
'client' => $this->client,
'bookingProcess' => $bookingProcess,
'displaywarning' => true,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null
]);
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
$this->addPreProcessHeaders($request, $response, $bookingProcess);
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/step/input-service", name="booking_process_cm_mvp1_step_input_service")
*/
public function step_input_service(Request $request): Response
{
$now = new \DateTime();
$canBookResponse = $this->checkCanBook($request);
if ($canBookResponse != null) {
return $canBookResponse;
}
$cpo = $this->assertBookingProcess($request);
$bookingProcess = $cpo['booking_process'];
$setCookie = $cpo['set_cookie'];
$message = $cpo['message'];
if ($message != null and $message != '') {
if (str_starts_with($message, '__redirect: ')) {
$url = substr($message, 12);
$this->doIncrementGmbClicks($request);
return $this->redirect($url);
}
$response = null;
if (str_starts_with($message, '__inactive: ')) {
$response = $this->render('booking_process_cm_mvp1/message_inactive.html.twig', [
'screen' => 'inactive',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => '',
'message' => substr($cpo['message'], 12)
]);
$this->doIncrementGmbClicks($request);
} else {
$response = $this->render('booking_process_cm_mvp1/message.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => $cpo['message']
]);
}
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
if ($bookingProcess == null) {
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
} else {
$o = $this->redirectOnInvalidStep($request, $bookingProcess, 'input-service', $cpo['set_cookie']);
if ($o != null) {
return $o;
} else {
$bookingProcess->setScreen('input-service');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
}
$regions = null;
$services = [];
$allowedServices = null;
$bookingProcessBooking = $bookingProcess->getBooking();
if ($bookingProcessBooking->getServiceType() == 'fixed') {
$regions = [$bookingProcessBooking->getSelectedRegion()];
$services = array();
foreach ($this->serviceRepository->findCustomerFacingWithRegions($regions) as $service) {
$services[$service->getId()] = $service;
}
$allowedServices = $bookingProcess->getAllowedServices();
if ($allowedServices) {
$arrayAllowedServices = explode(',', str_replace(', ', ',', $allowedServices));
$services = array_filter($services, function ($service) use ($arrayAllowedServices) {
if (in_array($service->getId(), $arrayAllowedServices)) {
return true;
}
return false;
});
}
} else {
$regions = $this->getRegionsFromLocation($bookingProcess->getBooking()->getLocation());
$services = array();
foreach ($this->serviceRepository->findCustomerFacingWithRegions($regions) as $service) {
$services[$service->getId()] = $service;
}
$allowedServices = $bookingProcess->getAllowedServices();
if ($allowedServices) {
$arrayAllowedServices = explode(',', str_replace(', ', ',', $allowedServices));
$services = array_filter($services, function ($service) use ($arrayAllowedServices) {
if (in_array($service->getId(), $arrayAllowedServices)) {
return true;
}
return false;
});
}
}
$response = $this->render('booking_process_cm_mvp1/step_input_service.html.twig', [
'screen' => 'input-service',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'previous' => $this->generateUrl($this->screensmap['input-confirmlocation']),
'next' => $this->generateUrl($this->screensmap['input-servicefields']),
'client' => $this->client,
'services' => $services,
'bookingProcess' => $bookingProcess,
'displaywarning' => true,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null
]);
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
$this->addPreProcessHeaders($request, $response, $bookingProcess);
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/step/input-servicefields", name="booking_process_cm_mvp1_step_input_servicefields")
*/
public function step_input_servicefields(Request $request): Response
{
$now = new \DateTime();
$canBookResponse = $this->checkCanBook($request);
if ($canBookResponse != null) {
return $canBookResponse;
}
$cpo = $this->assertBookingProcess($request);
$bookingProcess = $cpo['booking_process'];
$setCookie = $cpo['set_cookie'];
$message = $cpo['message'];
if ($message != null and $message != '') {
if (str_starts_with($message, '__redirect: ')) {
$url = substr($message, 12);
$this->doIncrementGmbClicks($request);
return $this->redirect($url);
}
$response = null;
if (str_starts_with($message, '__inactive: ')) {
$response = $this->render('booking_process_cm_mvp1/message_inactive.html.twig', [
'screen' => 'inactive',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => '',
'message' => substr($cpo['message'], 12)
]);
$this->doIncrementGmbClicks($request);
} else {
$response = $this->render('booking_process_cm_mvp1/message.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => $cpo['message']
]);
}
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
if ($bookingProcess == null) {
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
} else {
$o = $this->redirectOnInvalidStep($request, $bookingProcess, 'input-servicefields', $cpo['set_cookie']);
if ($o != null) {
return $o;
} else {
$bookingProcess->setScreen('input-servicefields');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
}
$response = $this->render('booking_process_cm_mvp1/step_input_servicefields.html.twig', [
'screen' => 'input-servicefields',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'previous' => $this->generateUrl($this->screensmap['input-service']),
'next' => $this->generateUrl($this->screensmap['input-datetime']),
'client' => $this->client,
'bookingProcess' => $bookingProcess,
'displaywarning' => true,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null
]);
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
$this->addPreProcessHeaders($request, $response, $bookingProcess);
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/step/input-schedule-type", name="booking_process_cm_mvp1_step_input_schedule_type")
*/
public function step_input_schedule_type(Request $request) {
$now = new \DateTime();
$canBookResponse = $this->checkCanBook($request);
if ($canBookResponse != null) {
return $canBookResponse;
}
$cpo = $this->assertBookingProcess($request);
$bookingProcess = $cpo['booking_process'];
$setCookie = $cpo['set_cookie'];
$message = $cpo['message'];
if ($message != null and $message != '') {
if (str_starts_with($message, '__redirect: ')) {
$url = substr($message, 12);
$this->doIncrementGmbClicks($request);
return $this->redirect($url);
}
$response = null;
if (str_starts_with($message, '__inactive: ')) {
$response = $this->render('booking_process_cm_mvp1/message_inactive.html.twig', [
'screen' => 'inactive',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => '',
'message' => substr($cpo['message'], 12)
]);
$this->doIncrementGmbClicks($request);
} else {
$response = $this->render('booking_process_cm_mvp1/message.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => $cpo['message']
]);
}
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
if ($bookingProcess == null) {
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
} else {
$o = $this->redirectOnInvalidStep($request, $bookingProcess, 'input-schedule-type', $cpo['set_cookie']);
if ($o != null) {
return $o;
} else {
$bookingProcess->setScreen('input-schedule-type');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
}
$response = $this->render('booking_process_cm_mvp1/step_input_schedule_type.html.twig', [
'screen' => 'input-schedule-type',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'previous' => $this->generateUrl($this->screensmap['input-servicefields']),
'next' => $this->generateUrl($this->screensmap['input-datetime']),
'client' => $this->client,
'bookingProcess' => $bookingProcess,
'choices' => [
'exact' => [
'title' => 'Exact Time Booking',
'description' => 'Choose an exact date and time for your booking'
],
'anytime' => [
'title' => 'Anytime Booking',
'description' => 'Choose a date and schedule your booking to happen anytime in that day'
],
'morning' => [
'title' => 'Morning Booking',
'description' => 'Choose a date and schedule your booking to happen in the morning of that day'
],
'afternoon' => [
'title' => 'Afternoon Booking',
'description' => 'Choose a date and schedule your booking to happen in the afternoon of that day'
],
'evening' => [
'title' => 'Evening Booking',
'description' => 'Choose a date and schedule your booking to happen in the evening of that day'
]
],
'displaywarning' => true,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null
]);
$this->addPreProcessHeaders($request, $response, $bookingProcess);
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/step/input-datetime", name="booking_process_cm_mvp1_step_input_datetime")
*/
public function step_input_datetime(Request $request): Response
{
$now = new \DateTime();
$canBookResponse = $this->checkCanBook($request);
if ($canBookResponse != null) {
return $canBookResponse;
}
$cpo = $this->assertBookingProcess($request);
$bookingProcess = $cpo['booking_process'];
$setCookie = $cpo['set_cookie'];
$message = $cpo['message'];
if ($message != null and $message != '') {
if (str_starts_with($message, '__redirect: ')) {
$url = substr($message, 12);
$this->doIncrementGmbClicks($request);
return $this->redirect($url);
}
$response = null;
if (str_starts_with($message, '__inactive: ')) {
$response = $this->render('booking_process_cm_mvp1/message_inactive.html.twig', [
'screen' => 'inactive',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => '',
'message' => substr($cpo['message'], 12)
]);
$this->doIncrementGmbClicks($request);
} else {
$response = $this->render('booking_process_cm_mvp1/message.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => $cpo['message']
]);
}
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
if ($bookingProcess == null) {
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
} else {
$o = $this->redirectOnInvalidStep($request, $bookingProcess, 'input-datetime', $cpo['set_cookie']);
if ($o != null) {
return $o;
} else {
$bookingProcess->setScreen('input-datetime');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
}
$response = $this->render('booking_process_cm_mvp1/step_input_datetime.html.twig', [
'screen' => 'input-datetime',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'previous' => $this->generateUrl($this->screensmap['input-servicefields']),
'next' => $this->generateUrl($this->screensmap['input-contact']),
'client' => $this->client,
'bookingProcess' => $bookingProcess,
'displaywarning' => true,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null
]);
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
$this->addPreProcessHeaders($request, $response, $bookingProcess);
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/step/input-contact", name="booking_process_cm_mvp1_step_input_contact")
*/
public function step_input_contact(Request $request): Response
{
$now = new \DateTime();
$canBookResponse = $this->checkCanBook($request);
if ($canBookResponse != null) {
return $canBookResponse;
}
$cpo = $this->assertBookingProcess($request);
$bookingProcess = $cpo['booking_process'];
$setCookie = $cpo['set_cookie'];
$message = $cpo['message'];
if ($message != null and $message != '') {
if (str_starts_with($message, '__redirect: ')) {
$url = substr($message, 12);
$this->doIncrementGmbClicks($request);
return $this->redirect($url);
}
$response = null;
if (str_starts_with($message, '__inactive: ')) {
$response = $this->render('booking_process_cm_mvp1/message_inactive.html.twig', [
'screen' => 'inactive',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => '',
'message' => substr($cpo['message'], 12)
]);
$this->doIncrementGmbClicks($request);
} else {
$response = $this->render('booking_process_cm_mvp1/message.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => $cpo['message']
]);
}
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
if ($bookingProcess == null) {
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
} else {
$o = $this->redirectOnInvalidStep($request, $bookingProcess, 'input-contact', $cpo['set_cookie']);
if ($o != null) {
return $o;
} else {
$bookingProcess->setScreen('input-contact');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
}
$response = $this->render('booking_process_cm_mvp1/step_input_contact.html.twig', [
'screen' => 'input-contact',
'headersteps' => true,
'complete' => false,
'headerheight' => 30,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'previous' => $this->generateUrl($this->screensmap['input-datetime']),
'next' => $this->generateUrl($this->screensmap['input-billing']),
'client' => $this->client,
'bookingProcess' => $bookingProcess,
'displaywarning' => true,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null
]);
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
$this->addPreProcessHeaders($request, $response, $bookingProcess);
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/step/input-billing", name="booking_process_cm_mvp1_step_input_billing")
*/
public function step_input_billing(Request $request): Response
{
$now = new \DateTime();
$canBookResponse = $this->checkCanBook($request);
if ($canBookResponse != null) {
return $canBookResponse;
}
$cpo = $this->assertBookingProcess($request);
$bookingProcess = $cpo['booking_process'];
$setCookie = $cpo['set_cookie'];
$message = $cpo['message'];
if ($message != null and $message != '') {
if (str_starts_with($message, '__redirect: ')) {
$url = substr($message, 12);
$this->doIncrementGmbClicks($request);
return $this->redirect($url);
}
$response = null;
if (str_starts_with($message, '__inactive: ')) {
$response = $this->render('booking_process_cm_mvp1/message_inactive.html.twig', [
'screen' => 'inactive',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => '',
'message' => substr($cpo['message'], 12)
]);
$this->doIncrementGmbClicks($request);
} else {
$response = $this->render('booking_process_cm_mvp1/message.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => $cpo['message']
]);
}
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
if ($bookingProcess == null) {
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
} else {
$o = $this->redirectOnInvalidStep($request, $bookingProcess, 'input-billing', $cpo['set_cookie']);
if ($o != null) {
return $o;
} else {
$bookingProcess->setScreen('input-billing');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
}
$response = $this->render('booking_process_cm_mvp1/step_input_billing.html.twig', [
'screen' => 'input-billing',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'previous' => $this->generateUrl($this->screensmap['input-contact']),
'next' => $this->generateUrl($this->screensmap['complete']),
'client' => $this->client,
'bookingProcess' => $bookingProcess,
'displaywarning' => true,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null
]);
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
$this->addPreProcessHeaders($request, $response, $bookingProcess);
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/step/confirm/{code}", name="booking_process_cm_mvp1_step_confirm")
*/
public function step_confirm(Request $request, string $code): Response
{
$bookingProcess = $this->bookingProcessRepository->findOneBy([
"code" => $code,
"status" => "commit-confirm"
]);
$response = null;
if ($bookingProcess !== null) {
$b = $this->doStepCommit($request, $bookingProcess);
if ($b) {
$emails = $this->emailsEntityModel->findByClient($this->client);
$this->setGoToScreenOnBookingProcess($bookingProcess, 'complete');
$this->doStepComplete($request, $bookingProcess);
$response = $this->render('booking_process_cm_mvp1/step_complete.html.twig', [
'screen' => 'complete',
'headersteps' => true,
'complete' => true,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'previous' => $this->generateUrl($this->screensmap['input-billing']),
'next' => $this->generateUrl($this->screensmap['complete']),
'client' => $this->client,
'emails' => $emails,
'bookingProcess' => $bookingProcess,
'displaywarning' => true,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null
]);
}
} else {
$response = new JsonResponse(
'THIS BOOKING CANNOT BE CONFIRMED',
Response::HTTP_BAD_REQUEST
);
}
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/step/commit", name="booking_process_cm_mvp1_step_commit")
*/
public function step_commit(Request $request): Response
{
$now = new \DateTime();
$canBookResponse = $this->checkCanBook($request);
if ($canBookResponse != null) {
return $canBookResponse;
}
$cpo = $this->assertBookingProcess($request);
$bookingProcess = $cpo['booking_process'];
$setCookie = $cpo['set_cookie'];
$message = $cpo['message'];
if ($message != null and $message != '') {
if (str_starts_with($message, '__redirect: ')) {
$url = substr($message, 12);
$this->doIncrementGmbClicks($request);
return $this->redirect($url);
}
$response = null;
if (str_starts_with($message, '__inactive: ')) {
$response = $this->render('booking_process_cm_mvp1/message_inactive.html.twig', [
'screen' => 'inactive',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => substr($cpo['message'], 12)
]);
$this->doIncrementGmbClicks($request);
} else {
$response = $this->render('booking_process_cm_mvp1/message.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => $cpo['message']
]);
}
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
if ($bookingProcess == null) {
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
} else {
$o = $this->redirectOnInvalidStep($request, $bookingProcess, 'commit', $cpo['set_cookie']);
if ($o != null) {
return $o;
} else {
$bookingProcess->setScreen('input-billing');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
}
$commit_type = $this->client->getPropertyValue('booking.commit.type');
$commit_result = null;
if ($commit_type === 'confirm' && $this->getUser() === null) {
$commit_result = $this->doStepConfirm($request, $bookingProcess);
} else {
$commit_result = $this->doStepCommit($request, $bookingProcess) ? 'commit-success' : 'commit-failure';
}
if ($commit_result === 'commit-confirm') {
$emails = $this->emailsEntityModel->findByClient($this->client);
$this->setGoToScreenOnBookingProcess($bookingProcess, 'commit-confirm');
$this->doStepCommitConfirm($request, $bookingProcess);
$response = $this->render('booking_process_cm_mvp1/step_confirm.html.twig', [
'screen' => 'complete',
'headersteps' => true,
'complete' => true,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'previous' => $this->generateUrl($this->screensmap['input-billing']),
'next' => $this->generateUrl($this->screensmap['complete']),
'client' => $this->client,
'emails' => $emails,
'bookingProcess' => $bookingProcess,
'displaywarning' => true,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null
]);
$this->unsetCookie($response);
} else if ($commit_result === 'commit-success') {
$emails = $this->emailsEntityModel->findByClient($this->client);
$this->setGoToScreenOnBookingProcess($bookingProcess, 'complete');
$this->doStepComplete($request, $bookingProcess);
$response = $this->render('booking_process_cm_mvp1/step_complete.html.twig', [
'screen' => 'complete',
'headersteps' => true,
'complete' => true,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'previous' => $this->generateUrl($this->screensmap['input-billing']),
'next' => $this->generateUrl($this->screensmap['complete']),
'client' => $this->client,
'emails' => $emails,
'bookingProcess' => $bookingProcess,
'displaywarning' => true,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null
]);
$this->unsetCookie($response);
} else {
$response = new Response(
'COMMIT FAILED',
Response::HTTP_OK,
['content-type' => 'text/html']
);
}
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/step/complete", name="booking_process_cm_mvp1_step_complete")
*/
public function step_input_complete(Request $request): Response
{
$now = new \DateTime();
$canBookResponse = $this->checkCanBook($request);
if ($canBookResponse != null) {
return $canBookResponse;
}
$cpo = $this->assertBookingProcess($request);
$bookingProcess = $cpo['booking_process'];
$setCookie = $cpo['set_cookie'];
$message = $cpo['message'];
if ($message != null and $message != '') {
if (str_starts_with($message, '__redirect: ')) {
$url = substr($message, 12);
$this->doIncrementGmbClicks($request);
return $this->redirect($url);
}
$response = null;
if (str_starts_with($message, '__inactive: ')) {
$response = $this->render('booking_process_cm_mvp1/message_inactive.html.twig', [
'screen' => 'inactive',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => substr($cpo['message'], 12)
]);
$this->doIncrementGmbClicks($request);
} else {
$response = $this->render('booking_process_cm_mvp1/message.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => $cpo['message']
]);
}
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
if ($bookingProcess == null) {
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
} else {
$o = $this->redirectOnInvalidStep($request, $bookingProcess, 'input-complete', $cpo['set_cookie']);
if ($o != null) {
return $o;
} else {
$bookingProcess->setScreen('complete');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
}
return $this->render('booking_process_cm_mvp1/step_complete.html.twig', [
'screen' => 'complete',
'headersteps' => true,
'complete' => true,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'previous' => $this->generateUrl($this->screensmap['input-billing']),
'next' => $this->generateUrl($this->screensmap['complete']),
'client' => $this->client,
'bookingProcess' => $bookingProcess,
'displaywarning' => true,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null
]);
}
/**
* @Route("/booking/process/cm/mvp1/step/complete-callback", name="booking_process_cm_mvp1_step_complete_callback")
*/
public function step_input_complete_callback(Request $request): Response
{
$now = new \DateTime();
$canBookResponse = $this->checkCanBook($request);
if ($canBookResponse != null) {
return $canBookResponse;
}
$cpo = $this->assertBookingProcess($request);
$bookingProcess = $cpo['booking_process'];
$setCookie = $cpo['set_cookie'];
$message = $cpo['message'];
if ($message != null and $message != '') {
if (str_starts_with($message, '__redirect: ')) {
$url = substr($message, 12);
$this->doIncrementGmbClicks($request);
return $this->redirect($url);
}
$response = null;
if (str_starts_with($message, '__inactive: ')) {
$response = $this->render('booking_process_cm_mvp1/message_inactive.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => substr($cpo['message'], 12)
]);
$this->doIncrementGmbClicks($request);
} else {
$response = $this->render('booking_process_cm_mvp1/message.html.twig', [
'screen' => 'message',
'headersteps' => true,
'complete' => false,
'controller_name' => 'BookingProcessController',
'next' => '',
'client' => $this->client,
'bookingProcess' => null,
'displaywarning' => false,
'warningstatus' => 0,
'warningbody' => '',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'title' => 'THERE WAS A PROBLEM',
'message' => $cpo['message']
]);
}
if ($setCookie) {
$this->setCookie($request, $response, $bookingProcess->getCode());
}
return $response;
}
if ($bookingProcess == null) {
return $this->redirect($this->generateUrl($this->screensmap['input-location']));
} else {
$o = $this->redirectOnInvalidStep($request, $bookingProcess, 'complete-callback', $cpo['set_cookie']);
if ($o != null) {
return $o;
} else {
$bookingProcess->setScreen('complete-callback');
$bookingProcess->setStatus('complete-callback');
$bookingProcess->setUpdatedAt($now);
$bookingProcess->setIpAddress($this->request->getClientIp());
$this->entityManager->persist($bookingProcess);
$this->entityManager->flush();
}
}
$response = $this->render('booking_process_cm_mvp1/step_complete_callback.html.twig', [
'screen' => 'complete',
'headersteps' => true,
'complete' => true,
'controller_name' => 'BookingProcessController',
'user' => $this->getUser() != null && ($this->getUser()->getClient() == null || $this->getUser()->getClient()->getId() == $this->client->getId()) ? $this->getUser() : null,
'previous' => $this->generateUrl($this->screensmap['input-billing']),
'next' => $this->generateUrl($this->screensmap['complete']),
'client' => $this->client,
'bookingProcess' => $bookingProcess,
'displaywarning' => true,
'warningstatus' => $bookingProcess != null && $bookingProcess->getWarningstatus() != null ? $bookingProcess->getWarningstatus() : 0,
'warningbody' => $bookingProcess != null && $bookingProcess->getWarningbody() != null && $bookingProcess->getWarningbody() != '' ? json_decode($bookingProcess->getWarningbody()) : null
]);
$this->unsetCookie($response);
return $response;
}
/**
* @Route("/booking/process/cm/mvp1/reschedule/{id}", name="booking_process_cm_mvp1_reschedule")
* @Route("/reschedule/cm/mvp1/{id}", name="booking_reschedule_cm_mvp1")
* @Route("/reschedule/{id}", name="booking_reschedule_cm_mvp1_default", condition="(((context.getHost() not in %app.beta.clients%) and ('%booking_process.scope%' == 'cm_mvp1')) or ((context.getHost() in %app.beta.clients%) and ('%booking_process.beta.scope%' == 'cm_mvp1')))")
*/
public function reschedule(Request $request, int $id) {
return $this->redirect($this->generateUrl($this->screensmap['input-datetime'], array('booking' => $id)));
}
/**
* @Route("/booking/process/cm/mvp1/edit/{id}", name="booking_process_cm_mvp1_edit")
* @Route("/edit/cm/mvp1/{id}", name="booking_edit_cm_mvp1")
* @Route("/edit/{id}", name="booking_edit_cm_mvp1_default", condition="(((context.getHost() not in %app.beta.clients%) and ('%booking_process.scope%' == 'cm_mvp1')) or ((context.getHost() in %app.beta.clients%) and ('%booking_process.beta.scope%' == 'cm_mvp1')))")
*/
public function edit(Request $request, int $id) {
return $this->redirect($this->generateUrl($this->screensmap['input-confirmlocation'], array('booking' => $id)));
}
protected function getRegionsFromLocation(BookingProcessLocation $location)
{
$regions = [];
$point = $this->locationToCoordinates($location);
foreach ($this->regionRepository->findByClient($this->client) as $region) {
$polygon = array_map(
array($this, 'locationToCoordinates'),
$region->getBoundaries()->toArray()
);
if ($this->pointInPolygon->inPolygon($point, $polygon)) {
$regions[] = $region;
}
}
return $regions;
}
protected function getRegionsGroupedByServiceType()
{
$regions = [
'fixed' => [],
'onsite' => []
];
$aregions = $this->regionRepository->findByClient($this->client);
foreach ($aregions as $region) {
$regions[$this->client->getServiceType() == 'fixed' ? 'fixed' : 'onsite'][] = $region;
}
return $regions;
}
protected function locationToCoordinates($location)
{
if ($location instanceof Boundary) {
$location = $location->getLocation();
}
if (!$location instanceof Location && !$location instanceof BookingProcessLocation) {
throw new \InvalidArgumentException('$location must be a Location|Boundary|BookingProcessLocation');
}
return array($location->getLatitude(), $location->getLongitude());
}
/**
* @Route("/booking/process/cm/mvp1/step/datetime/availability/date", name="booking_process_cm_mvp1_step_datetime_dateavailability")
*/
public function dateAvailability(
Request $request, DayScheduler $dayScheduler,
CalendarExtension $calendarExtension,
HoursOfOperationRepository $hoursOfOperationRepository,
Scheduler $scheduler,
HoursChangeRepository $hoursChangeRepository
)
{
try {
$now = new \DateTime();
$bookingProcess = $this->checkBookingProcess($request);
if ($bookingProcess == null) {
$response = new JsonResponse(
'MISSING BOOKING PROCESS',
Response::HTTP_NOT_FOUND
);
return $response;
}
$bookingProcessBooking = $bookingProcess->getBooking();
if ($bookingProcess == null) {
$response = new JsonResponse(
'MISSING BOOKING FOR THIS BOOKING PROCESS',
Response::HTTP_NOT_FOUND
);
return $response;
}
$bookingProcessBookingLocation = $bookingProcessBooking->getLocation();
if ($bookingProcessBookingLocation == null) {
$response = new JsonResponse(
'MISSING BOOKING LOCATION FOR THIS BOOKING PROCESS',
Response::HTTP_NOT_FOUND
);
return $response;
}
{
$bookingRegions = $bookingProcessBooking->getRegions();
$bookingRegionsIds = [];
if ($bookingRegions) {
foreach($bookingRegions as $bookingRegion) {
$bookingRegionsIds[] = $bookingRegion->getId();
}
}
$bookingProcessLocation = $bookingProcessBooking->getLocation();
$locationRegions = $this->getRegionsFromLocation($bookingProcessLocation, $bookingProcess->getAllowedRegions());
foreach ($bookingRegions as $bookingRegion) {
$bookingProcessBooking->removeRegion($bookingRegion);
}
$region_id = $bookingRegionsIds[0];
$region = $this->regionRepository->find($region_id);
if ($bookingProcessBooking->getServiceType() === 'fixed') {
$bookingProcessBooking->addRegion($region);
} else {
foreach ($locationRegions as $locationRegion) {
$bookingProcessBooking->addRegion($locationRegion);
}
}
if ($bookingProcessBooking->getServiceType() !== 'fixed' && (!$locationRegions || count($locationRegions) < 1)) {
throw new \Exception("Location is out of bounds!");
} else {
foreach ($locationRegions as $locationRegion) {
$bookingProcessBooking->addRegion($locationRegion);
}
}
$this->entityManager->persist($bookingProcessBooking);
$this->entityManager->flush();
}
$schedule_type = $request->query->get('schedule_type');
if ($schedule_type == null) {
$schedule_type = 'anytime';
}
$input_start = $request->query->get('start');
$start = null;
if ($input_start == null) {
$start = clone $now;
} else {
$start = \DateTime::createFromFormat('Y-m-d H:i:s', $input_start . ' 00:00:00');
if (!$start) {
throw new \Exception("Invalid start date");
}
}
$input_end = $request->query->get('end');
$end = null;
if ($input_end == null) {
$end = clone $now;
$end->modify($this->getParameter('orc_booking.schedule.calendar.lookahead'));
} else {
$end = \DateTime::createFromFormat('Y-m-d H:i:s', $input_end . ' 23:59:59');
$end->modify('+1 day');
$end->setTime(0, 0, 0);
}
if ($start <= $now) {
$start = clone $now;
// $start = $this->determineCalendarQueryStartForProcess(
// $start, $bookingProcessBooking, $hoursOfOperationRepository,
// $this->endTimeCalculator, $hoursChangeRepository
// );
}
$availableDays = $this->scheduleAvailabilityCMMVP1Service->getServiceAvailability($this->client, $bookingProcessBooking->getService(), $start, $end, $bookingProcessBooking->getRegions(), $this->endTimeCalculator->getTimeRequiredForProcess($bookingProcessBooking), $bookingProcessBooking);
$aavailableDays = [];
foreach ($availableDays as $ssdt => $oovalue) {
$oavailability = $this->ptimeAvailability(\DateTime::createFromFormat('Y-m-d', $ssdt), null, $bookingProcessBooking);
if (count($oavailability) > 0) {
$aavailableDays[$ssdt] = $oovalue;
}
}
// TODO
{
$response = new JsonResponse(
$aavailableDays,
Response::HTTP_OK
);
return $response;
}
// $response = new Response();
// $response->headers->set('Content-Type', 'application/json');
// $response->setContent(
// $calendarExtension->getDatesAsJsonEvents(
// []
// )
// );
//
// return $response;
} catch (\Throwable $throwable) {
$response = new JsonResponse(
[
'message' => $throwable->getMessage(),
'file' => $throwable->getFile(),
'line' => $throwable->getLine(),
'trace' => $throwable->getTrace()
],
Response::HTTP_INTERNAL_SERVER_ERROR
);
return $response;
}
}
public function ptimeAvailability(\DateTime $day, $schedule_type = null, BookingProcessBooking $bookingProcessBooking) {
$now = new \DateTime();
$nowpluscutoff = clone $now;
$nowpluscutoff->modify(sprintf('+%d hours', $bookingProcessBooking->getService()->getCutofftime()));
$available_times = [];
$available_times_gap = [];
$available_times_exact = [];
$start = clone $day;
if ($start < new \DateTime('today')) {
$start = new \DateTime();
}
$end = clone $day;
$end->modify('+1 day');
$date = $day;
$publicInterval = $this->baseService->round15($bookingProcessBooking->getService()->getBaseTime());
$requiredTime = $this->endTimeCalculator->getTimeRequiredForProcess($bookingProcessBooking);
$qb_crews = $this->entityManager->createQueryBuilder();
$debugging = false;
// if ($day->format('Y-m-d') === '2023-12-28') {
// $debugging = true;
// }
if ($debugging) {
dump($day->format('Y-m-d'));
}
$qb_crews
->select([
'crew' . ' AS ocrew',
$qb_crews->expr()->count('b.id') . ' AS count_b',
'r.id AS radius_id',
'rl.latitude AS radius_latitude',
'rl.longitude AS radius_longitude',
'r.radius AS radius_size'
])
->from('Orc\BookingBundle\Entity\Crew', 'crew')
->innerJoin('crew.services', 'service', Expr\Join::WITH, $qb_crews->expr()->eq('service', ':service'))
->innerJoin('crew.regions', 'region', Expr\Join::WITH, $qb_crews->expr()->in('region', ':regions'))
->leftJoin('crew.bookings', 'b', Expr\Join::WITH, "DATE_FORMAT(b.dateStart, '%Y-%m-%d') = :start AND b.radius IS NOT NULL")
->leftJoin('b.radius', 'r')
->leftJoin('r.location', 'rl')
//->andWhere($qb_crews->expr()->eq('crew.status', ':status_active'))
->andWhere($qb_crews->expr()->eq('crew.status', ':status_active'))
->andWhere($qb_crews->expr()->eq('crew.active', true));
$qb_crews
->addGroupBy('crew.id')
->setParameter('service', $bookingProcessBooking->getService())
->setParameter('regions', $bookingProcessBooking->getRegions())
->setParameter('status_active', Crew::STATUS_ACTIVE)
->setParameter('start', $start->format("Y-m-d"));
$acrews = $qb_crews
->getQuery()
->getResult();
if ($debugging) {
//dump(['$acrews' => $acrews]);
}
// dump(array_map(function($o) { return [
// 'count_b' => $o['count_b'],
// 'radius_id' => $o['radius_id'],
// 'radius_latitude' => $o['radius_latitude'],
// 'radius_longitude' => $o['radius_longitude'],
// 'radius_size' => $o['radius_size'],
// 'id' => $o['ocrew']->getId(),
// 'name' => $o['ocrew']->getName(),
// 'regions' => array_map(function ($oo) {
// return [
// 'id' => $oo->getId(),
// 'name' => $oo->getName()
// ];
// },$o['ocrew']->getRegions()->toArray())
// ]; }, $acrews));
$crews = array_map(function($o) { return $o['ocrew']; }, $acrews);
$mapradiuscrew = [];
foreach ($acrews as $o) {
$mapradiuscrew[$o['ocrew']->getId()] = [
'crew_id' => $o['ocrew']->getId(),
'count_b' => $o['count_b'],
'radius_id' => $o['radius_id'],
'radius_latitude' => $o['radius_latitude'],
'radius_longitude' => $o['radius_longitude'],
'radius_size' => $o['radius_size']
];
}
//$bookableHours = $this->getBookableHours($this->request, $day);
$gaps = [];
$gaps_morning = [];
$gaps_afternoon = [];
$gaps_evening = [];
$is_anytime_available = false;
$is_morning_available = false;
$is_afternoon_available = false;
$is_evening_available = false;
$is_anytime_actually_available = false;
$is_morning_actually_available = false;
$is_afternoon_actually_available = false;
$is_evening_actually_available = false;
// if ($debugging) {
// dump($acrews);
// }
foreach ($acrews as $oocrew) {
$crew = $oocrew['ocrew'];
$count_b = $oocrew['count_b'] != null ? intval($oocrew['count_b']) : null;
$radius_id = $oocrew['radius_id'] != null ? intval($oocrew['radius_id']) : null;
$radius_latitude = $oocrew['radius_latitude'] != null ? floatval($oocrew['radius_latitude']) : null;
$radius_longitude = $oocrew['radius_longitude'] != null ? floatval($oocrew['radius_longitude']) : null;
$radius_size = $oocrew['radius_size'] != null ? floatval($oocrew['radius_size']) : null;
$distance = null;
if (
$bookingProcessBooking != null
&& $bookingProcessBooking->getServiceType() !== 'fixed'
&& $radius_id !== null
&& $radius_latitude !== null
&& $radius_longitude !== null
&& $radius_size !== null
&& $bookingProcessBooking->getLocation() != null
&& $bookingProcessBooking->getLocation()->getLatitude() !== null
&& $bookingProcessBooking->getLocation()->getLongitude() !== null
) {
$distance = $this->distanceCalculator->getDistanceP($radius_latitude, $radius_longitude, $bookingProcessBooking->getLocation()->getLatitude(), $bookingProcessBooking->getLocation()->getLongitude(), ($this->client->getUnits() == 'km' ? DistanceCalculator::EARTH_RADIUS_KM : DistanceCalculator::EARTH_RADIUS_MILES));
if ($distance > $radius_size) {
if ($debugging) {
dump(sprintf('Skipping crew %d', $crew->getId()));
}
continue;
}
}
// dump([
// 'crew' => $crew->getId(),
// 'distance' => $distance,
// 'radius_size' => $radius_size,
// ]);
if ($distance <= $radius_size) {
$materialBooking = null;
if ($bookingProcessBooking->getProcess() != null && $bookingProcessBooking->getProcess()->getMaterialBooking() != null) {
$materialBooking = $this->bookingRepository->findOneBy(['id' => $bookingProcessBooking->getProcess()->getMaterialBooking()->getId()]);
}
$gapInfo = $this->scheduleAvailabilityCMMVP1Service->getGapInfo($this->client, $crew, $date, $materialBooking, $bookingProcessBooking);
// dump([
// 'crew' => $crew->getId(),
// '$gapInfo' => $gapInfo
// ]);
//$gapInfo = $this->scheduleAvailabilityCMMVP1Service->getGapInfo($this->client, $crew, $date);
if ($this->client->getCmEnabled() && $day->format('Y-m-d') > $nowpluscutoff->format('Y-m-d')) {
if ($crew->getCanBookAnytime() && $gapInfo['gaps']['anytime'] >= $requiredTime && !$is_anytime_available) {
//$available_times[] = 'gap|anytime';
$is_anytime_available = true;
}
if ($crew->getCanBookMorning() && $gapInfo['gaps']['morning'] >= $requiredTime && !$is_morning_available) {
//$available_times[] = 'gap|morning';
$is_morning_available = true;
}
if ($crew->getCanBookAfternoon() && $gapInfo['gaps']['afternoon'] >= $requiredTime && !$is_afternoon_available) {
//$available_times[] = 'gap|afternoon';
$is_afternoon_available = true;
}
if ($crew->getCanBookEvening() && $gapInfo['gaps']['evening'] >= $requiredTime && !$is_evening_available) {
//$available_times[] = 'gap|evening';
$is_evening_available = true;
}
}
$gaps = array_merge($gaps, $gapInfo['gaps']['gaps']['anytime']);
$gaps_morning = array_merge($gaps_morning, $gapInfo['gaps']['gaps']['morning']);
$gaps_afternoon = array_merge($gaps_afternoon, $gapInfo['gaps']['gaps']['afternoon']);
$gaps_evening = array_merge($gaps_evening, $gapInfo['gaps']['gaps']['evening']);
}
}
if ($debugging) {
dump($gaps);
}
switch ($schedule_type) {
case 'morning':
$actual_gaps = $gaps_morning;
break;
case 'afternoon':
$actual_gaps = $gaps_afternoon;
break;
case 'evening':
$actual_gaps = $gaps_evening;
break;
case 'anytime':
case 'exact':
default:
$actual_gaps = $gaps;
break;
}
uasort($actual_gaps, 'App\Service\ScheduleAvailabilityCMMVP1Service::block_compare');
$i_day_of_week = intval($date->format('w'));
$hos = $this->client->getHoursOfOperation();
$ho = null;
foreach ($hos as $aho) {
if ($aho->getDay() == $i_day_of_week) {
$ho = $aho;
break;
}
}
if ($debugging) {
dump(['$nowpluscutoff' => $nowpluscutoff]);
}
if ($ho != null && !$ho->getOff()) {
$block_morning = [
'start' => $ho->getStartTime()->format('H:i'),
'end' => $ho->getStartTimeAfternoon()->format('H:i')
];
$block_afternoon = [
'start' => $ho->getStartTimeAfternoon()->format('H:i'),
'end' => $ho->getStartTimeEvening()->format('H:i')
];
$block_evening = [
'start' => $ho->getStartTimeEvening()->format('H:i'),
'end' => $ho->getStartTime()->format('H:i')
];
$quarters = $this->scheduleAvailabilityCMMVP1Service->getTimeIntervals($ho->getStartTime(), $ho->getEndTime());
$bookable_quarters = [];
//RoutezillaDebugger::setMark(false, $quarters);
//RoutezillaDebugger(false, sprintf('', ''));
if (true) {
$bookable_quarters = [];
$i = 0;
foreach ($quarters as $quarter) {
$dt_quarter = \DateTime::createFromFormat('Y-m-d H:i:s', sprintf('%s %s:00', $start->format('Y-m-d'), $quarter));
//RoutezillaDebugger::setMark(false, sprintf('LOOPING %d: $quarter = %s', $i, $quarter));
if ($i == 0) {
//RoutezillaDebugger::setMark(false, sprintf('LOOPING %d: $dt_quarter = %s', $i, $dt_quarter->format('Y-m-d H:i:s')));
if (true || $dt_quarter >= $nowpluscutoff) {
$bookable_quarters[] = $quarter;
}
} else {
if (count($bookable_quarters) > 0) {
$last_quarter = $bookable_quarters[count($bookable_quarters) - 1];
$dt_lp_quarter = \DateTime::createFromFormat('Y-m-d H:i:s', sprintf('%s %s:00', $start->format('Y-m-d'), $last_quarter));
$dt_lp_quarter->modify(sprintf('+%d minutes', $publicInterval));
if ($dt_quarter >= $dt_lp_quarter) {
if (true || $dt_quarter > $nowpluscutoff) {
$bookable_quarters[] = $quarter;
}
}
} else {
if (true || $dt_quarter > $nowpluscutoff) {
$bookable_quarters[] = $quarter;
}
}
}
$i++;
}
} else {
$bookable_quarters = $quarters;
}
//RoutezillaDebugger::setMark(true, 'STOP');
//dd($quarters);
foreach ($bookable_quarters as $quarter) {
$dt_start = clone $date;
$a = explode(':', $quarter);
$h = intval($a[0]);
$m = intval($a[1]);
$dt_start->setTime($h, $m, 0);
$dt_end = clone $dt_start;
$dt_end->modify(sprintf("+%d minutes", $requiredTime));
$block = [
'start' => $dt_start->format('H:i'),
'end' => $dt_end->format('H:i')
];
// dump([
// '$block' => $block,
// '$dt_start' => $dt_start,
// '$nowpluscutoff' => $nowpluscutoff->format('Y-m-d H:i:s'),
// '$actual_gaps' => $actual_gaps
// ]);
if ($dt_start >= $nowpluscutoff && $this->scheduleAvailabilityCMMVP1Service->isBlockFitInside($block, $actual_gaps)) {
{
$is_anytime_actually_available = true;
}
if (!$is_morning_actually_available && $this->scheduleAvailabilityCMMVP1Service->isBlockInside($block, $block_morning)) {
$is_morning_actually_available = true;
}
if (!$is_afternoon_actually_available && $this->scheduleAvailabilityCMMVP1Service->isBlockInside($block, $block_afternoon)) {
$is_afternoon_actually_available = true;
}
if (!$is_evening_actually_available && $this->scheduleAvailabilityCMMVP1Service->isBlockInside($block, $block_evening)) {
$is_evening_actually_available = true;
}
if ($this->client->getArrivalWindow() > 0) {
$available_times_exact[] = sprintf('time|%s|%s', $block['start'], $block['end']);
} else {
$available_times_exact[] = sprintf('time|%s|%s', $block['start'], $block['end']);
}
}
}
}
if ($is_anytime_actually_available) {
$available_times_gap[] = 'gap|anytime';
}
if ($is_morning_actually_available) {
$available_times_gap[] = 'gap|morning';
}
if ($is_afternoon_actually_available) {
$available_times_gap[] = 'gap|afternoon';
}
if ($is_evening_actually_available) {
$available_times_gap[] = 'gap|evening';
}
$available_times = array_merge($available_times_gap, $available_times_exact);
if ($debugging) {
dd('END');
}
return $available_times;
}
/**
* @Route("/booking/process/cm/mvp1/step/datetime/availability/time/{day}", name="booking_process_cm_mvp1_step_datetime_timeavailability")
*/
public function timeAvailability(\DateTime $day, Request $request) {
try {
$bookingProcess = $this->checkBookingProcess($request);
if ($bookingProcess == null) {
$response = new JsonResponse(
'MISSING BOOKING PROCESS',
Response::HTTP_NOT_FOUND
);
return $response;
}
$bookingProcessBooking = $bookingProcess->getBooking();
if ($bookingProcess == null) {
$response = new JsonResponse(
'MISSING BOOKING FOR THIS BOOKING PROCESS',
Response::HTTP_NOT_FOUND
);
return $response;
}
$bookingProcessBookingLocation = $bookingProcessBooking->getLocation();
if ($bookingProcessBookingLocation == null) {
$response = new JsonResponse(
'MISSING BOOKING LOCATION FOR THIS BOOKING PROCESS',
Response::HTTP_NOT_FOUND
);
return $response;
}
$available_times = $this->ptimeAvailability($day, null, $bookingProcessBooking);
{
$response = new JsonResponse(
$available_times,
Response::HTTP_OK
);
return $response;
}
} catch (\Throwable $throwable) {
$response = new JsonResponse(
[
'message' => $throwable->getMessage(),
'file' => $throwable->getFile(),
'line' => $throwable->getLine(),
'trace' => $throwable->getTrace()
],
Response::HTTP_INTERNAL_SERVER_ERROR
);
return $response;
}
}
/**
* @Route("/booking/process/cm/mvp1/step/customer/list", name="booking_process_cm_mvp1_step_customer_list")
*/
public function getCustomers()
{
$oresponsedata = [];
$oresponsestatus = Response::HTTP_OK;
$user = $this->getUser();
if ($user == null) {
// RETURN EMPTY
} else {
//$acustomers = $this->customerRepository->findBy([ 'client' => $this->client->getId(), 'deleted' => 0 ]);
$acustomers = $this->customerRepository->findClientCustomers();
$amarked = [];
foreach ($acustomers as $ocustomer) {
$smarked = sprintf('%s|%s|%s', $ocustomer->getName(), $ocustomer->getEmail(), $ocustomer->getPhone());
if (!in_array($smarked, $amarked)) {
$amarked[] = $smarked;
$oresponsedata[] = [
'id' => $ocustomer->getId(),
'name' => $ocustomer->getName(),
'email' => $ocustomer->getEmail(),
'phone' => $ocustomer->getPhone(),
'location' => $ocustomer->getLocation() != null ? [
'id' => $ocustomer->getLocation()->getId(),
'street' => $ocustomer->getLocation()->getStreet(),
'line2' => $ocustomer->getLocation()->getLine2(),
'city' => $ocustomer->getLocation()->getCity(),
'code' => $ocustomer->getLocation()->getCode(),
'province' => $ocustomer->getLocation()->getProvince(),
'country' => $ocustomer->getLocation()->getCountry(),
'latitude' => $ocustomer->getLocation()->getLatitude(),
'longitude' => $ocustomer->getLocation()->getLongitude(),
'address' => $ocustomer->getLocation()->getAddress()
] : null
];
}
}
}
return new JsonResponse($oresponsedata, $oresponsestatus);
}
/**
* @Route("/booking/process/cm/mvp1/step/customer/notify", name="booking_process_cm_mvp1_step_customer_notify")
*/
public function doCustomerNotify(Request $request) {
$sbody = $request->getContent();
if ($sbody != null) {
$customerMailer = $this->confirmationMailer;
$obody = json_decode($sbody);
$obooking = property_exists($obody, 'booking') ? $obody->booking : null;
$oendpoints = property_exists($obody, 'endpoints') ? $obody->endpoints : null;
$bemail = $oendpoints !== null && property_exists($oendpoints, 'email') ? $oendpoints->email : false;
$bsms = $oendpoints !== null && property_exists($oendpoints, 'sms') ? $oendpoints->sms : false;
if ($obooking !== null) {
$booking = $this->bookingRepository->findOneBy(['id' => $obooking->id ]);
$nnotifications = 0;
$sentemail = false;
$sentsms = false;
if ($bemail) {
try {
$customerMailer->send($booking);
$nnotifications++;
$sendemail = true;
}
catch (TransportException $e) {
//$this->emailErrors[] = 'Failed to send you an e-mail confirmation at ' . htmlspecialchars($customer->getEmail()) . '. It seems that this e-mail is not valid.';
//$result = self::FAILED_TO_SEND_EMAIL;
}
}
if ($bsms) {
try {
$customerMailer->sendSMS($booking);
$nnotifications++;
$sendemail = sms;
}
catch (\Throwable $e) {
//$this->emailErrors[] = 'Failed to send you an SMS confirmation to ' . htmlspecialchars($customer->getPhone()) . '.';
//$result = self::FAILED_TO_SEND_EMAIL;
}
}
if ($nnotifications > 0) {
$response = new JsonResponse(
[
'icon' => 'success',
'message' => 'NOTIFICATION SENT SUCCESSFULY TO THE CUSTOMER'
],
Response::HTTP_OK
);
} else {
$response = new JsonResponse(
[
'icon' => 'error',
'message' => 'FAILED TO SEND NOTIFICATIONS',
'email' => $sentemail,
'sms' => $sentsms
],
Response::HTTP_INTERNAL_SERVER_ERROR
);
}
}
} else {
$response = new JsonResponse(
[
'icon' => 'error',
'message' => 'INVALID NOTIFICATION DATA'
],
Response::HTTP_BAD_REQUEST
);
}
return $response;
}
/**
* Query schedule for available times, and filter into bookable hours based on service length
* @return DateTime[]
*/
public function getBookableHours(Request $request, $date = null)
{
$bookingProcess = $this->checkBookingProcess($request);
if ($bookingProcess == null) {
return [];
}
$bookingProcessBooking = $bookingProcess->getBooking();
if ($bookingProcess == null) {
return [];
}
$cutofftime = $bookingProcessBooking->getService()->getCutofftime();
$publicInterval = $this->baseService->round15($bookingProcessBooking->getService()->getBaseTime());
if (!$publicInterval) {
$publicInterval = $this->baseService->round15($bookingProcessBooking->getService()->getBaseTime());
}
if ($date === null) {
$date = $bookingProcessBooking->getDateStart();
$bookingProcessBooking->setDateEnd($this->endTimeCalculator->getEndTimeForProcess($bookingProcessBooking));
}
$start = clone $date;
$start->modify('-1 day');
$end = clone $date;
$end->setTime(0, 0);
$end->modify('+1 day');
// if ( $booking->getStatus() == BookingStatus::STATUS_UNASSIGNABLE) {
// $start = clone $date;
// $end = clone $date;
// $maxHoursOfOperation = $this->hoursOfOperationRepository->getMaxHoursOfOperation();
// $earliestTimeHour = (int)(new \DateTime($maxHoursOfOperation[0]['earliestTime']))->format('H');
// $earliestTimeMinutes = (int)(new \DateTime($maxHoursOfOperation[0]['earliestTime']))->format('i');
// $latestTimeHour = (int)(new \DateTime($maxHoursOfOperation[0]['latestTime']))->format('H');
// $latestTimeMinutes = (int)(new \DateTime($maxHoursOfOperation[0]['latestTime']))->format('i');
// $start->setTime($earliestTimeHour, $earliestTimeMinutes);
// $end->setTime($latestTimeHour, $latestTimeMinutes);
// }
$this->scheduler->setRange($start, $end);
$availableSlots = $this->scheduler->getAvailableTimeSlotsForProcess($this->client, $bookingProcessBooking);
$todaysSlots = array_filter($availableSlots, function($slot) use ($date) {
return $slot->format('Y-m-d') == $date->format('Y-m-d');
});
$bookable = array();
$i = 0;
foreach ( $todaysSlots as $slot ) {
if ( $i == 0 ) {
if ($slot >= (new \DateTime)->modify($cutofftime . ' hours') ) {
$bookable[] = $slot;
}
$lastTestedSlot = $slot;
}
else {
if ($bookable) {
$lastSlot = clone $bookable[count($bookable) - 1];
if ( $slot >= $lastSlot->modify('+' . $publicInterval . ' minutes')) {
if ($slot > (new \DateTime)->modify($cutofftime . ' hours') ) {
$bookable[] = $slot;
}
}
}
else {
if ($slot >= (new \DateTime)->modify($cutofftime . ' hours') ) {
$bookable[] = $slot;
}
}
}
$i++;
}
return $bookable;
}
/**
* Gets the Region containing Location, if any
* @param Location
* @return Region|null
*/
protected function getRegion(Location $location)
{
$point = $this->locationToCoordinates($location);
foreach ($this->regionRepository->findAll() as $region) {
$polygon = array_map(
array($this, 'locationToCoordinates'),
$region->getBoundaries()->toArray()
);
if ($this->pointInPolygon->inPolygon($point, $polygon)) {
return $region;
}
}
return false;
}
protected function getAddress($request)
{
return trim(
sprintf(
'%s%s, %s, %s, %s',
$request->request->get('street'),
$request->request->get('line2') ? ' ' . $request->request->get('line2') : '',
$request->request->get('city'),
$request->request->get('province'),
$request->request->get('code')
),
' ,'
);
}
private function verifyServiceFieldsNext($bookingProcess): RedirectResponse
{
$allfields = $bookingProcess->getBooking()->getService()->getFields();
$fields = [];
foreach ($allfields as $field) {
if ($field->getIsActive() && $field->getQuestion() != null && $field->getQuestion() != '') {
$fields[] = $field;
}
}
if (count($fields) > 0) {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-servicefields');
return $this->redirect($this->generateUrl($this->screensmap['input-servicefields']));
} else {
$this->setGoToScreenOnBookingProcess($bookingProcess, 'input-datetime');
return $this->redirect($this->generateUrl($this->screensmap['input-datetime']));
}
}
}