<?php
namespace AdminBundle\Controller;
use AdminBundle\Entity\Account;
use AdminBundle\Entity\Booking;
use AdminBundle\Entity\BookingBookingExtra;
use AdminBundle\Entity\BookingCancelReason;
use AdminBundle\Entity\BookingExtra;
use AdminBundle\Entity\BookingHistory;
use AdminBundle\Entity\BookingRequest;
use AdminBundle\Entity\BookingRequestHistory;
use AdminBundle\Entity\BookingViasAddress;
use AdminBundle\Entity\BroadcastedDriver;
use AdminBundle\Entity\Car;
use AdminBundle\Entity\Driver;
use AdminBundle\Entity\DriverHistory;
use AdminBundle\Entity\DriverHistoryLocations;
use AdminBundle\Entity\Payment;
use AdminBundle\Entity\Settings;
use AdminBundle\Entity\User;
use AdminBundle\Helpers\MandrillManager;
use AdminBundle\WebSockets\NotificationPusher;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Query\Expr\Join;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
class BookingController extends BaseController
{
private static $mapDashboardStatusRequest = [
'incoming' => [Booking::STATUS_NEW_BOOKING],
'pending' => [Booking::STATUS_PENDING],
'deallocated' => [
Booking::STATUS_DEALLOCATED_ON_DEMAND,
Booking::STATUS_DEALLOCATED_LATE_PICKUP,
Booking::STATUS_DEALLOCATED_NO_LONGER_AVAILABLE,
Booking::STATUS_DEALLOCATED_CAR_BROKE_DOWN,
Booking::STATUS_DEALLOCATED_OFFICE,
],
'live' => [
Booking::STATUS_DRIVER_ACCEPT,
Booking::STATUS_ON_THE_WAY,
Booking::STATUS_ARRIVED_AND_WAITING,
Booking::STATUS_PASSENGER_ON_BOARD,
Booking::STATUS_ABOUT_TO_DROP,
],
'completed' => [Booking::STATUS_COMPLETED],
'cancelled' => [
Booking::STATUS_CANCELLED_OTHER_REASON,
Booking::STATUS_CLIENT_CANCELLATION,
Booking::STATUS_CLIENT_NOT_SHOW_UP,
Booking::STATUS_CAR_BROKE_DOWN,
Booking::STATUS_OFFICE_CANCELLATION,
],
'pending-cancelled' => [Booking::STATUS_PENDING_CANCELLATION],
];
/**
* Display the booking request history for this booking.
*
* @param string $key - the Booking key
*
* @return Response
*/
public function bookingRequestHistoryAction($key, $return = false) {
$history = $this->get('request.service')->getBookingHistory($key);
return $this->render('@Admin/BookingRequest/history_list.html.twig', [
'history' => $history,
'return' => $return
]);
}
/**
* Display the booking request history.
*
* @param string $key - the Booking key
*
* @return Response
*/
public function requestHistoryAction($key) {
$history = $this->get('request.service')->getHistory($key);
return $this->render('@Admin/BookingRequest/history.html.twig', [
'history' => $history,
'key' => $key,
'return' => false
]);
}
/**
* @param Request $request
* @return JsonResponse
*/
public function sendEmailAction(Request $request)
{
$emailNumber = $request->request->get('emailNumber');
$bookingId = $request->request->get('bookingId');
$mandrillManager = $this->get('mandrill.manager');
$distance_unit = $this->get('doctrine')->getRepository(Settings::class)->findOneBy([
'key' => 'distance_unit',
]);
$distance_unit = $distance_unit ? $distance_unit->getValue() : 'Miles';
$dateFormat = 'd/m/Y';
$booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
if ($booking->isCancel()) {
return new JsonResponse([
'success' => false,
'status' => 400,
'message' => 'The booking was canceled',
]);
}
$officeEmail = $this->get('settings_repo')->getOfficeEmail();
switch ($emailNumber) {
case 't1':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_NEW_BOOKING_CLIENT, [],
[
'subject' => 'Twelve Transfers - Journey Confirmation',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_NEW_BOOKING_CLIENT),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"passenger_phone" => $booking->getClientPhone(),
"passenger_email" => $booking->getClientEmail(),
"booking_key" => $booking->getKey(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"booking_dropoff_location" => $booking->getDestinationAddress(),
"booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
return "<li>$address</li>";
}, $booking->getViasAsArray())) . "</ul>",
"booking_passengers" => $booking->getPassengersNumber(),
"booking_luggage" => $booking->getCheckinLuggage(),
"booking_notes" => $booking->getNotes(),
"booking_cost" => $booking->getOverridePrice(),
"currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
"booking_duration" => $booking->getEstimatedTimePrettyFormat(),
"booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
"booking_hand_luggage" => $booking->getHandLuggage(),
"booking_car_type" => $booking->getCarType()->getName(),
"premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
"return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
"return_booking" => !empty($booking->getReturnBooking()) ? true : null,
"return_booking_key" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getKey() : null,
"return_booking_pickup_date" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getPickUpDate()->format($dateFormat) : null,
"return_booking_pickup_time" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getPickUpTime() : null,
"return_booking_pickup_location" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getPickUpAddress() : null,
"return_booking_dropoff_location" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getDestinationAddress() : null,
"return_booking_vias_content" => $booking->getReturnBooking() ? "<ul>" . implode("", array_map(function ($address) {
return "<li>$address</li>";
}, $booking->getReturnBooking()->getViasAsArray())) . "</ul>" : null,
"return_booking_notes" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getNotes() : null,
"return_booking_cost" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getOverridePrice() : null,
"return_booking_duration" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getEstimatedTimePrettyFormat() : null,
"return_booking_distance" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getDistanceUnit() . ' ' . $distance_unit : null,
"flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
"landing_time" => $booking->getFlightLandingTime(),
"mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
"return_flight_number" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getFlightNumber() : null,
"return_landing_time" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getFlightLandingTime() : null,
"return_mg_timeframe" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getMeetAndGreetTimePrettyFormat() : null,
"booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
$name = $objective['name'];
//$price = $objective['price'];
return "<li>$name</li>";
}, $booking->getObjectivesAsArray())) . "</ul>",
"return_booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
$name = $objective['name'];
//$price = $objective['price'];
return "<li>$name</li>";
}, $booking->getReturnObjectivesAsArray())) . "</ul>",
],
'merge_language' => 'mailchimp',
]
);
break;
case 't2':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_NEW_BOOKING_OFFICE, [],
[
'subject' => 'New Booking has been Created',
'from_email' => $officeEmail,
'to' => [
'email' => $officeEmail,
'name' => 'Twelve Transfers',
'type' => 'to',
],
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"passenger_phone" => $booking->getClientPhone(),
"passenger_email" => $booking->getClientEmail(),
"booking_key" => $booking->getKey(),
"booking_creation_date" => $booking->getBookingDate()->format($dateFormat),
"booking_creation_time" => $booking->getBookingDate()->format('H:i'),
"booking_origin" => 'TBD:origin', //todo: update this
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"booking_dropoff_location" => $booking->getDestinationAddress(),
"booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
return "<li>$address</li>";
}, $booking->getViasAsArray())) . "</ul>",
"booking_passengers" => $booking->getPassengersNumber(),
"booking_luggage" => $booking->getCheckinLuggage(),
"booking_notes" => $booking->getNotes(),
"booking_cost" => $booking->getOverridePrice(),
"currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
"booking_duration" => $booking->getEstimatedTimePrettyFormat(),
"booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
"booking_hand_luggage" => $booking->getHandLuggage(),
"booking_car_type" => $booking->getCarType()->getName(),
"flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
"landing_time" => $booking->getFlightLandingTime(),
"mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
"booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
$name = $objective['name'];
//$price = $objective['price'];
return "<li>$name</li>";
}, $booking->getObjectivesAsArray())) . "</ul>",
],
'merge_language' => 'mailchimp',
]
);
break;
case 't3':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_BOOKING_COMPLETED, [],
[
'subject' => 'Twelve Transfers - Booking Completed',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_BOOKING_COMPLETED),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"booking_review_link" => $this->getParameter('assets_base_url') . 'review/' . $booking->getKey(),
],
'merge_language' => 'mailchimp',
]
);
break;
case 't4':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_BOOKING_CANCELLED, [],
[
'subject' => 'Twelve Transfers - Booking Cancelled',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_BOOKING_CANCELLED),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"booking_key" => $booking->getKey(),
"passenger_phone" => $booking->getClientPhone(),
"passenger_email" => $booking->getClientEmail(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"booking_dropoff_location" => $booking->getDestinationAddress(),
"booking_cancel_reason" => $booking->getCancelReason(),
"booking_cancel_charge" => $booking->getCancelRefund(),
],
'merge_language' => 'mailchimp',
]
);
break;
case 't5':
/** @var Driver $driver */
$driver = $booking->getDriver();
if (empty($driver)) {
return new JsonResponse([
'success' => false,
'status' => 404,
'message' => 'The booking haven\'t a driver',
]);
}
/** @var Car $car */
$car = $driver->getCar();
if (empty($car)) {
return new JsonResponse([
'success' => false,
'status' => 404,
'message' => 'The driver haven\'t assigned a car. Check if the driver have a correct setup.',
]);
}
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_DRIVER_ALLOCATED, [], [
'subject' => 'Twelve Transfers - Your Driver\'s Details',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_DRIVER_ALLOCATED),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"booking_key" => $booking->getKey(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
"return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
"driver_name" => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
"driver_PCO" => $driver->getPublicCarriageOfficeLicenceNumber(),
"driver_HACK" => $driver->getHackLicenseNumber(),
"driver_SSN" => $driver->getSocialSecurityNumber(),
"driver_phone" => $driver->getPhone(),
"driver_vehicle_name" => $car->getMaker() . ' ' . $car->getModel(),
"driver_vehicle_plate" => $car->getPlateNumber(),
"driver_vehicle_PHV" => $car->getPhvLicenseNumber(),
"driver_vehicle_LIMO" => $car->getLimoLicenseNumber(),
"driver_picture" => $this->getParameter('assets_base_url') . (!empty($driver->getPicture()) ? $driver->getPicturePath() : 'bundles/admin/img/driver/default_driver_image.png'),
"driver_vehicle_color" => $car->getColor(),
],
'merge_language' => 'mailchimp',
]
);
break;
case 't6':
/** @var Driver $driver */
$driver = $booking->getDriver();
if (empty($driver)) {
return new JsonResponse([
'success' => false,
'status' => 404,
'message' => 'The booking haven\'t a driver',
]);
}
/** @var Car $car */
$car = $driver->getCar();
if (empty($car)) {
return new JsonResponse([
'success' => false,
'status' => 404,
'message' => 'The driver haven\'t assigned a car. Check if the driver have a correct setup.',
]);
}
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_DRIVER_REALLOCATED, [], [
'subject' => 'Twelve Transfers - Your Driver has Changed',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_DRIVER_REALLOCATED),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"booking_key" => $booking->getKey(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
"return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
"driver_name" => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
"driver_PCO" => $driver->getPublicCarriageOfficeLicenceNumber(),
"driver_HACK" => $driver->getHackLicenseNumber(),
"driver_SSN" => $driver->getSocialSecurityNumber(),
"driver_phone" => $driver->getPhone(),
"driver_vehicle_name" => $car->getMaker() . ' ' . $car->getModel(),
"driver_vehicle_plate" => $car->getPlateNumber(),
"driver_vehicle_PHV" => $car->getPhvLicenseNumber(),
"driver_vehicle_LIMO" => $car->getLimoLicenseNumber(),
"driver_picture" => $this->getParameter('assets_base_url') . (!empty($driver->getPicture()) ? $driver->getPicturePath() : 'bundles/admin/img/driver/default_driver_image.png'),
"driver_vehicle_color" => $car->getColor(),
],
'merge_language' => 'mailchimp',
]
);
break;
case 't7':
/** @var Driver $driver */
$driver = $booking->getDriver();
if (empty($driver)) {
return new JsonResponse([
'success' => false,
'status' => 404,
'message' => 'The booking haven\'t a driver',
]);
}
/** @var Car $car */
$car = $driver->getCar();
if (empty($car)) {
return new JsonResponse([
'success' => false,
'status' => 404,
'message' => 'The driver haven\'t assigned a car. Check if the driver have a correct setup.',
]);
}
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_DRIVER_ARRIVED, [], [
'subject' => 'Twelve Transfers - Your Driver has Arrived',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_DRIVER_ARRIVED),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"booking_key" => $booking->getKey(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
"return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
"driver_name" => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
"driver_PCO" => $driver->getPublicCarriageOfficeLicenceNumber(),
"driver_HACK" => $driver->getHackLicenseNumber(),
"driver_SSN" => $driver->getSocialSecurityNumber(),
"driver_phone" => $driver->getPhone(),
"driver_vehicle_name" => $car->getMaker() . ' ' . $car->getModel(),
"driver_vehicle_plate" => $car->getPlateNumber(),
"driver_vehicle_PHV" => $car->getPhvLicenseNumber(),
"driver_vehicle_LIMO" => $car->getLimoLicenseNumber(),
"driver_picture" => $this->getParameter('assets_base_url') . (!empty($driver->getPicture()) ? $driver->getPicturePath() : 'bundles/admin/img/driver/default_driver_image.png'),
"driver_vehicle_color" => $car->getColor(),
],
'merge_language' => 'mailchimp',
]
);
break;
case 't7.5':
/** @var Driver $driver */
$driver = $booking->getDriver();
if (empty($driver)) {
return new JsonResponse([
'success' => false,
'status' => 404,
'message' => 'The booking haven\'t a driver',
]);
}
/** @var Car $car */
$car = $driver->getCar();
if (empty($car)) {
return new JsonResponse([
'success' => false,
'status' => 404,
'message' => 'The driver haven\'t assigned a car. Check if the driver have a correct setup.',
]);
}
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_DRIVER_WAITING, [], [
'subject' => 'Twelve Transfers - Your Driver is Waiting',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_DRIVER_WAITING),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"booking_key" => $booking->getKey(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
"return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
"driver_name" => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
"driver_PCO" => $driver->getPublicCarriageOfficeLicenceNumber(),
"driver_HACK" => $driver->getHackLicenseNumber(),
"driver_SSN" => $driver->getSocialSecurityNumber(),
"driver_phone" => $driver->getPhone(),
"driver_vehicle_name" => $car->getMaker() . ' ' . $car->getModel(),
"driver_vehicle_plate" => $car->getPlateNumber(),
"driver_vehicle_PHV" => $car->getPhvLicenseNumber(),
"driver_vehicle_LIMO" => $car->getLimoLicenseNumber(),
"driver_picture" => $this->getParameter('assets_base_url') . (!empty($driver->getPicture()) ? $driver->getPicturePath() : 'bundles/admin/img/driver/default_driver_image.png'),
"driver_vehicle_color" => $booking->getDriver()->getCar()->getColor(),
],
'merge_language' => 'mailchimp',
]
);
break;
case 't8':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_PAYMENT_INITIAL, [],
[
'subject' => 'Twelve Transfers - Payment Link',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_PAYMENT_INITIAL),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"payment_link" => $this->get('payment.helper')->generateUrl($this->get('payment.helper')->generateToken($booking->getPayment(), $booking->getPayment()->getAmountLeft())),
"booking_key" => $booking->getKey(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"booking_dropoff_location" => $booking->getDestinationAddress(),
"booking_cost" => $booking->getPayment()->getAmountLeft(),
"currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
],
'merge_language' => 'mailchimp',
]
);
break;
case 't9':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_PAYMENT_REMINDER, [],
[
'subject' => 'Twelve Transfers - Payment Link Reminder',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_PAYMENT_REMINDER),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"payment_link" => $this->get('payment.helper')->generateUrl($this->get('payment.helper')->generateToken($booking->getPayment(), $booking->getPayment()->getAmountLeft())),
"booking_key" => $booking->getKey(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"booking_dropoff_location" => $booking->getDestinationAddress(),
"booking_cost" => $booking->getPayment()->getAmountLeft(),
"currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
],
'merge_language' => 'mailchimp',
]
);
break;
case 't10':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_PAYMENT_WARNING, [],
[
'subject' => 'Twelve Transfers - WARNING - Payment Link Reminder',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_PAYMENT_WARNING),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"payment_link" => $this->get('payment.helper')->generateUrl($this->get('payment.helper')->generateToken($booking->getPayment(), $booking->getPayment()->getAmountLeft())),
"booking_key" => $booking->getKey(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"booking_dropoff_location" => $booking->getDestinationAddress(),
"booking_cost" => $booking->getPayment()->getAmountLeft(),
"currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
],
'merge_language' => 'mailchimp',
]
);
break;
case 't11':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_PENDING_CANCELLED, [],
[
'subject' => 'Twelve Transfers - WARNING - Pending Cancellation',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_PENDING_CANCELLED),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"booking_key" => $booking->getKey(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"booking_dropoff_location" => $booking->getDestinationAddress(),
"booking_cost" => $booking->getPayment()->getAmountLeft(),
"currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
"payment_link" => $this->get('payment.helper')->generateUrl($this->get('payment.helper')->generateToken($booking->getPayment(), $booking->getPayment()->getAmountLeft())),
],
'merge_language' => 'mailchimp',
]
);
break;
case 't12':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_BOOKING_UPDATE, [],
[
'subject' => 'Twelve Transfers - Booking has been Updated',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_BOOKING_UPDATE),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"booking_key" => $booking->getKey(),
"passenger_phone" => $booking->getClientPhone(),
"passenger_email" => $booking->getClientEmail(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"booking_dropoff_location" => $booking->getDestinationAddress(),
"booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
return "<li>$address</li>";
}, $booking->getViasAsArray())) . "</ul>",
"booking_passengers" => $booking->getPassengersNumber(),
"booking_luggage" => $booking->getCheckinLuggage(),
"booking_notes" => $booking->getNotes(),
"booking_cost" => $booking->getPayment()->getAmount(),
"premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
"return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
"currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
"booking_duration" => $booking->getEstimatedTimePrettyFormat(),
"booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
"booking_hand_luggage" => $booking->getHandLuggage(),
"booking_car_type" => $booking->getCarType()->getName(),
"flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
"landing_time" => $booking->getFlightLandingTime(),
"mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
"booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
$name = $objective['name'];
//$price = $objective['price'];
return "<li>$name</li>";
}, $booking->getObjectivesAsArray())) . "</ul>",
],
'merge_language' => 'mailchimp',
]
);
break;
case 't13':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_BOOKING_RECONFIRM, [],
[
'subject' => 'Twelve Transfers - IMPORTANT - Please Confirm your Booking',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_BOOKING_RECONFIRM),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"booking_key" => $booking->getKey(),
"passenger_phone" => $booking->getClientPhone(),
"passenger_email" => $booking->getClientEmail(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"booking_dropoff_location" => $booking->getDestinationAddress(),
"booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
return "<li>$address</li>";
}, $booking->getViasAsArray())) . "</ul>",
"booking_passengers" => $booking->getPassengersNumber(),
"booking_luggage" => $booking->getCheckinLuggage(),
"booking_notes" => $booking->getNotes(),
"booking_cost" => $booking->getPayment()->getAmount(),
"premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
"return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
"currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
"booking_duration" => $booking->getEstimatedTimePrettyFormat(),
"booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
"booking_hand_luggage" => $booking->getHandLuggage(),
"booking_car_type" => $booking->getCarType()->getName(),
"flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
"landing_time" => $booking->getFlightLandingTime(),
"mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
"booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
$name = $objective['name'];
//$price = $objective['price'];
return "<li>$name</li>";
}, $booking->getObjectivesAsArray())) . "</ul>",
],
'merge_language' => 'mailchimp',
]
);
break;
case 't14':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_BOOKING_APPROACHING, [],
[
'subject' => 'Twelve Transfers - Journey Reminder',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_BOOKING_APPROACHING),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"booking_key" => $booking->getKey(),
"passenger_phone" => $booking->getClientPhone(),
"passenger_email" => $booking->getClientEmail(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"booking_dropoff_location" => $booking->getDestinationAddress(),
"booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
return "<li>$address</li>";
}, $booking->getViasAsArray())) . "</ul>",
"booking_passengers" => $booking->getPassengersNumber(),
"booking_luggage" => $booking->getCheckinLuggage(),
"booking_notes" => $booking->getNotes(),
"booking_cost" => $booking->getPayment()->getAmount(),
"premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
"return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
"currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
"booking_duration" => $booking->getEstimatedTimePrettyFormat(),
"booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
"booking_hand_luggage" => $booking->getHandLuggage(),
"booking_car_type" => $booking->getCarType()->getName(),
"flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
"landing_time" => $booking->getFlightLandingTime(),
"mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
"booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
$name = $objective['name'];
//$price = $objective['price'];
return "<li>$name</li>";
}, $booking->getObjectivesAsArray())) . "</ul>",
],
'merge_language' => 'mailchimp',
]
);
break;
case 't15':
/** @var Driver $driver */
$driver = $booking->getDriver();
if (empty($driver)) {
return new JsonResponse([
'success' => false,
'status' => 404,
'message' => 'The booking haven\'t a driver',
]);
}
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_DRIVER_REGISTERED, [],
[
'subject' => 'Twelve Transfers - Welcome',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_PENDING_BOOKING),
'global_merge_vars' => [
"driver_name" => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
"driver_ID" => $driver->getInternalName(),
"driver_PCO" => $driver->getPublicCarriageOfficeLicenceNumber(),
"driver_HACK" => $driver->getHackLicenseNumber(),
"driver_SSN" => $driver->getSocialSecurityNumber(),
"driver_phone" => $driver->getPhone(),
"driver_email" => $driver->getUser()->getEmail(),
"driver_vehicle_name" => $driver->getCar()->getMaker() . ' ' . $driver->getCar()->getModel(),
"driver_vehicle_plate" => $driver->getCar()->getPlateNumber(),
"driver_vehicle_PHV" => $driver->getCar()->getPhvLicenseNumber(),
"driver_vehicle_LIMO" => $driver->getCar()->getLimoLicenseNumber(),
"driver_vehicle_color" => $driver->getCar()->getColor(),
],
'merge_language' => 'mailchimp',
]
);
break;
case 't16':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_PENDING_BOOKING, [],
[
'subject' => 'Twelve Transfers - Booking Attempt',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_PENDING_BOOKING),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"booking_key" => $booking->getKey(),
"payment_link" => $this->get('payment.helper')->generateUrl($this->get('payment.helper')->generateToken($booking->getPayment(), $booking->getPayment()->getAmountLeft())),
],
'merge_language' => 'mailchimp',
]
);
break;
case 't25':
$statusEmail = $mandrillManager->sendTemplate(
MandrillManager::$TEMPLATE_SHUTTLE_ENQUIRY, [],
[
'subject' => 'Twelve Transfers - Lower Rates with our Shuttle Option',
'from_email' => $officeEmail,
'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_SHUTTLE_ENQUIRY),
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"passenger_phone" => $booking->getClientPhone(),
"passenger_email" => $booking->getClientEmail(),
"booking_key" => $booking->getKey(),
"booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"booking_dropoff_location" => $booking->getDestinationAddress(),
"booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
return "<li>$address</li>";
}, $booking->getViasAsArray())) . "</ul>",
"booking_passengers" => $booking->getPassengersNumber(),
"booking_luggage" => $booking->getCheckinLuggage(),
"booking_notes" => $booking->getNotes(),
"booking_cost" => $booking->getOverridePrice(),
"currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
"booking_duration" => $booking->getEstimatedTimePrettyFormat(),
"booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
"booking_hand_luggage" => $booking->getHandLuggage(),
"booking_car_type" => $booking->getCarType()->getName(),
"return_booking" => !empty($booking->getReturnBooking()) ? true : null,
"return_booking_key" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getKey() : null,
"return_booking_pickup_date" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getPickUpDate()->format($dateFormat) : null,
"return_booking_pickup_time" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getPickUpTime() : null,
"return_booking_pickup_location" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getPickUpAddress() : null,
"return_booking_dropoff_location" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getDestinationAddress() : null,
"return_booking_vias_content" => $booking->getReturnBooking() ? "<ul>" . implode("", array_map(function ($address) {
return "<li>$address</li>";
}, $booking->getReturnBooking()->getViasAsArray())) . "</ul>" : null,
"return_booking_notes" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getNotes() : null,
"return_booking_cost" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getOverridePrice() : null,
"return_booking_duration" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getEstimatedTimePrettyFormat() : null,
"return_booking_distance" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getDistanceUnit() . ' ' . $distance_unit : null,
"flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
"landing_time" => $booking->getFlightLandingTime(),
"mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
"return_flight_number" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getFlightNumber() : null,
"return_landing_time" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getFlightLandingTime() : null,
"return_mg_timeframe" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getMeetAndGreetTimePrettyFormat() : null,
"booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
$name = $objective['name'];
//$price = $objective['price'];
return "<li>$name</li>";
}, $booking->getObjectivesAsArray())) . "</ul>",
"return_booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
$name = $objective['name'];
//$price = $objective['price'];
return "<li>$name</li>";
}, $booking->getReturnObjectivesAsArray())) . "</ul>",
],
'merge_language' => 'mailchimp',
]
);
break;
}
foreach ($statusEmail as $status) {
if ($status['status'] != 'sent') {
return new JsonResponse([
'success' => false,
'status' => 500,
'message' => 'Reject Reason: ' . $status['reject_reason'],
]);
}
}
return new JsonResponse([
'success' => true,
'status' => 200,
'message' => 'The mail has been sent successfully',
]);
}
public function bookingTakeoverAction(Request $request, $id) {
$user = false;
if ($token = $this->get('security.token_storage')->getToken()) {
$user = $token->getUser();
}
if ($user) {
$email = $user->getEmail();
$pool = $this->get('sonata.admin.pool');
$admin = $pool->getAdminByAdminCode('admin.booking');
$url = $admin->generateUrl('edit', ['id' => $id]);
$admin->setRequest($request);
$booking = $admin->getObject($id);
$admin->setSubject($booking);
$booking->isOpen($email);
$booking = $admin->update($booking);
} else {
$url = $this->generateUrl('sonata_admin_dashboard');
}
return new RedirectResponse(
$url
);
}
public function getBookingDriversAction($bookingId)
{
$booking = $this->get('doctrine')->getRepository(Booking::class)->find($bookingId);
$drivers = $this->getDoctrine()->getRepository(Driver::class)->createQueryBuilder('d')
->join('d.car', 'c')
->join('c.type', 'ct', Join::WITH, 'ct.passengers >= :limit_passangers')
->where('d.status = :status_active')
->setParameter('limit_passangers', $booking->getPassengersNumber())
->setParameter('status_active', Driver::STATUS_ACTIVE)
->getQuery()->getResult();
$broadcastedDrivers = $this->getDoctrine()->getRepository(BroadcastedDriver::class)->findBy([
'booking' => $bookingId,
'status' => BroadcastedDriver::STATUS_APPROVED,
]);
$response = [
'manual_dispatch' => [],
'brodcasted' => [],
];
$broadcastedDriversIds = [];
/** @var BroadcastedDriver $broadcastedDriver */
foreach ($broadcastedDrivers as $broadcastedDriver) {
$driver = $broadcastedDriver->getDriver();
$car = $driver->getCar();
if ($car->getType()->getPassengers() >= $booking->getPassengersNumber()) {
$broadcastedDriversIds[] = $driver->getId();
$response['brodcasted'][] = [
'id' => $driver->getId(),
'name' => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
'internalName' => $driver->getInternalName(),
];
}
}
foreach ($drivers as $driver) {
if (!in_array($driver->getId(), $broadcastedDriversIds)) {
$maxNumberOfPassengers = $car = $driver->getCar()->getMaxNumberOfPassengers();
if (isset($maxNumberOfPassengers) && ($maxNumberOfPassengers < $booking->getPassengersNumber())) {
continue;
}
$response['manual_dispatch'][] = [
'id' => $driver->getId(),
'name' => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
'internalName' => $driver->getInternalName(),
];
}
}
return new JsonResponse($response);
}
public function preAssignBookingDriverAction(Request $request)
{
$driverId = $request->request->get('driverId');
$bookingId = $request->request->get('bookingId');
$driver = $this->getDoctrine()->getRepository(Driver::class)->findOneBy(['id' => $driverId]);
$booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
if ($booking->isCancel()) {
return new JsonResponse([
'success' => true,
'status' => 400,
'message' => 'The booking was canceled',
]);
}
$booking->setNeedSendToDriver(true);
$booking->setDriver($driver);
$this->getDoctrine()->getManager()->persist($booking);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([
'success' => true,
'status' => 200,
'message' => 'Driver has been successfully pre-assigned',
]);
}
public function selectBookingDriverAction(Request $request)
{
$driverId = $request->request->get('driverId');
$bookingId = $request->request->get('bookingId');
$em = $this->getDoctrine()->getManager();
$driver = $em->getRepository(Driver::class)->findOneBy(['id' => $driverId]);
$booking = $em->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
if ($booking->isCancel()) {
return new JsonResponse([
'success' => true,
'status' => 400,
'message' => 'The booking was canceled',
]);
}
$checkDriverShift = $this->get('driver.service')->getDriverShiftStatus($driver,$booking->getPickUpDateTime());
if(!empty($checkDriverShift)) {
$entityManager = $this->getDoctrine()->getManager();
$bookingHistoryDriver = new BookingHistory();
$bookingHistoryDriver->setBooking($booking);
$bookingHistoryDriver->setActionType(BookingHistory::ACTION_DRIVER_SHIFT_TEST);
$bookingHistoryDriver->setUser($driver->getUser());
$bookingHistoryDriver->setPayload($checkDriverShift);
$entityManager->persist($bookingHistoryDriver);
$entityManager->flush();
$blockTimeShiftBookings = $entityManager->getRepository(Settings::class)->findOneBy([
'key'=>'block_time_shift_bookings',
'type' => Settings::TYPE_API_DRIVER
]);
if (!empty($blockTimeShiftBookings) and $blockTimeShiftBookings->getValue() and $checkDriverShift['status'] == JsonResponse::HTTP_FORBIDDEN) {
return new JsonResponse($checkDriverShift);
}
}
$currentDriverUser = $driver->getUser();
$payload = [
'current_user_id' => $currentDriverUser->getId(),
'current_user_name' => $currentDriverUser->getFullname(),
'current_user_email' => $currentDriverUser->getEmail(),
];
if ($booking->getDriver()) {
$payload['old_user_id'] = $booking->getDriver()->getUser()->getId();
$payload['old_user_name'] = $booking->getDriver()->getUser()->getFullName();
$payload['old_user_email'] = $booking->getDriver()->getUser()->getEmail();
}
$booking->setNeedSendToDriver(false);
$booking->setDriver($driver);
$booking->setStatus(Booking::STATUS_DISPATCHED);
$driverHistory = $this
->get('driver-history.service')
->create(
$driver,
$booking->getKey(),
DriverHistory::VALUE_MANUALLY_DISPATCH,
Driver::REPUTATION_POINTS_BOOKING_MANUALLY_DISPATCH,
DriverHistory::TYPE_BOOKING
);
$driver->addReputationPoints(Driver::REPUTATION_POINTS_BOOKING_MANUALLY_DISPATCH);
$em->persist($driverHistory);
$em->persist($driver);
$em->persist($booking);
$em->flush();
$driverUser = $driver->getUser();
return new JsonResponse([
'success' => true,
'status' => 200,
'message' => 'Driver has been successfully selected',
'driver' => [
'firstName' => $driverUser->getFirstname(),
'lastName' => $driverUser->getLastname(),
'phone' => $driver->getPhone(),
],
]);
}
public function preAssignBookingsDriverAction(Request $request)
{
$driverId = $request->request->get('driverId');
$bookingIds = $request->request->get('bookingIds');
$bookingIdsArray = explode(',', $bookingIds);
$driver = $this->getDoctrine()->getRepository(Driver::class)->findOneBy(['id' => $driverId]);
foreach ($bookingIdsArray as $bookingId) {
$booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
if ($booking->isCancel()) {
return new JsonResponse([
'success' => true,
'status' => 400,
'message' => 'The booking was canceled',
]);
}
$booking->setNeedSendToDriver(true);
$booking->setDriver($driver);
$this->getDoctrine()->getManager()->persist($booking);
}
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([
'success' => true,
'status' => 200,
]);
}
public function selectBookingsDriverAction(Request $request)
{
$driverId = $request->request->get('driverId');
$bookingIds = $request->request->get('bookingIds');
$bookingIdsArray = explode(',', $bookingIds);
$driver = $this->getDoctrine()->getRepository(Driver::class)->findOneBy(['id' => $driverId]);
$currentDriverUser = $driver->getUser();
$payload = [
'current_user_id' => $currentDriverUser->getId(),
'current_user_name' => $currentDriverUser->getFullname(),
'current_user_email' => $currentDriverUser->getEmail(),
];
foreach ($bookingIdsArray as $bookingId) {
$booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
if (!$booking) {
return new JsonResponse([
'success' => true,
'status' => 400,
'message' => 'Invalid booking id',
]);
}
if ($booking->isCancel()) {
return new JsonResponse([
'success' => true,
'status' => 400,
'message' => 'The booking was canceled',
]);
}
if ($booking->getDriver()) {
$payload['old_user_id'] = $booking->getDriver()->getUser()->getId();
$payload['old_user_name'] = $booking->getDriver()->getUser()->getFullName();
$payload['old_user_email'] = $booking->getDriver()->getUser()->getEmail();
}
$booking->setNeedSendToDriver(false);
$booking->setDriver($driver);
$booking->setStatus(Booking::STATUS_DISPATCHED);
$this->getDoctrine()->getManager()->persist($booking);
}
$this->getDoctrine()->getManager()->flush();
$driverUser = $driver->getUser();
return new JsonResponse([
'success' => true,
'status' => 200,
'message' => 'Driver has been successfully selected',
'driver' => [
'firstName' => $driverUser->getFirstname(),
'lastName' => $driverUser->getLastname(),
'phone' => $driver->getPhone(),
],
]);
}
public function broadcastAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$bookingId = $request->request->get('bookingId');
$carTypeIds = $request->request->get('carTypeIds');
$booking = $em->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
$driver = $booking->getDriver();
if ($booking->isExpireBroadcast() || $driver) {
return new JsonResponse([
'success' => false,
'status' => JsonResponse::HTTP_BAD_REQUEST,
]);
}
if ($booking->isCancel()) {
return new JsonResponse([
'success' => true,
'status' => JsonResponse::HTTP_BAD_REQUEST,
'message' => 'The booking was canceled',
]);
}
$em->getRepository(BroadcastedDriver::class)->removeBroadcastedDrivers($bookingId);
$drivers = $em->getRepository(Driver::class)->getDriversByCarTypes($carTypeIds);
foreach ($drivers as $driver) {
$broadcast = new BroadcastedDriver();
$broadcast->setBooking($booking);
$broadcast->setDriver($driver);
$user = $driver->getUser();
if ($user && $user->getApiKey()) {
$now = new \DateTime();
$this->get('websocket_notification.service')->send([
'apiKey' => $user->getApiKey(),
'data' => [
'event' => NotificationPusher::SEND_BOOKING_BROADCAST_EVENT,
'booking' => $booking->getKey(),
'message' => "You have a new broadcast booking request notification for booking #{$booking->getKey()} at {$now->format('Y-m-d H:i')}",
'pickup_date_time' => $booking->getPickUpDateTime()->format('Y-m-d H:i:s')
],
], [
'title' => "You have a new broadcast booking request notification for booking #{$booking->getKey()} at {$now->format('Y-m-d H:i')}",
'body' => 'Please check details.'
]);
}
$em->persist($broadcast);
}
$expireBroadcastDate = new \DateTime();
$expireBroadcastDate->modify("+1 hours");
$booking->setExpireBroadcastDate($expireBroadcastDate);
$booking->setStatus(Booking::STATUS_BROADCAST);
$booking->setDriversConfirmedNumber(0);
$em->persist($booking);
$em->flush();
return new JsonResponse([
'success' => true,
'status' => JsonResponse::HTTP_OK,
]);
}
public function getDashboardBookingsAction(Request $request)
{
$doctrine = $this->get('doctrine');
$lastUpdate = $request->request->get('lastTime');
/** @var QueryBuilder $queryBuilderHistory */
$queryBuilderHistory = $doctrine
->getRepository(BookingHistory::class)
->createQueryBuilder('h')
->select('b.id AS bookingId')
->leftJoin(Booking::class, 'b', Join::WITH, 'h.booking=b.id')
->groupBy('h.booking')
->orderBy('h.date', 'DESC')
;
if ($lastUpdate > 0) {
$queryBuilderHistory
->andWhere('h.date > :fromDate')
->setParameter('fromDate', (new \DateTime())->setTimestamp($lastUpdate))
;
}
$bookingsIds = $queryBuilderHistory
->setMaxResults(50)
->getQuery()
->getArrayResult()
;
$inIds = array_column($bookingsIds, 'bookingId');
if (empty($inIds)) {
return new JsonResponse([
'results' => [],
'lastTime' => $lastUpdate,
]);
}
$statuses = [];
foreach ($request->request->get('status', []) as $value) {
$statuses = array_merge($statuses, self::$mapDashboardStatusRequest[$value]);
}
if (empty($statuses)) {
$statuses[] = '-1';
}
/** @var QueryBuilder $queryBuilder */
$queryBuilder = $doctrine
->getRepository(Booking::class)
->createQueryBuilder('b')
;
$queryBuilder
->where($queryBuilder->expr()->in('b.status', $statuses))
->andWhere($queryBuilder->expr()->in('b.id', $inIds))
;
$queryBuilderPickUpAddress = null;
$queryBuilderDestinationAddress = null;
$queryBuilderDriver = null;
$queryBuildersClient = [
'first_name' => null,
'last_name' => null,
'phone' => null,
'email' => null,
];
$searchKey = $request->request->get('key');
if (!empty($searchKey)) {
$queryBuilderPickUpAddress = clone $queryBuilder;
$queryBuilderDestinationAddress = clone $queryBuilder;
$queryBuilderDriver = clone $queryBuilder;
$queryBuildersClient = [
'first_name' => clone $queryBuilder,
'last_name' => clone $queryBuilder,
'phone' => is_numeric(str_replace('+', '', $searchKey)) ? clone $queryBuilder : null,
'email' => clone $queryBuilder,
];
$queryBuilder->andWhere($queryBuilder->expr()->like('b.key', "'$searchKey%'"));
$queryBuilderPickUpAddress->andWhere($queryBuilderPickUpAddress->expr()->like('b.pickUpAddress', "'%$searchKey%'"));
$queryBuilderDestinationAddress->andWhere($queryBuilderDestinationAddress->expr()->like('b.destinationAddress', "'%$searchKey%'"));
$queryBuilderDriver
->innerJoin('b.driver', 'd', Join::WITH, 'd.internalName like :search')
->setParameter('search', "$searchKey%")
;
$queryBuildersClient['first_name']->andWhere('b.clientFirstName like :search')->setParameter('search', "$searchKey%");
$queryBuildersClient['last_name']->andWhere('b.clientLastName like :search')->setParameter('search', "$searchKey%");
if ($queryBuildersClient['phone'] != null) {
$queryBuildersClient['phone']->andWhere('b.clientPhone like :search')->setParameter('search', "$searchKey%");
}
$queryBuildersClient['email']->andWhere('b.clientEmail like :search')->setParameter('search', "$searchKey%");
}
// $queryBuilder
// ->setFirstResult($request->request->get('startWith', 0))
// ->setMaxResults($request->request->get('limit', 5))
// ;
// $ignoreIds = $request->request->get('ignoreIds', []);
// if (!empty($ignoreIds)) {
// $queryBuilder->andWhere($queryBuilder->expr()->not($queryBuilder->expr()->in('b.id', $ignoreIds)));
// }
/** @var Booking[] $bookings */
$bookings = $queryBuilder
->setMaxResults(50)
->getQuery()
->getResult()
;
$limit = $request->request->get('limit', 5);
$ignoreIds = array_map(function (Booking $booking) {
return $booking->getId();
}, $bookings);
if (count($bookings) < $limit && $queryBuilderPickUpAddress != null) {
$queryBuilderPickUpAddress->setMaxResults($limit);
if (!empty($ignoreIds)) {
$queryBuilderPickUpAddress->andWhere($queryBuilderPickUpAddress->expr()->not($queryBuilderPickUpAddress->expr()->in('b.id', $ignoreIds)));
}
/** @var Booking $b */
foreach ($queryBuilderPickUpAddress->getQuery()->getResult() as $b) {
$ignoreIds[] = $b->getId();
if (count($bookings) < $limit) {
$bookings[] = $b;
} else {
break;
}
}
}
if (count($bookings) < $limit && $queryBuilderDestinationAddress != null) {
$queryBuilderDestinationAddress->setMaxResults($limit);
if (!empty($ignoreIds)) {
$queryBuilderDestinationAddress->andWhere($queryBuilderDestinationAddress->expr()->not($queryBuilderDestinationAddress->expr()->in('b.id', $ignoreIds)));
}
/** @var Booking $b */
foreach ($queryBuilderDestinationAddress->getQuery()->getResult() as $b) {
$ignoreIds[] = $b->getId();
if (count($bookings) < $limit) {
$bookings[] = $b;
} else {
break;
}
}
}
if (count($bookings) < $limit && $queryBuilderDriver != null) {
$queryBuilderDriver->setMaxResults($limit);
if (!empty($ignoreIds)) {
$queryBuilderDriver->andWhere($queryBuilderDriver->expr()->not($queryBuilderDriver->expr()->in('b.id', $ignoreIds)));
}
/** @var Booking $b */
foreach ($queryBuilderDriver->getQuery()->getResult() as $b) {
$ignoreIds[] = $b->getId();
if (count($bookings) < $limit) {
$bookings[] = $b;
} else {
break;
}
}
}
if (count($bookings) < $limit) {
/** @var QueryBuilder $qb */
foreach ($queryBuildersClient as $key => $qb) {
if ($qb != null) {
$qb->setMaxResults($limit);
if (!empty($ignoreIds)) {
$qb->andWhere($qb->expr()->not($qb->expr()->in('b.id', $ignoreIds)));
}
/** @var Booking $b */
foreach ($qb->getQuery()->getResult() as $b) {
$ignoreIds[] = $b->getId();
if (count($bookings) < $limit) {
$bookings[] = $b;
} else {
break 2;
}
}
}
}
}
$response = [];
/** @var RouterInterface $router */
$router = $this->get('router');
$cachedClassColors = [];
foreach (self::$mapDashboardStatusRequest as $key => $statuses) {
foreach ($statuses as $status) {
$cachedClassColors[$status] = $key;
}
}
$defaultCarType = Car::$carCtlfTypes[Car::CAR_TYPE_SALOON];
/** @var Booking $booking */
foreach ($bookings as $booking) {
/** @var \DateTime $lastBookingHistoryDate */
$lastBookingHistoryDate = $booking
->getBookingHistory()
->last()
->getDate()
;
$lastBookingHistoryTimestamp = $lastBookingHistoryDate->getTimestamp();
$response[] = [
'id' => $booking->getId(),
'key' => $booking->getKey(),
'url' => $router->generate('admin_admin_booking_edit', ['id' => $booking->getId()]),
'status' => Booking::$statusTypes[$booking->getStatus()],
'classColor' => array_key_exists($booking->getStatus(), $cachedClassColors)
? $cachedClassColors[$booking->getStatus()]
: '',
'pickUpAddress' => $booking->getPickUpAddress(),
'dropOfAddress' => $booking->getDestinationAddress(),
'pickUpTime' => "{$booking->getPickUpDate()->format('F d')} {$booking->getPickUpTime()}",
'price' => $booking->getOverridePrice(),
'carType' => empty($booking->getCarType())
? $defaultCarType
: $booking->getCarType()->getShortName(),
'updateTime' => $lastBookingHistoryDate->format('H:i:s'),
'updateDateTime' => $lastBookingHistoryTimestamp,
];
$lastUpdate = $lastUpdate < $lastBookingHistoryTimestamp
? $lastBookingHistoryTimestamp
: $lastUpdate
;
}
usort($response, function ($a, $b) {
return $a['updateDateTime'] - $b['updateDateTime'];
});
return new JsonResponse([
'results' => $lastUpdate == 1 ? array_reverse($response) : $response,
'lastTime' => $lastUpdate,
'dt' => (new \DateTime())
->setTimestamp($lastUpdate)
->format('d-m-Y H:i:s'),
]);
}
public function updateDashboardBookingsAction(Request $request)
{
$ids = $request->request->get('ids');
if (!empty($ids)) {
/** @var QueryBuilder $queryBuilder */
$queryBuilder = $this->get('doctrine')->getRepository(Booking::class)->createQueryBuilder('b');
$queryBuilder->where($queryBuilder->expr()->in('b.id', $ids));
$bookings = $queryBuilder->getQuery()->getResult();
$response = [];
/** @var Booking $booking */
foreach ($bookings as $booking) {
$response[] = [
'id' => $booking->getId(),
'key' => $booking->getKey(),
'url' => $this->get('router')->generate('admin_admin_booking_edit', ['id' => $booking->getId()]),
'status' => Booking::$statusTypes[$booking->getStatus()],
'classColor' => key(array_filter(self::$mapDashboardStatusRequest, function ($v, $k) use ($booking) {
return in_array($booking->getStatus(), $v);
}, ARRAY_FILTER_USE_BOTH)),
'pickUpAddress' => $booking->getPickUpAddress(),
'dropOfAddress' => $booking->getDestinationAddress(),
'pickUpTime' => $booking->getPickUpDate()->format('F d') . ' ' . $booking->getPickUpTime(),
'price' => $booking->getOverridePrice(),
'carType' => empty($booking->getCarType()) ? Car::$carCtlfTypes[Car::CAR_TYPE_SALOON] : $booking->getCarType()->getName(),
'updateTime' => count($booking->getBookingHistory()) ? $booking->getBookingHistory()->last()->getDate()->format('H:i:s') : $booking->getBookingDate()->format('H:i:s'),
'updateDateTime' => count($booking->getBookingHistory()) ? $booking->getBookingHistory()->last()->getDate()->getTimestamp() : $booking->getBookingDate()->getTimestamp(),
];
}
usort($response, function ($a, $b) {
return $a['updateDateTime'] - $b['updateDateTime'];
});
// $response = array_reverse($response);
$hash = md5(serialize($response) . $_SERVER['REMOTE_ADDR']);
if (isset($_SESSION['hash_list'])) {
if ($_SESSION['hash_list'] == $hash) {
$response = [];
}
}
$_SESSION['hash_list'] = $hash;
return new JsonResponse($response);
}
return new JsonResponse([]);
}
public function officeCancellationAction(Request $request)
{
$bookingId = $request->request->get('bookingId');
$cancelReason = $request->request->get('cancelReason');
$cancelRefund = $request->request->get('cancelRefund');
$booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
$booking->setStatus(Booking::STATUS_OFFICE_CANCELLATION);
$booking->setCancelReason($cancelReason);
$cancelPercent = 0;
if ($cancelRefund) {
//$cancelPercent = $cancelRefund/100;
$cancelPercent = $cancelRefund; // to be checked as the value inserted is in percent
}
$booking->setCancelRefund($cancelPercent);
$this->getDoctrine()->getManager()->persist($booking);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([
'success' => true,
'status' => 200,
]);
}
public function deleteAction(Request $request)
{
$bookingId = $request->request->get('bookingId');
$booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
$booking->setStatus(Booking::STATUS_DELETED);
$this->getDoctrine()->getManager()->persist($booking);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([
'success' => true,
'status' => 200,
]);
}
public function deleteASAPAction(Request $request)
{
$bookingId = $request->request->get('bookingId');
$booking_request = $this->getDoctrine()->getRepository(BookingRequest::class)->findOneBy(['id' => $bookingId]);
$booking_extras = $this->getDoctrine()->getRepository(BookingBookingExtra::class)->findOneBy(['bookingRequest' => $bookingId]);
$this->getDoctrine()->getManager()->remove($booking_request);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([
'success' => true,
'status' => 200,
]);
}
public function completedAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$bookingId = $request->request->get('bookingId');
$booking = $em->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
$booking->setStatus(Booking::STATUS_COMPLETED);
$em->persist($booking);
$em->flush();
return new JsonResponse([
'success' => true,
'status' => JsonResponse::HTTP_OK,
]);
}
public function isOpenAction(Request $request)
{
$bookingId = $request->request->get('bookingId');
$booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
$booking->isOpen($this->get('security.token_storage')->getToken()->getUser()->getEmail());
$this->getDoctrine()->getManager()->persist($booking);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([
'success' => true,
'status' => 200,
]);
}
/**
* @param Request $request
* @param $bookingKey
*
* @return JsonResponse
*/
public function getJourneyLogsAction(Request $request, $bookingKey)
{
$show_history_log_map = $this->get('doctrine')->getRepository(Settings::class)->findOneBy([
'key' => 'show_history_log_map',
]);
if ($show_history_log_map->getValue() == 0) {
return new JsonResponse(array(
'status' => Response::HTTP_FORBIDDEN,
'message' => 'not enabled',
));
}
try {
/** @var Booking $booking */
$booking = $this->get('doctrine')->getRepository(Booking::class)->findOneBy([
'key' => $bookingKey,
]);
if ($booking && $booking->getId()) {
$logs = $this->get('doctrine')->getRepository(DriverHistoryLocations::class)
->getLocationsById($booking->getId());
if (count($logs) > 0) {
$stepTimeMarker = 120;
$initTime = ($logs[0]['date']);
$markers[] = reset($logs);
foreach ($logs as $log) {
$compareTime = ($log['date']);
$diff = $compareTime->getTimestamp() - $initTime->getTimestamp();
if ($diff > $stepTimeMarker) {
$markers[] = $log;
$initTime = $compareTime;
}
}
$markers[] = end($logs);
$logs = $this->get('jms_serializer')->toArray($logs);
$totals = count($logs);
if ($totals > 23) {
$step = $totals / 23;
$c = 0;
while ($c < $totals) {
if ($logs[ceil($c)]) {
$waypoints[] = $logs[ceil($c)];
}
$c += $step;
}
} else {
$waypoints = $logs;
if (count($waypoints) > 3) {
unset($waypoints[0]);
unset($waypoints[count($waypoints) - 1]);
}
}
$lat = 0.0;
$lng = 0.0;
foreach ($waypoints as $marker) {
if ($marker['lat'] != 0 && $marker['lng'] != 0) {
$lat += $marker['lat'];
$lng += $marker['lng'];
}
}
$centerlat = $lat / count($markers);
$centerlon = $lng / count($markers);
$start = $logs[0];
$end = end($logs);
return new JsonResponse([
'success' => true,
'status' => Response::HTTP_OK,
'journey' => $logs,
'waypoints' => $waypoints,
'markers' => $markers,
'start' => $start,
'end' => $end,
'center' => ['lat' => $centerlat, 'lng' => $centerlon],
'returnBookingId' => $booking->getReturnBooking() ? $booking->getReturnBooking()->getKey() : null,
'urlReturn' => $booking->getReturnBooking() ? $this->generateUrl('admin_bookings_get_journey_logs', ['bookingKey' => $booking->getReturnBooking()->getKey()]) : null,
]);
} elseif (isset($booking) && $booking->getPickUpLat()) {
return new JsonResponse([
'success' => true,
'status' => Response::HTTP_OK,
'start' => ['lat' => $booking->getPickUpLat(), 'lng' => $booking->getPickUpLng()],
'end' => ['lat' => $booking->getDestinationLat(), 'lng' => $booking->getDestinationLng()],
'center' => ['lat' => $booking->getDestinationLat(), 'lng' => $booking->getDestinationLng()],
'returnBookingId' => $booking->getReturnBooking() ? $booking->getReturnBooking()->getId() : null,
]);
}
} else {
return new JsonResponse(array(
'status' => Response::HTTP_BAD_REQUEST,
'message' => 'invalid details',
));
}
} catch (\Exception $e) {
return new JsonResponse(array(
'status' => Response::HTTP_BAD_REQUEST,
'message' => $e->getMessage(),
));
}
}
public function getBookingsStatusAction(Request $request)
{
$bookingIds = $request->request->get('bookingIds');
$queryBuilder = $this->get('doctrine')->getRepository(Booking::class)->createQueryBuilder('b');
$queryBuilder->select('b.id, b.status')
->where("b.id IN(:bookingIds)")
->setParameter('bookingIds', $bookingIds);
$bookingsStatus = $queryBuilder->getQuery()->getArrayResult();
foreach ($bookingsStatus as $key => $bookingStatus) {
$bookingsStatus[$key]['statusName'] = Booking::$statusTypes[$bookingStatus['status']];
}
return new JsonResponse($bookingsStatus);
}
public function getBookingCancelReasonsAction(Request $request)
{
$reasons = $this->get('doctrine')->getRepository(BookingCancelReason::class)->findAll();
$response = [];
/** @var BookingCancelReason $reason */
foreach ($reasons as $reason) {
$response[] = [
'id' => $reason->getId(),
'reason' => $reason->getReason(),
];
}
return new JsonResponse($response);
}
public function removeDriverAction(Request $request)
{
$bookingId = $request->request->get('bookingId');
$booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
$booking->setDriver(null);
$this->getDoctrine()->getManager()->persist($booking);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([
'success' => true,
'status' => 200,
]);
}
public function notifiedDriversAction(Request $request)
{
$bookingId = $request->request->get('asap');
$allDrivers = array();
$bookingRequest = $this->get('doctrine')->getRepository(BookingRequest::class)->findOneBy(array('id' => $bookingId));
if (!empty($bookingRequest)) {
$notifiedDrivers = $bookingRequest->getNotifiedDrivers();
if (!empty($notifiedDrivers)) {
$decodedNotifiedDrivers = json_decode($notifiedDrivers, true);
foreach ($decodedNotifiedDrivers as $driver) {
$driverData = $this->get('doctrine')->getRepository(Driver::class)->findOneBy(array('id' => $driver['driverId']));
$driverCarType = $driverData->getCar()->getType();
$entry = [
'id' => $driverData->getId(),
'name' => $driverData->getUser()->getFirstname() . ' ' . $driverData->getUser()->getLastname(),
'internalName' => $driverData->getInternalName(),
'carType' => $driverCarType->getName(),
];
array_push($allDrivers, $entry);
}
}
}
return new JsonResponse($allDrivers);
}
public function resendDriverNotificationsAction(Request $request)
{
$bookingRequestId = $request->request->get('bookingRequestId');
$bookingRequest = $this->getDoctrine()->getRepository(BookingRequest::class)->findOneBy(['id' => $bookingRequestId]);
if (!empty($bookingRequest)) {
$findDriversService = $this->get('find-matching-jobs.service');
$interval = $bookingRequest->getEstimatedTime();
$intervalComponents = explode(':', $interval);
$minutes = intval($intervalComponents[0]) * 60 + intval($intervalComponents[1]);
$pickUpFullDateTime = $bookingRequest->getPickUpDateTime();
$car_type_id = !empty($bookingRequest->getCarType()) ? $bookingRequest->getCarType()->getId() : null;
$all_drivers = $findDriversService->findDriversForLocations($bookingRequest->getPickUpLat(), $bookingRequest->getPickUpLng(), $minutes, $pickUpFullDateTime, $car_type_id);
if (!empty($all_drivers)) {
$bookingRequest->setNotifiedDrivers(json_encode($all_drivers));
} else {
return new JsonResponse([
'success' => true,
'status' => 200,
'message' => 'Drivers not found for this location.',
]);
}
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([
'success' => true,
'status' => 200,
'message' => 'Driver notifications refreshed.',
]);
}
return new JsonResponse([
'success' => true,
'status' => 200,
'message' => 'Booking request not found.',
]);
}
public function createBookingFromASAPAction(Request $request)
{
$bookingId = $request->request->get('bookingId');
$booking_request = $this->getDoctrine()->getRepository(BookingRequest::class)->findOneBy(['id' => $bookingId]);
if (!empty($booking_request)) {
$paymentMethod = $request->request->get('payment_method', Payment::TYPE_CARD);
if (!in_array($paymentMethod, array_keys(Payment::TYPE))) {
return new JsonResponse([
'status' => 400,
'message' => 'Invalid paymentMethod. The method allowed are: ' . implode(" ", array_keys(Payment::TYPE)),
]);
}
$clientEmail = $booking_request->getClientEmail();
$clientFirstName = $booking_request->getClientFirstName();
$clientLastName = $booking_request->getClientLastName();
$clientPhone = $booking_request->getClientPhone();
$notes = !empty($booking_request->getNotes()) ? $booking_request->getNotes() : '';
$user = null;
$sendEmailCheckBooking = false;
if (!empty($clientEmail)) {
$user = $this->get('doctrine')->getRepository(User::class)->findOneBy([
'email' => $clientEmail,
]);
if ($user) {
if ($user->getAccount()) {
if ($user->getFirstname() != $clientFirstName ||
$user->getLastname() != $clientLastName ||
$user->getPhone() != $clientPhone) {
$notes .= 'Alternative Passenger Travelling: ' . $clientFirstName . ' ' . $clientLastName . '/' . $clientPhone;
$sendEmailCheckBooking = true;
}
} else {
$user = null;
}
} else {
//if not user that is account then will create one
$user = new User();
$user->setUsernameCanonical($clientEmail);
$user->setUsername($clientEmail);
$user->addRole(User::ROLE_CLIENT);
$user->setEnabled(true);
$user->setPassword(substr(md5(microtime()), rand(0, 26), 10));
$user->setFirstname($clientFirstName);
$user->setLastname($clientLastName);
$user->setEmail($clientEmail);
$user->setPhone($clientPhone);
$this->get('doctrine')->getManager()->persist($user);
$account = new Account();
$account->setUser($user);
$account->setPhone($clientPhone);
$account->setEmail($clientEmail);
$account->setName($clientFirstName . ' ' . $clientLastName);
$account->setTitle('Mr');
$this->get('doctrine')->getManager()->persist($account);
$user->setAccount($account);
}
}
$distanceUnit = $booking_request->getDistanceUnit();
$price = $booking_request->getQuotePrice();
$estimateTime = $booking_request->getEstimatedTime();
$pmgValue = $booking_request->getPmg();
$booking = new Booking();
$booking->setPmg($pmgValue);
$booking->setStatus(Booking::STATUS_PENDING);
$booking->setPickUpAddress($booking_request->getPickupAddress());
$booking->setPickUpPostCode($booking_request->getPickUpPostCode());
$booking->setDestinationAddress($booking_request->getDestinationAddress());
$booking->setDestinationPostCode($booking_request->getDestinationPostCode());
$booking->setPickUpDate($booking_request->getPickUpDate());
$booking->setPickUpTime($booking_request->getPickUpTime());
$booking->setCarType($booking_request->getCarType());
$booking->setHandLuggage($booking_request->getHandLuggage());
$booking->setCheckinLuggage($booking_request->getCheckinLuggage());
$booking->setPassengersNumber($booking_request->getPassengersNumber());
$booking->setFlightLandingTime($booking_request->getFlightLandingTime());
$booking->setFlightNumber($booking_request->getFlightNumber());
$booking->setClientFirstName($clientFirstName);
$booking->setClientLastName($clientLastName);
$booking->setClientPhone($clientPhone);
$booking->setClientEmail($clientEmail);
$booking->setClientAlternativePhone($booking_request->getClientAlternativePhone());
$booking->setClientAlternativeEmail($booking_request->getClientAlternativeEmail());
$booking->setNotes($notes);
$booking->setQuotePrice($price);
$booking->setOverridePrice($price);
$booking->setDriverPrice($price - 1);
$booking->setDistanceUnit($distanceUnit);
$booking->setEstimatedTime($estimateTime);
$booking->setPaymentType($paymentMethod);
$booking->setCreateAccount(false);
$booking->setClientUser($user);
$booking->setPickUpLat($booking_request->getPickupLat());
$booking->setPickUpLng($booking_request->getPickupLng());
$booking->setDestinationLat($booking_request->getDestinationLat());
$booking->setDestinationLng($booking_request->getDestinationLng());
$booking->setDriver($booking_request->getDriver());
$booking->setBookingDataSerialized($booking_request->getBookingDataSerialized());
$vias_custom = $booking_request->getVias();
foreach ($vias_custom as $via) {
// Vias might already be BookingViasAddress objects.
if ($via instanceof BookingViasAddress) {
$new_via = $via;
} else {
$new_via = new BookingViasAddress();
$new_via->setAddress($via['address']);
$new_via->setMapAddress($via['value']);
$new_via->setPostCode($via['postcode']);
}
$new_via->setBooking($booking);
$booking->addVias($new_via);
$this->get('doctrine')->getManager()->persist($new_via);
}
$bookingExtras = $booking_request->getExtras();
/** @var BookingBookingExtra $bE */
foreach ($bookingExtras as $bE) {
$bE->setBooking($booking);
}
$booking->setExtras($bookingExtras);
if (!empty($booking_request->getReturnBooking()) and !empty($booking_request->getReturnBooking()->getId())) {
$returnBooking = $this->addReturnBooking($booking, $booking_request, $bookingExtras, $vias_custom);
$this->get('doctrine')->getManager()->persist($returnBooking);
}
$voucherCode = $booking_request->getVoucherCode();
try {
if (!empty($voucherCode)) {
$booking->setVoucherCode($voucherCode);
$this->get('voucher.service')->applyVoucher($booking);
}
} catch (\Exception $e) {
return new JsonResponse([
'status' => 500,
'message' => $e->getMessage(),
]);
}
if (!empty($booking_request)) {
$booking_request->setBookingCreatedKey($booking->getKey());
}
$this->get('doctrine')->getManager()->persist($booking);
$this->get('doctrine')->getManager()->flush();
$this->get('admin.booking')->createObjectSecurity($booking);
// Record booking request history.
$requestService = $this->get('request.service');
$payload = [
'details' => 'Booking created from this booking request',
'method' => 'createBookingFromASAPAction'
];
$action = BookingRequestHistory::SYSTEM_ACTION;
$requestService->addHistory($bookingRequest->getKey(), $action, $payload);
$this->sendEmailNewBooking($sendEmailCheckBooking, $booking);
return new JsonResponse([
'status' => 200,
'message' => "A new booking was created from this booking asap",
'booking' => $this->get('jms_serializer')->toArray($booking),
]);
} else {
return new JsonResponse([
'status' => 400,
'message' => "Could not find any booking asap",
]);
}
}
public function addReturnBooking($booking, $booking_request, $bookingExtras, $vias_custom)
{
$returnPrice = $booking_request->getReturnDriverPrice();
$returnNotes = $booking_request->getReturnBookingNotes();
$pmgValueReturn = $booking_request->getReturnPmg();
$returnBooking = clone $booking;
$booking->setReturnPmg($pmgValueReturn);
$returnBooking->setPmg($pmgValueReturn);
$returnBooking->generateKey();
$returnBooking->setFlightLandingTime($booking_request->getReturnFlightLandingTime());
$returnBooking->setFlightNumber($booking_request->getReturnFlightNumber());
$returnBooking->setPickUpAddress($booking->getDestinationAddress());
$returnBooking->setPickUpMapAddress($booking->getDestinationMapAddress());
$returnBooking->setPickUpPostCode($booking->getDestinationPostCode());
$returnBooking->setPickUpDate($booking_request->getReturnPickUpDate());
$returnBooking->setPickUpTime($booking_request->getReturnPickUpTime());
$returnBooking->setDestinationAddress($booking->getPickUpAddress());
$returnBooking->setDestinationMapAddress($booking->getPickUpMapAddress());
$returnBooking->setDestinationPostCode($booking->getPickUpPostCode());
$returnBooking->setNotes($returnNotes);
$returnBooking->setQuotePrice($returnPrice);
$returnBooking->setOverridePrice($returnPrice);
$returnBooking->setDriverPrice($returnPrice - 1);
/** @var BookingBookingExtra $bE */
foreach ($bookingExtras as $bE) {
$bE->setBooking($returnBooking);
}
$returnBooking->setExtras($bookingExtras);
foreach ($vias_custom as $via) {
// Vias might already be BookingViasAddress objects.
if ($via instanceof BookingViasAddress) {
$new_via = $via;
} else {
$new_via = new BookingViasAddress();
$new_via->setAddress($via['address']);
$new_via->setMapAddress($via['value']);
$new_via->setPostCode($via['postcode']);
}
$new_via->setBooking($returnBooking);
$returnBooking->addVias($new_via);
$this->get('doctrine')->getManager()->persist($new_via);
}
$booking->setReturnFlightLandingTime($booking_request->getReturnFlightLandingTime());
$booking->setReturnFlightNumber($booking_request->getReturnFlightNumber());
$booking->setReturnPickUpDate($booking_request->getReturnPickUpDate());
$booking->setReturnPickUpTime($booking_request->getReturnPickUpTime());
$booking->setReturnBookingNotes($returnNotes);
$booking->setReturnDriverPrice($returnPrice - 1);
$booking->setReturnBooking($returnBooking);
$returnBooking->setParentBooking($booking);
return $returnBooking;
}
public function sendEmailNewBooking($sendEmailCheckBooking, $booking)
{
if ($sendEmailCheckBooking) {
$distance_unit = $this->get('doctrine')->getRepository(Settings::class)->findOneBy([
'key' => 'distance_unit',
]);
$distance_unit = $distance_unit ? $distance_unit->getValue() : 'Miles';
$officeEmail = $this->get('settings_repo')->getOfficeEmail();
$this->get('mandrill.manager')->sendTemplate(
MandrillManager::$TEMPLATE_OPERATOR_BOOKING_CHECK, [],
[
'subject' => 'New Booking has been Created - Manual Check Details',
'from_email' => $officeEmail,
'to' => [
'email' => $officeEmail,
'name' => 'Twelve Transfers',
'type' => 'to',
],
'global_merge_vars' => [
"passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
"passenger_phone" => $booking->getClientPhone(),
"passenger_email" => $booking->getClientEmail(),
"booking_key" => $booking->getKey(),
"booking_creation_date" => $booking->getBookingDate()->format('d/m/Y'),
"booking_creation_time" => $booking->getBookingDate()->format('H:i'),
"booking_origin" => 'API',
"booking_pickup_date" => $booking->getPickUpDate()->format('d/m/Y'),
"booking_pickup_time" => $booking->getPickUpTime(),
"booking_pickup_location" => $booking->getPickUpAddress(),
"booking_dropoff_location" => $booking->getDestinationAddress(),
"booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
return "<li>$address</li>";
}, $booking->getViasAsArray())) . "</ul>",
"booking_passengers" => $booking->getPassengersNumber(),
"booking_luggage" => $booking->getCheckinLuggage(),
"booking_notes" => $booking->getNotes(),
"booking_cost" => $booking->getOverridePrice(),
"currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
"booking_duration" => $booking->getEstimatedTimePrettyFormat(),
"booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
"booking_hand_luggage" => $booking->getHandLuggage(),
"booking_car_type" => $booking->getCarType()->getName(),
"flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
"landing_time" => $booking->getFlightLandingTime(),
"mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
],
'merge_language' => 'mailchimp',
]
);
}
}
public function getBookingsKeysAction(Request $request)
{
$em = $this->get('doctrine')->getManager();
$search = $request->query->get('search');
$bookingKeys = [];
$result = $em->getRepository(Booking::class)->searchByKey($search);
foreach ($result as $booking) {
$client = $booking['clientId']
? [
'id' => $booking['clientId'],
'text' => "{$booking['clientFirstName']} {$booking['clientLastName']} - {$booking['phone']} - {$booking['clientEmail']}",
]
: [];
$driver = $booking['driverId']
? [
'id' => $booking['driverId'],
'text' => "{$booking['driverFirstName']} {$booking['driverLastName']} - {$booking['driverPhone']} - {$booking['driverEmail']}",
]
: [];
$bookingKeys[] = [
'id' => $booking['bookingKey'],
'value' => $booking['bookingKey'],
'client' => $client,
'driver' => $driver,
];
}
return new JsonResponse($bookingKeys);
}
public function adminManualPaymentAction(Request $request)
{
$response = [
'status' => 400,
'message' => 'Something went wrong.',
];
$paymentId = $request->request->get('paymentId');
$paymentCard = $request->request->get('paymentCard');
if (!empty($paymentId) and !empty($paymentId)) {
$payment = $this->getDoctrine()->getRepository(Payment::class)->findOneBy(['id' => $paymentId]);
if (!empty($payment)) {
$typeExplode = explode('_', $paymentCard);
$type = $typeExplode[0];
$card = $typeExplode[1];
$response = $this->get('payment.service')->automaticPaymentForCustomer($payment, $type, $card);
return new JsonResponse($response);
} else {
$response = [
'status' => 400,
'message' => 'Payment not found for this booking.',
];
return new JsonResponse($response);
}
} else {
$response = [
'status' => 400,
'message' => 'Missing parameters.',
];
return new JsonResponse($response);
}
return new JsonResponse($response);
}
public function updateBookingExtraOrderAction(Request $request)
{
try {
$bookingExtraIdsSorted = $request->request->get('bookingExtraIdsSorted');
if(!empty($bookingExtraIdsSorted)) {
$em = $this->get('doctrine')->getManager();
$bookingExtras = $em->getRepository(BookingExtra::class)->findAll();
/** @var BookingExtra $extra */
foreach ($bookingExtras as $extra) {
$extra->setPriority(
intval($bookingExtraIdsSorted[$extra->getId()])
);
$em->persist($extra);
}
$em->flush();
}
return new JsonResponse('ok');
} catch (\Exception $e) {
return new JsonResponse('An error has occured!');
}
}
}