src/AdminBundle/Controller/BookingController.php line 1171

Open in your IDE?
  1. <?php
  2. namespace AdminBundle\Controller;
  3. use AdminBundle\Entity\Account;
  4. use AdminBundle\Entity\Booking;
  5. use AdminBundle\Entity\BookingBookingExtra;
  6. use AdminBundle\Entity\BookingCancelReason;
  7. use AdminBundle\Entity\BookingExtra;
  8. use AdminBundle\Entity\BookingHistory;
  9. use AdminBundle\Entity\BookingRequest;
  10. use AdminBundle\Entity\BookingRequestHistory;
  11. use AdminBundle\Entity\BookingViasAddress;
  12. use AdminBundle\Entity\BroadcastedDriver;
  13. use AdminBundle\Entity\Car;
  14. use AdminBundle\Entity\Driver;
  15. use AdminBundle\Entity\DriverHistory;
  16. use AdminBundle\Entity\DriverHistoryLocations;
  17. use AdminBundle\Entity\Payment;
  18. use AdminBundle\Entity\Settings;
  19. use AdminBundle\Entity\User;
  20. use AdminBundle\Helpers\MandrillManager;
  21. use AdminBundle\WebSockets\NotificationPusher;
  22. use Doctrine\ORM\QueryBuilder;
  23. use Doctrine\ORM\Query\Expr\Join;
  24. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  25. use Symfony\Component\HttpFoundation\JsonResponse;
  26. use Symfony\Component\HttpFoundation\RedirectResponse;
  27. use Symfony\Component\HttpFoundation\Request;
  28. use Symfony\Component\HttpFoundation\Response;
  29. use Symfony\Component\Routing\RouterInterface;
  30. class BookingController extends BaseController
  31. {
  32. private static $mapDashboardStatusRequest = [
  33. 'incoming' => [Booking::STATUS_NEW_BOOKING],
  34. 'pending' => [Booking::STATUS_PENDING],
  35. 'deallocated' => [
  36. Booking::STATUS_DEALLOCATED_ON_DEMAND,
  37. Booking::STATUS_DEALLOCATED_LATE_PICKUP,
  38. Booking::STATUS_DEALLOCATED_NO_LONGER_AVAILABLE,
  39. Booking::STATUS_DEALLOCATED_CAR_BROKE_DOWN,
  40. Booking::STATUS_DEALLOCATED_OFFICE,
  41. ],
  42. 'live' => [
  43. Booking::STATUS_DRIVER_ACCEPT,
  44. Booking::STATUS_ON_THE_WAY,
  45. Booking::STATUS_ARRIVED_AND_WAITING,
  46. Booking::STATUS_PASSENGER_ON_BOARD,
  47. Booking::STATUS_ABOUT_TO_DROP,
  48. ],
  49. 'completed' => [Booking::STATUS_COMPLETED],
  50. 'cancelled' => [
  51. Booking::STATUS_CANCELLED_OTHER_REASON,
  52. Booking::STATUS_CLIENT_CANCELLATION,
  53. Booking::STATUS_CLIENT_NOT_SHOW_UP,
  54. Booking::STATUS_CAR_BROKE_DOWN,
  55. Booking::STATUS_OFFICE_CANCELLATION,
  56. ],
  57. 'pending-cancelled' => [Booking::STATUS_PENDING_CANCELLATION],
  58. ];
  59. /**
  60. * Display the booking request history for this booking.
  61. *
  62. * @param string $key - the Booking key
  63. *
  64. * @return Response
  65. */
  66. public function bookingRequestHistoryAction($key, $return = false) {
  67. $history = $this->get('request.service')->getBookingHistory($key);
  68. return $this->render('@Admin/BookingRequest/history_list.html.twig', [
  69. 'history' => $history,
  70. 'return' => $return
  71. ]);
  72. }
  73. /**
  74. * Display the booking request history.
  75. *
  76. * @param string $key - the Booking key
  77. *
  78. * @return Response
  79. */
  80. public function requestHistoryAction($key) {
  81. $history = $this->get('request.service')->getHistory($key);
  82. return $this->render('@Admin/BookingRequest/history.html.twig', [
  83. 'history' => $history,
  84. 'key' => $key,
  85. 'return' => false
  86. ]);
  87. }
  88. /**
  89. * @param Request $request
  90. * @return JsonResponse
  91. */
  92. public function sendEmailAction(Request $request)
  93. {
  94. $emailNumber = $request->request->get('emailNumber');
  95. $bookingId = $request->request->get('bookingId');
  96. $mandrillManager = $this->get('mandrill.manager');
  97. $distance_unit = $this->get('doctrine')->getRepository(Settings::class)->findOneBy([
  98. 'key' => 'distance_unit',
  99. ]);
  100. $distance_unit = $distance_unit ? $distance_unit->getValue() : 'Miles';
  101. $dateFormat = 'd/m/Y';
  102. $booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
  103. if ($booking->isCancel()) {
  104. return new JsonResponse([
  105. 'success' => false,
  106. 'status' => 400,
  107. 'message' => 'The booking was canceled',
  108. ]);
  109. }
  110. $officeEmail = $this->get('settings_repo')->getOfficeEmail();
  111. switch ($emailNumber) {
  112. case 't1':
  113. $statusEmail = $mandrillManager->sendTemplate(
  114. MandrillManager::$TEMPLATE_NEW_BOOKING_CLIENT, [],
  115. [
  116. 'subject' => 'Twelve Transfers - Journey Confirmation',
  117. 'from_email' => $officeEmail,
  118. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_NEW_BOOKING_CLIENT),
  119. 'global_merge_vars' => [
  120. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  121. "passenger_phone" => $booking->getClientPhone(),
  122. "passenger_email" => $booking->getClientEmail(),
  123. "booking_key" => $booking->getKey(),
  124. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  125. "booking_pickup_time" => $booking->getPickUpTime(),
  126. "booking_pickup_location" => $booking->getPickUpAddress(),
  127. "booking_dropoff_location" => $booking->getDestinationAddress(),
  128. "booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
  129. return "<li>$address</li>";
  130. }, $booking->getViasAsArray())) . "</ul>",
  131. "booking_passengers" => $booking->getPassengersNumber(),
  132. "booking_luggage" => $booking->getCheckinLuggage(),
  133. "booking_notes" => $booking->getNotes(),
  134. "booking_cost" => $booking->getOverridePrice(),
  135. "currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
  136. "booking_duration" => $booking->getEstimatedTimePrettyFormat(),
  137. "booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
  138. "booking_hand_luggage" => $booking->getHandLuggage(),
  139. "booking_car_type" => $booking->getCarType()->getName(),
  140. "premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
  141. "return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
  142. "return_booking" => !empty($booking->getReturnBooking()) ? true : null,
  143. "return_booking_key" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getKey() : null,
  144. "return_booking_pickup_date" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getPickUpDate()->format($dateFormat) : null,
  145. "return_booking_pickup_time" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getPickUpTime() : null,
  146. "return_booking_pickup_location" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getPickUpAddress() : null,
  147. "return_booking_dropoff_location" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getDestinationAddress() : null,
  148. "return_booking_vias_content" => $booking->getReturnBooking() ? "<ul>" . implode("", array_map(function ($address) {
  149. return "<li>$address</li>";
  150. }, $booking->getReturnBooking()->getViasAsArray())) . "</ul>" : null,
  151. "return_booking_notes" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getNotes() : null,
  152. "return_booking_cost" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getOverridePrice() : null,
  153. "return_booking_duration" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getEstimatedTimePrettyFormat() : null,
  154. "return_booking_distance" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getDistanceUnit() . ' ' . $distance_unit : null,
  155. "flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
  156. "landing_time" => $booking->getFlightLandingTime(),
  157. "mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
  158. "return_flight_number" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getFlightNumber() : null,
  159. "return_landing_time" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getFlightLandingTime() : null,
  160. "return_mg_timeframe" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getMeetAndGreetTimePrettyFormat() : null,
  161. "booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
  162. $name = $objective['name'];
  163. //$price = $objective['price'];
  164. return "<li>$name</li>";
  165. }, $booking->getObjectivesAsArray())) . "</ul>",
  166. "return_booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
  167. $name = $objective['name'];
  168. //$price = $objective['price'];
  169. return "<li>$name</li>";
  170. }, $booking->getReturnObjectivesAsArray())) . "</ul>",
  171. ],
  172. 'merge_language' => 'mailchimp',
  173. ]
  174. );
  175. break;
  176. case 't2':
  177. $statusEmail = $mandrillManager->sendTemplate(
  178. MandrillManager::$TEMPLATE_NEW_BOOKING_OFFICE, [],
  179. [
  180. 'subject' => 'New Booking has been Created',
  181. 'from_email' => $officeEmail,
  182. 'to' => [
  183. 'email' => $officeEmail,
  184. 'name' => 'Twelve Transfers',
  185. 'type' => 'to',
  186. ],
  187. 'global_merge_vars' => [
  188. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  189. "passenger_phone" => $booking->getClientPhone(),
  190. "passenger_email" => $booking->getClientEmail(),
  191. "booking_key" => $booking->getKey(),
  192. "booking_creation_date" => $booking->getBookingDate()->format($dateFormat),
  193. "booking_creation_time" => $booking->getBookingDate()->format('H:i'),
  194. "booking_origin" => 'TBD:origin', //todo: update this
  195. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  196. "booking_pickup_time" => $booking->getPickUpTime(),
  197. "booking_pickup_location" => $booking->getPickUpAddress(),
  198. "booking_dropoff_location" => $booking->getDestinationAddress(),
  199. "booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
  200. return "<li>$address</li>";
  201. }, $booking->getViasAsArray())) . "</ul>",
  202. "booking_passengers" => $booking->getPassengersNumber(),
  203. "booking_luggage" => $booking->getCheckinLuggage(),
  204. "booking_notes" => $booking->getNotes(),
  205. "booking_cost" => $booking->getOverridePrice(),
  206. "currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
  207. "booking_duration" => $booking->getEstimatedTimePrettyFormat(),
  208. "booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
  209. "booking_hand_luggage" => $booking->getHandLuggage(),
  210. "booking_car_type" => $booking->getCarType()->getName(),
  211. "flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
  212. "landing_time" => $booking->getFlightLandingTime(),
  213. "mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
  214. "booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
  215. $name = $objective['name'];
  216. //$price = $objective['price'];
  217. return "<li>$name</li>";
  218. }, $booking->getObjectivesAsArray())) . "</ul>",
  219. ],
  220. 'merge_language' => 'mailchimp',
  221. ]
  222. );
  223. break;
  224. case 't3':
  225. $statusEmail = $mandrillManager->sendTemplate(
  226. MandrillManager::$TEMPLATE_BOOKING_COMPLETED, [],
  227. [
  228. 'subject' => 'Twelve Transfers - Booking Completed',
  229. 'from_email' => $officeEmail,
  230. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_BOOKING_COMPLETED),
  231. 'global_merge_vars' => [
  232. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  233. "booking_review_link" => $this->getParameter('assets_base_url') . 'review/' . $booking->getKey(),
  234. ],
  235. 'merge_language' => 'mailchimp',
  236. ]
  237. );
  238. break;
  239. case 't4':
  240. $statusEmail = $mandrillManager->sendTemplate(
  241. MandrillManager::$TEMPLATE_BOOKING_CANCELLED, [],
  242. [
  243. 'subject' => 'Twelve Transfers - Booking Cancelled',
  244. 'from_email' => $officeEmail,
  245. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_BOOKING_CANCELLED),
  246. 'global_merge_vars' => [
  247. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  248. "booking_key" => $booking->getKey(),
  249. "passenger_phone" => $booking->getClientPhone(),
  250. "passenger_email" => $booking->getClientEmail(),
  251. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  252. "booking_pickup_time" => $booking->getPickUpTime(),
  253. "booking_pickup_location" => $booking->getPickUpAddress(),
  254. "booking_dropoff_location" => $booking->getDestinationAddress(),
  255. "booking_cancel_reason" => $booking->getCancelReason(),
  256. "booking_cancel_charge" => $booking->getCancelRefund(),
  257. ],
  258. 'merge_language' => 'mailchimp',
  259. ]
  260. );
  261. break;
  262. case 't5':
  263. /** @var Driver $driver */
  264. $driver = $booking->getDriver();
  265. if (empty($driver)) {
  266. return new JsonResponse([
  267. 'success' => false,
  268. 'status' => 404,
  269. 'message' => 'The booking haven\'t a driver',
  270. ]);
  271. }
  272. /** @var Car $car */
  273. $car = $driver->getCar();
  274. if (empty($car)) {
  275. return new JsonResponse([
  276. 'success' => false,
  277. 'status' => 404,
  278. 'message' => 'The driver haven\'t assigned a car. Check if the driver have a correct setup.',
  279. ]);
  280. }
  281. $statusEmail = $mandrillManager->sendTemplate(
  282. MandrillManager::$TEMPLATE_DRIVER_ALLOCATED, [], [
  283. 'subject' => 'Twelve Transfers - Your Driver\'s Details',
  284. 'from_email' => $officeEmail,
  285. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_DRIVER_ALLOCATED),
  286. 'global_merge_vars' => [
  287. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  288. "booking_key" => $booking->getKey(),
  289. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  290. "booking_pickup_time" => $booking->getPickUpTime(),
  291. "booking_pickup_location" => $booking->getPickUpAddress(),
  292. "premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
  293. "return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
  294. "driver_name" => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
  295. "driver_PCO" => $driver->getPublicCarriageOfficeLicenceNumber(),
  296. "driver_HACK" => $driver->getHackLicenseNumber(),
  297. "driver_SSN" => $driver->getSocialSecurityNumber(),
  298. "driver_phone" => $driver->getPhone(),
  299. "driver_vehicle_name" => $car->getMaker() . ' ' . $car->getModel(),
  300. "driver_vehicle_plate" => $car->getPlateNumber(),
  301. "driver_vehicle_PHV" => $car->getPhvLicenseNumber(),
  302. "driver_vehicle_LIMO" => $car->getLimoLicenseNumber(),
  303. "driver_picture" => $this->getParameter('assets_base_url') . (!empty($driver->getPicture()) ? $driver->getPicturePath() : 'bundles/admin/img/driver/default_driver_image.png'),
  304. "driver_vehicle_color" => $car->getColor(),
  305. ],
  306. 'merge_language' => 'mailchimp',
  307. ]
  308. );
  309. break;
  310. case 't6':
  311. /** @var Driver $driver */
  312. $driver = $booking->getDriver();
  313. if (empty($driver)) {
  314. return new JsonResponse([
  315. 'success' => false,
  316. 'status' => 404,
  317. 'message' => 'The booking haven\'t a driver',
  318. ]);
  319. }
  320. /** @var Car $car */
  321. $car = $driver->getCar();
  322. if (empty($car)) {
  323. return new JsonResponse([
  324. 'success' => false,
  325. 'status' => 404,
  326. 'message' => 'The driver haven\'t assigned a car. Check if the driver have a correct setup.',
  327. ]);
  328. }
  329. $statusEmail = $mandrillManager->sendTemplate(
  330. MandrillManager::$TEMPLATE_DRIVER_REALLOCATED, [], [
  331. 'subject' => 'Twelve Transfers - Your Driver has Changed',
  332. 'from_email' => $officeEmail,
  333. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_DRIVER_REALLOCATED),
  334. 'global_merge_vars' => [
  335. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  336. "booking_key" => $booking->getKey(),
  337. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  338. "booking_pickup_time" => $booking->getPickUpTime(),
  339. "booking_pickup_location" => $booking->getPickUpAddress(),
  340. "premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
  341. "return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
  342. "driver_name" => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
  343. "driver_PCO" => $driver->getPublicCarriageOfficeLicenceNumber(),
  344. "driver_HACK" => $driver->getHackLicenseNumber(),
  345. "driver_SSN" => $driver->getSocialSecurityNumber(),
  346. "driver_phone" => $driver->getPhone(),
  347. "driver_vehicle_name" => $car->getMaker() . ' ' . $car->getModel(),
  348. "driver_vehicle_plate" => $car->getPlateNumber(),
  349. "driver_vehicle_PHV" => $car->getPhvLicenseNumber(),
  350. "driver_vehicle_LIMO" => $car->getLimoLicenseNumber(),
  351. "driver_picture" => $this->getParameter('assets_base_url') . (!empty($driver->getPicture()) ? $driver->getPicturePath() : 'bundles/admin/img/driver/default_driver_image.png'),
  352. "driver_vehicle_color" => $car->getColor(),
  353. ],
  354. 'merge_language' => 'mailchimp',
  355. ]
  356. );
  357. break;
  358. case 't7':
  359. /** @var Driver $driver */
  360. $driver = $booking->getDriver();
  361. if (empty($driver)) {
  362. return new JsonResponse([
  363. 'success' => false,
  364. 'status' => 404,
  365. 'message' => 'The booking haven\'t a driver',
  366. ]);
  367. }
  368. /** @var Car $car */
  369. $car = $driver->getCar();
  370. if (empty($car)) {
  371. return new JsonResponse([
  372. 'success' => false,
  373. 'status' => 404,
  374. 'message' => 'The driver haven\'t assigned a car. Check if the driver have a correct setup.',
  375. ]);
  376. }
  377. $statusEmail = $mandrillManager->sendTemplate(
  378. MandrillManager::$TEMPLATE_DRIVER_ARRIVED, [], [
  379. 'subject' => 'Twelve Transfers - Your Driver has Arrived',
  380. 'from_email' => $officeEmail,
  381. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_DRIVER_ARRIVED),
  382. 'global_merge_vars' => [
  383. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  384. "booking_key" => $booking->getKey(),
  385. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  386. "booking_pickup_time" => $booking->getPickUpTime(),
  387. "booking_pickup_location" => $booking->getPickUpAddress(),
  388. "premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
  389. "return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
  390. "driver_name" => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
  391. "driver_PCO" => $driver->getPublicCarriageOfficeLicenceNumber(),
  392. "driver_HACK" => $driver->getHackLicenseNumber(),
  393. "driver_SSN" => $driver->getSocialSecurityNumber(),
  394. "driver_phone" => $driver->getPhone(),
  395. "driver_vehicle_name" => $car->getMaker() . ' ' . $car->getModel(),
  396. "driver_vehicle_plate" => $car->getPlateNumber(),
  397. "driver_vehicle_PHV" => $car->getPhvLicenseNumber(),
  398. "driver_vehicle_LIMO" => $car->getLimoLicenseNumber(),
  399. "driver_picture" => $this->getParameter('assets_base_url') . (!empty($driver->getPicture()) ? $driver->getPicturePath() : 'bundles/admin/img/driver/default_driver_image.png'),
  400. "driver_vehicle_color" => $car->getColor(),
  401. ],
  402. 'merge_language' => 'mailchimp',
  403. ]
  404. );
  405. break;
  406. case 't7.5':
  407. /** @var Driver $driver */
  408. $driver = $booking->getDriver();
  409. if (empty($driver)) {
  410. return new JsonResponse([
  411. 'success' => false,
  412. 'status' => 404,
  413. 'message' => 'The booking haven\'t a driver',
  414. ]);
  415. }
  416. /** @var Car $car */
  417. $car = $driver->getCar();
  418. if (empty($car)) {
  419. return new JsonResponse([
  420. 'success' => false,
  421. 'status' => 404,
  422. 'message' => 'The driver haven\'t assigned a car. Check if the driver have a correct setup.',
  423. ]);
  424. }
  425. $statusEmail = $mandrillManager->sendTemplate(
  426. MandrillManager::$TEMPLATE_DRIVER_WAITING, [], [
  427. 'subject' => 'Twelve Transfers - Your Driver is Waiting',
  428. 'from_email' => $officeEmail,
  429. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_DRIVER_WAITING),
  430. 'global_merge_vars' => [
  431. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  432. "booking_key" => $booking->getKey(),
  433. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  434. "booking_pickup_time" => $booking->getPickUpTime(),
  435. "booking_pickup_location" => $booking->getPickUpAddress(),
  436. "premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
  437. "return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
  438. "driver_name" => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
  439. "driver_PCO" => $driver->getPublicCarriageOfficeLicenceNumber(),
  440. "driver_HACK" => $driver->getHackLicenseNumber(),
  441. "driver_SSN" => $driver->getSocialSecurityNumber(),
  442. "driver_phone" => $driver->getPhone(),
  443. "driver_vehicle_name" => $car->getMaker() . ' ' . $car->getModel(),
  444. "driver_vehicle_plate" => $car->getPlateNumber(),
  445. "driver_vehicle_PHV" => $car->getPhvLicenseNumber(),
  446. "driver_vehicle_LIMO" => $car->getLimoLicenseNumber(),
  447. "driver_picture" => $this->getParameter('assets_base_url') . (!empty($driver->getPicture()) ? $driver->getPicturePath() : 'bundles/admin/img/driver/default_driver_image.png'),
  448. "driver_vehicle_color" => $booking->getDriver()->getCar()->getColor(),
  449. ],
  450. 'merge_language' => 'mailchimp',
  451. ]
  452. );
  453. break;
  454. case 't8':
  455. $statusEmail = $mandrillManager->sendTemplate(
  456. MandrillManager::$TEMPLATE_PAYMENT_INITIAL, [],
  457. [
  458. 'subject' => 'Twelve Transfers - Payment Link',
  459. 'from_email' => $officeEmail,
  460. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_PAYMENT_INITIAL),
  461. 'global_merge_vars' => [
  462. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  463. "payment_link" => $this->get('payment.helper')->generateUrl($this->get('payment.helper')->generateToken($booking->getPayment(), $booking->getPayment()->getAmountLeft())),
  464. "booking_key" => $booking->getKey(),
  465. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  466. "booking_pickup_time" => $booking->getPickUpTime(),
  467. "booking_pickup_location" => $booking->getPickUpAddress(),
  468. "booking_dropoff_location" => $booking->getDestinationAddress(),
  469. "booking_cost" => $booking->getPayment()->getAmountLeft(),
  470. "currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
  471. ],
  472. 'merge_language' => 'mailchimp',
  473. ]
  474. );
  475. break;
  476. case 't9':
  477. $statusEmail = $mandrillManager->sendTemplate(
  478. MandrillManager::$TEMPLATE_PAYMENT_REMINDER, [],
  479. [
  480. 'subject' => 'Twelve Transfers - Payment Link Reminder',
  481. 'from_email' => $officeEmail,
  482. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_PAYMENT_REMINDER),
  483. 'global_merge_vars' => [
  484. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  485. "payment_link" => $this->get('payment.helper')->generateUrl($this->get('payment.helper')->generateToken($booking->getPayment(), $booking->getPayment()->getAmountLeft())),
  486. "booking_key" => $booking->getKey(),
  487. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  488. "booking_pickup_time" => $booking->getPickUpTime(),
  489. "booking_pickup_location" => $booking->getPickUpAddress(),
  490. "booking_dropoff_location" => $booking->getDestinationAddress(),
  491. "booking_cost" => $booking->getPayment()->getAmountLeft(),
  492. "currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
  493. ],
  494. 'merge_language' => 'mailchimp',
  495. ]
  496. );
  497. break;
  498. case 't10':
  499. $statusEmail = $mandrillManager->sendTemplate(
  500. MandrillManager::$TEMPLATE_PAYMENT_WARNING, [],
  501. [
  502. 'subject' => 'Twelve Transfers - WARNING - Payment Link Reminder',
  503. 'from_email' => $officeEmail,
  504. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_PAYMENT_WARNING),
  505. 'global_merge_vars' => [
  506. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  507. "payment_link" => $this->get('payment.helper')->generateUrl($this->get('payment.helper')->generateToken($booking->getPayment(), $booking->getPayment()->getAmountLeft())),
  508. "booking_key" => $booking->getKey(),
  509. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  510. "booking_pickup_time" => $booking->getPickUpTime(),
  511. "booking_pickup_location" => $booking->getPickUpAddress(),
  512. "booking_dropoff_location" => $booking->getDestinationAddress(),
  513. "booking_cost" => $booking->getPayment()->getAmountLeft(),
  514. "currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
  515. ],
  516. 'merge_language' => 'mailchimp',
  517. ]
  518. );
  519. break;
  520. case 't11':
  521. $statusEmail = $mandrillManager->sendTemplate(
  522. MandrillManager::$TEMPLATE_PENDING_CANCELLED, [],
  523. [
  524. 'subject' => 'Twelve Transfers - WARNING - Pending Cancellation',
  525. 'from_email' => $officeEmail,
  526. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_PENDING_CANCELLED),
  527. 'global_merge_vars' => [
  528. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  529. "booking_key" => $booking->getKey(),
  530. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  531. "booking_pickup_time" => $booking->getPickUpTime(),
  532. "booking_pickup_location" => $booking->getPickUpAddress(),
  533. "booking_dropoff_location" => $booking->getDestinationAddress(),
  534. "booking_cost" => $booking->getPayment()->getAmountLeft(),
  535. "currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
  536. "payment_link" => $this->get('payment.helper')->generateUrl($this->get('payment.helper')->generateToken($booking->getPayment(), $booking->getPayment()->getAmountLeft())),
  537. ],
  538. 'merge_language' => 'mailchimp',
  539. ]
  540. );
  541. break;
  542. case 't12':
  543. $statusEmail = $mandrillManager->sendTemplate(
  544. MandrillManager::$TEMPLATE_BOOKING_UPDATE, [],
  545. [
  546. 'subject' => 'Twelve Transfers - Booking has been Updated',
  547. 'from_email' => $officeEmail,
  548. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_BOOKING_UPDATE),
  549. 'global_merge_vars' => [
  550. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  551. "booking_key" => $booking->getKey(),
  552. "passenger_phone" => $booking->getClientPhone(),
  553. "passenger_email" => $booking->getClientEmail(),
  554. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  555. "booking_pickup_time" => $booking->getPickUpTime(),
  556. "booking_pickup_location" => $booking->getPickUpAddress(),
  557. "booking_dropoff_location" => $booking->getDestinationAddress(),
  558. "booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
  559. return "<li>$address</li>";
  560. }, $booking->getViasAsArray())) . "</ul>",
  561. "booking_passengers" => $booking->getPassengersNumber(),
  562. "booking_luggage" => $booking->getCheckinLuggage(),
  563. "booking_notes" => $booking->getNotes(),
  564. "booking_cost" => $booking->getPayment()->getAmount(),
  565. "premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
  566. "return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
  567. "currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
  568. "booking_duration" => $booking->getEstimatedTimePrettyFormat(),
  569. "booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
  570. "booking_hand_luggage" => $booking->getHandLuggage(),
  571. "booking_car_type" => $booking->getCarType()->getName(),
  572. "flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
  573. "landing_time" => $booking->getFlightLandingTime(),
  574. "mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
  575. "booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
  576. $name = $objective['name'];
  577. //$price = $objective['price'];
  578. return "<li>$name</li>";
  579. }, $booking->getObjectivesAsArray())) . "</ul>",
  580. ],
  581. 'merge_language' => 'mailchimp',
  582. ]
  583. );
  584. break;
  585. case 't13':
  586. $statusEmail = $mandrillManager->sendTemplate(
  587. MandrillManager::$TEMPLATE_BOOKING_RECONFIRM, [],
  588. [
  589. 'subject' => 'Twelve Transfers - IMPORTANT - Please Confirm your Booking',
  590. 'from_email' => $officeEmail,
  591. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_BOOKING_RECONFIRM),
  592. 'global_merge_vars' => [
  593. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  594. "booking_key" => $booking->getKey(),
  595. "passenger_phone" => $booking->getClientPhone(),
  596. "passenger_email" => $booking->getClientEmail(),
  597. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  598. "booking_pickup_time" => $booking->getPickUpTime(),
  599. "booking_pickup_location" => $booking->getPickUpAddress(),
  600. "booking_dropoff_location" => $booking->getDestinationAddress(),
  601. "booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
  602. return "<li>$address</li>";
  603. }, $booking->getViasAsArray())) . "</ul>",
  604. "booking_passengers" => $booking->getPassengersNumber(),
  605. "booking_luggage" => $booking->getCheckinLuggage(),
  606. "booking_notes" => $booking->getNotes(),
  607. "booking_cost" => $booking->getPayment()->getAmount(),
  608. "premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
  609. "return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
  610. "currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
  611. "booking_duration" => $booking->getEstimatedTimePrettyFormat(),
  612. "booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
  613. "booking_hand_luggage" => $booking->getHandLuggage(),
  614. "booking_car_type" => $booking->getCarType()->getName(),
  615. "flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
  616. "landing_time" => $booking->getFlightLandingTime(),
  617. "mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
  618. "booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
  619. $name = $objective['name'];
  620. //$price = $objective['price'];
  621. return "<li>$name</li>";
  622. }, $booking->getObjectivesAsArray())) . "</ul>",
  623. ],
  624. 'merge_language' => 'mailchimp',
  625. ]
  626. );
  627. break;
  628. case 't14':
  629. $statusEmail = $mandrillManager->sendTemplate(
  630. MandrillManager::$TEMPLATE_BOOKING_APPROACHING, [],
  631. [
  632. 'subject' => 'Twelve Transfers - Journey Reminder',
  633. 'from_email' => $officeEmail,
  634. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_BOOKING_APPROACHING),
  635. 'global_merge_vars' => [
  636. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  637. "booking_key" => $booking->getKey(),
  638. "passenger_phone" => $booking->getClientPhone(),
  639. "passenger_email" => $booking->getClientEmail(),
  640. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  641. "booking_pickup_time" => $booking->getPickUpTime(),
  642. "booking_pickup_location" => $booking->getPickUpAddress(),
  643. "booking_dropoff_location" => $booking->getDestinationAddress(),
  644. "booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
  645. return "<li>$address</li>";
  646. }, $booking->getViasAsArray())) . "</ul>",
  647. "booking_passengers" => $booking->getPassengersNumber(),
  648. "booking_luggage" => $booking->getCheckinLuggage(),
  649. "booking_notes" => $booking->getNotes(),
  650. "booking_cost" => $booking->getPayment()->getAmount(),
  651. "premium_mg" => (!empty($booking->getPmg()) and $booking->getPmg() > 0) ? true : false,
  652. "return_premium_mg" => (!empty($booking->getReturnPmg()) and $booking->getReturnPmg() > 0) ? true : false,
  653. "currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
  654. "booking_duration" => $booking->getEstimatedTimePrettyFormat(),
  655. "booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
  656. "booking_hand_luggage" => $booking->getHandLuggage(),
  657. "booking_car_type" => $booking->getCarType()->getName(),
  658. "flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
  659. "landing_time" => $booking->getFlightLandingTime(),
  660. "mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
  661. "booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
  662. $name = $objective['name'];
  663. //$price = $objective['price'];
  664. return "<li>$name</li>";
  665. }, $booking->getObjectivesAsArray())) . "</ul>",
  666. ],
  667. 'merge_language' => 'mailchimp',
  668. ]
  669. );
  670. break;
  671. case 't15':
  672. /** @var Driver $driver */
  673. $driver = $booking->getDriver();
  674. if (empty($driver)) {
  675. return new JsonResponse([
  676. 'success' => false,
  677. 'status' => 404,
  678. 'message' => 'The booking haven\'t a driver',
  679. ]);
  680. }
  681. $statusEmail = $mandrillManager->sendTemplate(
  682. MandrillManager::$TEMPLATE_DRIVER_REGISTERED, [],
  683. [
  684. 'subject' => 'Twelve Transfers - Welcome',
  685. 'from_email' => $officeEmail,
  686. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_PENDING_BOOKING),
  687. 'global_merge_vars' => [
  688. "driver_name" => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
  689. "driver_ID" => $driver->getInternalName(),
  690. "driver_PCO" => $driver->getPublicCarriageOfficeLicenceNumber(),
  691. "driver_HACK" => $driver->getHackLicenseNumber(),
  692. "driver_SSN" => $driver->getSocialSecurityNumber(),
  693. "driver_phone" => $driver->getPhone(),
  694. "driver_email" => $driver->getUser()->getEmail(),
  695. "driver_vehicle_name" => $driver->getCar()->getMaker() . ' ' . $driver->getCar()->getModel(),
  696. "driver_vehicle_plate" => $driver->getCar()->getPlateNumber(),
  697. "driver_vehicle_PHV" => $driver->getCar()->getPhvLicenseNumber(),
  698. "driver_vehicle_LIMO" => $driver->getCar()->getLimoLicenseNumber(),
  699. "driver_vehicle_color" => $driver->getCar()->getColor(),
  700. ],
  701. 'merge_language' => 'mailchimp',
  702. ]
  703. );
  704. break;
  705. case 't16':
  706. $statusEmail = $mandrillManager->sendTemplate(
  707. MandrillManager::$TEMPLATE_PENDING_BOOKING, [],
  708. [
  709. 'subject' => 'Twelve Transfers - Booking Attempt',
  710. 'from_email' => $officeEmail,
  711. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_PENDING_BOOKING),
  712. 'global_merge_vars' => [
  713. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  714. "booking_key" => $booking->getKey(),
  715. "payment_link" => $this->get('payment.helper')->generateUrl($this->get('payment.helper')->generateToken($booking->getPayment(), $booking->getPayment()->getAmountLeft())),
  716. ],
  717. 'merge_language' => 'mailchimp',
  718. ]
  719. );
  720. break;
  721. case 't25':
  722. $statusEmail = $mandrillManager->sendTemplate(
  723. MandrillManager::$TEMPLATE_SHUTTLE_ENQUIRY, [],
  724. [
  725. 'subject' => 'Twelve Transfers - Lower Rates with our Shuttle Option',
  726. 'from_email' => $officeEmail,
  727. 'to' => $mandrillManager->getToListByBooking($booking, MandrillManager::$TEMPLATE_SHUTTLE_ENQUIRY),
  728. 'global_merge_vars' => [
  729. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  730. "passenger_phone" => $booking->getClientPhone(),
  731. "passenger_email" => $booking->getClientEmail(),
  732. "booking_key" => $booking->getKey(),
  733. "booking_pickup_date" => $booking->getPickUpDate()->format($dateFormat),
  734. "booking_pickup_time" => $booking->getPickUpTime(),
  735. "booking_pickup_location" => $booking->getPickUpAddress(),
  736. "booking_dropoff_location" => $booking->getDestinationAddress(),
  737. "booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
  738. return "<li>$address</li>";
  739. }, $booking->getViasAsArray())) . "</ul>",
  740. "booking_passengers" => $booking->getPassengersNumber(),
  741. "booking_luggage" => $booking->getCheckinLuggage(),
  742. "booking_notes" => $booking->getNotes(),
  743. "booking_cost" => $booking->getOverridePrice(),
  744. "currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
  745. "booking_duration" => $booking->getEstimatedTimePrettyFormat(),
  746. "booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
  747. "booking_hand_luggage" => $booking->getHandLuggage(),
  748. "booking_car_type" => $booking->getCarType()->getName(),
  749. "return_booking" => !empty($booking->getReturnBooking()) ? true : null,
  750. "return_booking_key" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getKey() : null,
  751. "return_booking_pickup_date" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getPickUpDate()->format($dateFormat) : null,
  752. "return_booking_pickup_time" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getPickUpTime() : null,
  753. "return_booking_pickup_location" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getPickUpAddress() : null,
  754. "return_booking_dropoff_location" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getDestinationAddress() : null,
  755. "return_booking_vias_content" => $booking->getReturnBooking() ? "<ul>" . implode("", array_map(function ($address) {
  756. return "<li>$address</li>";
  757. }, $booking->getReturnBooking()->getViasAsArray())) . "</ul>" : null,
  758. "return_booking_notes" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getNotes() : null,
  759. "return_booking_cost" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getOverridePrice() : null,
  760. "return_booking_duration" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getEstimatedTimePrettyFormat() : null,
  761. "return_booking_distance" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getDistanceUnit() . ' ' . $distance_unit : null,
  762. "flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
  763. "landing_time" => $booking->getFlightLandingTime(),
  764. "mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
  765. "return_flight_number" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getFlightNumber() : null,
  766. "return_landing_time" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getFlightLandingTime() : null,
  767. "return_mg_timeframe" => $booking->getReturnBooking() ? $booking->getReturnBooking()->getMeetAndGreetTimePrettyFormat() : null,
  768. "booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
  769. $name = $objective['name'];
  770. //$price = $objective['price'];
  771. return "<li>$name</li>";
  772. }, $booking->getObjectivesAsArray())) . "</ul>",
  773. "return_booking_tour_content" => "<ul>" . implode("", array_map(function ($objective) {
  774. $name = $objective['name'];
  775. //$price = $objective['price'];
  776. return "<li>$name</li>";
  777. }, $booking->getReturnObjectivesAsArray())) . "</ul>",
  778. ],
  779. 'merge_language' => 'mailchimp',
  780. ]
  781. );
  782. break;
  783. }
  784. foreach ($statusEmail as $status) {
  785. if ($status['status'] != 'sent') {
  786. return new JsonResponse([
  787. 'success' => false,
  788. 'status' => 500,
  789. 'message' => 'Reject Reason: ' . $status['reject_reason'],
  790. ]);
  791. }
  792. }
  793. return new JsonResponse([
  794. 'success' => true,
  795. 'status' => 200,
  796. 'message' => 'The mail has been sent successfully',
  797. ]);
  798. }
  799. public function bookingTakeoverAction(Request $request, $id) {
  800. $user = false;
  801. if ($token = $this->get('security.token_storage')->getToken()) {
  802. $user = $token->getUser();
  803. }
  804. if ($user) {
  805. $email = $user->getEmail();
  806. $pool = $this->get('sonata.admin.pool');
  807. $admin = $pool->getAdminByAdminCode('admin.booking');
  808. $url = $admin->generateUrl('edit', ['id' => $id]);
  809. $admin->setRequest($request);
  810. $booking = $admin->getObject($id);
  811. $admin->setSubject($booking);
  812. $booking->isOpen($email);
  813. $booking = $admin->update($booking);
  814. } else {
  815. $url = $this->generateUrl('sonata_admin_dashboard');
  816. }
  817. return new RedirectResponse(
  818. $url
  819. );
  820. }
  821. public function getBookingDriversAction($bookingId)
  822. {
  823. $booking = $this->get('doctrine')->getRepository(Booking::class)->find($bookingId);
  824. $drivers = $this->getDoctrine()->getRepository(Driver::class)->createQueryBuilder('d')
  825. ->join('d.car', 'c')
  826. ->join('c.type', 'ct', Join::WITH, 'ct.passengers >= :limit_passangers')
  827. ->where('d.status = :status_active')
  828. ->setParameter('limit_passangers', $booking->getPassengersNumber())
  829. ->setParameter('status_active', Driver::STATUS_ACTIVE)
  830. ->getQuery()->getResult();
  831. $broadcastedDrivers = $this->getDoctrine()->getRepository(BroadcastedDriver::class)->findBy([
  832. 'booking' => $bookingId,
  833. 'status' => BroadcastedDriver::STATUS_APPROVED,
  834. ]);
  835. $response = [
  836. 'manual_dispatch' => [],
  837. 'brodcasted' => [],
  838. ];
  839. $broadcastedDriversIds = [];
  840. /** @var BroadcastedDriver $broadcastedDriver */
  841. foreach ($broadcastedDrivers as $broadcastedDriver) {
  842. $driver = $broadcastedDriver->getDriver();
  843. $car = $driver->getCar();
  844. if ($car->getType()->getPassengers() >= $booking->getPassengersNumber()) {
  845. $broadcastedDriversIds[] = $driver->getId();
  846. $response['brodcasted'][] = [
  847. 'id' => $driver->getId(),
  848. 'name' => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
  849. 'internalName' => $driver->getInternalName(),
  850. ];
  851. }
  852. }
  853. foreach ($drivers as $driver) {
  854. if (!in_array($driver->getId(), $broadcastedDriversIds)) {
  855. $maxNumberOfPassengers = $car = $driver->getCar()->getMaxNumberOfPassengers();
  856. if (isset($maxNumberOfPassengers) && ($maxNumberOfPassengers < $booking->getPassengersNumber())) {
  857. continue;
  858. }
  859. $response['manual_dispatch'][] = [
  860. 'id' => $driver->getId(),
  861. 'name' => $driver->getUser()->getFirstname() . ' ' . $driver->getUser()->getLastname(),
  862. 'internalName' => $driver->getInternalName(),
  863. ];
  864. }
  865. }
  866. return new JsonResponse($response);
  867. }
  868. public function preAssignBookingDriverAction(Request $request)
  869. {
  870. $driverId = $request->request->get('driverId');
  871. $bookingId = $request->request->get('bookingId');
  872. $driver = $this->getDoctrine()->getRepository(Driver::class)->findOneBy(['id' => $driverId]);
  873. $booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
  874. if ($booking->isCancel()) {
  875. return new JsonResponse([
  876. 'success' => true,
  877. 'status' => 400,
  878. 'message' => 'The booking was canceled',
  879. ]);
  880. }
  881. $booking->setNeedSendToDriver(true);
  882. $booking->setDriver($driver);
  883. $this->getDoctrine()->getManager()->persist($booking);
  884. $this->getDoctrine()->getManager()->flush();
  885. return new JsonResponse([
  886. 'success' => true,
  887. 'status' => 200,
  888. 'message' => 'Driver has been successfully pre-assigned',
  889. ]);
  890. }
  891. public function selectBookingDriverAction(Request $request)
  892. {
  893. $driverId = $request->request->get('driverId');
  894. $bookingId = $request->request->get('bookingId');
  895. $em = $this->getDoctrine()->getManager();
  896. $driver = $em->getRepository(Driver::class)->findOneBy(['id' => $driverId]);
  897. $booking = $em->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
  898. if ($booking->isCancel()) {
  899. return new JsonResponse([
  900. 'success' => true,
  901. 'status' => 400,
  902. 'message' => 'The booking was canceled',
  903. ]);
  904. }
  905. $checkDriverShift = $this->get('driver.service')->getDriverShiftStatus($driver,$booking->getPickUpDateTime());
  906. if(!empty($checkDriverShift)) {
  907. $entityManager = $this->getDoctrine()->getManager();
  908. $bookingHistoryDriver = new BookingHistory();
  909. $bookingHistoryDriver->setBooking($booking);
  910. $bookingHistoryDriver->setActionType(BookingHistory::ACTION_DRIVER_SHIFT_TEST);
  911. $bookingHistoryDriver->setUser($driver->getUser());
  912. $bookingHistoryDriver->setPayload($checkDriverShift);
  913. $entityManager->persist($bookingHistoryDriver);
  914. $entityManager->flush();
  915. $blockTimeShiftBookings = $entityManager->getRepository(Settings::class)->findOneBy([
  916. 'key'=>'block_time_shift_bookings',
  917. 'type' => Settings::TYPE_API_DRIVER
  918. ]);
  919. if (!empty($blockTimeShiftBookings) and $blockTimeShiftBookings->getValue() and $checkDriverShift['status'] == JsonResponse::HTTP_FORBIDDEN) {
  920. return new JsonResponse($checkDriverShift);
  921. }
  922. }
  923. $currentDriverUser = $driver->getUser();
  924. $payload = [
  925. 'current_user_id' => $currentDriverUser->getId(),
  926. 'current_user_name' => $currentDriverUser->getFullname(),
  927. 'current_user_email' => $currentDriverUser->getEmail(),
  928. ];
  929. if ($booking->getDriver()) {
  930. $payload['old_user_id'] = $booking->getDriver()->getUser()->getId();
  931. $payload['old_user_name'] = $booking->getDriver()->getUser()->getFullName();
  932. $payload['old_user_email'] = $booking->getDriver()->getUser()->getEmail();
  933. }
  934. $booking->setNeedSendToDriver(false);
  935. $booking->setDriver($driver);
  936. $booking->setStatus(Booking::STATUS_DISPATCHED);
  937. $driverHistory = $this
  938. ->get('driver-history.service')
  939. ->create(
  940. $driver,
  941. $booking->getKey(),
  942. DriverHistory::VALUE_MANUALLY_DISPATCH,
  943. Driver::REPUTATION_POINTS_BOOKING_MANUALLY_DISPATCH,
  944. DriverHistory::TYPE_BOOKING
  945. );
  946. $driver->addReputationPoints(Driver::REPUTATION_POINTS_BOOKING_MANUALLY_DISPATCH);
  947. $em->persist($driverHistory);
  948. $em->persist($driver);
  949. $em->persist($booking);
  950. $em->flush();
  951. $driverUser = $driver->getUser();
  952. return new JsonResponse([
  953. 'success' => true,
  954. 'status' => 200,
  955. 'message' => 'Driver has been successfully selected',
  956. 'driver' => [
  957. 'firstName' => $driverUser->getFirstname(),
  958. 'lastName' => $driverUser->getLastname(),
  959. 'phone' => $driver->getPhone(),
  960. ],
  961. ]);
  962. }
  963. public function preAssignBookingsDriverAction(Request $request)
  964. {
  965. $driverId = $request->request->get('driverId');
  966. $bookingIds = $request->request->get('bookingIds');
  967. $bookingIdsArray = explode(',', $bookingIds);
  968. $driver = $this->getDoctrine()->getRepository(Driver::class)->findOneBy(['id' => $driverId]);
  969. foreach ($bookingIdsArray as $bookingId) {
  970. $booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
  971. if ($booking->isCancel()) {
  972. return new JsonResponse([
  973. 'success' => true,
  974. 'status' => 400,
  975. 'message' => 'The booking was canceled',
  976. ]);
  977. }
  978. $booking->setNeedSendToDriver(true);
  979. $booking->setDriver($driver);
  980. $this->getDoctrine()->getManager()->persist($booking);
  981. }
  982. $this->getDoctrine()->getManager()->flush();
  983. return new JsonResponse([
  984. 'success' => true,
  985. 'status' => 200,
  986. ]);
  987. }
  988. public function selectBookingsDriverAction(Request $request)
  989. {
  990. $driverId = $request->request->get('driverId');
  991. $bookingIds = $request->request->get('bookingIds');
  992. $bookingIdsArray = explode(',', $bookingIds);
  993. $driver = $this->getDoctrine()->getRepository(Driver::class)->findOneBy(['id' => $driverId]);
  994. $currentDriverUser = $driver->getUser();
  995. $payload = [
  996. 'current_user_id' => $currentDriverUser->getId(),
  997. 'current_user_name' => $currentDriverUser->getFullname(),
  998. 'current_user_email' => $currentDriverUser->getEmail(),
  999. ];
  1000. foreach ($bookingIdsArray as $bookingId) {
  1001. $booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
  1002. if (!$booking) {
  1003. return new JsonResponse([
  1004. 'success' => true,
  1005. 'status' => 400,
  1006. 'message' => 'Invalid booking id',
  1007. ]);
  1008. }
  1009. if ($booking->isCancel()) {
  1010. return new JsonResponse([
  1011. 'success' => true,
  1012. 'status' => 400,
  1013. 'message' => 'The booking was canceled',
  1014. ]);
  1015. }
  1016. if ($booking->getDriver()) {
  1017. $payload['old_user_id'] = $booking->getDriver()->getUser()->getId();
  1018. $payload['old_user_name'] = $booking->getDriver()->getUser()->getFullName();
  1019. $payload['old_user_email'] = $booking->getDriver()->getUser()->getEmail();
  1020. }
  1021. $booking->setNeedSendToDriver(false);
  1022. $booking->setDriver($driver);
  1023. $booking->setStatus(Booking::STATUS_DISPATCHED);
  1024. $this->getDoctrine()->getManager()->persist($booking);
  1025. }
  1026. $this->getDoctrine()->getManager()->flush();
  1027. $driverUser = $driver->getUser();
  1028. return new JsonResponse([
  1029. 'success' => true,
  1030. 'status' => 200,
  1031. 'message' => 'Driver has been successfully selected',
  1032. 'driver' => [
  1033. 'firstName' => $driverUser->getFirstname(),
  1034. 'lastName' => $driverUser->getLastname(),
  1035. 'phone' => $driver->getPhone(),
  1036. ],
  1037. ]);
  1038. }
  1039. public function broadcastAction(Request $request)
  1040. {
  1041. $em = $this->getDoctrine()->getManager();
  1042. $bookingId = $request->request->get('bookingId');
  1043. $carTypeIds = $request->request->get('carTypeIds');
  1044. $booking = $em->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
  1045. $driver = $booking->getDriver();
  1046. if ($booking->isExpireBroadcast() || $driver) {
  1047. return new JsonResponse([
  1048. 'success' => false,
  1049. 'status' => JsonResponse::HTTP_BAD_REQUEST,
  1050. ]);
  1051. }
  1052. if ($booking->isCancel()) {
  1053. return new JsonResponse([
  1054. 'success' => true,
  1055. 'status' => JsonResponse::HTTP_BAD_REQUEST,
  1056. 'message' => 'The booking was canceled',
  1057. ]);
  1058. }
  1059. $em->getRepository(BroadcastedDriver::class)->removeBroadcastedDrivers($bookingId);
  1060. $drivers = $em->getRepository(Driver::class)->getDriversByCarTypes($carTypeIds);
  1061. foreach ($drivers as $driver) {
  1062. $broadcast = new BroadcastedDriver();
  1063. $broadcast->setBooking($booking);
  1064. $broadcast->setDriver($driver);
  1065. $user = $driver->getUser();
  1066. if ($user && $user->getApiKey()) {
  1067. $now = new \DateTime();
  1068. $this->get('websocket_notification.service')->send([
  1069. 'apiKey' => $user->getApiKey(),
  1070. 'data' => [
  1071. 'event' => NotificationPusher::SEND_BOOKING_BROADCAST_EVENT,
  1072. 'booking' => $booking->getKey(),
  1073. 'message' => "You have a new broadcast booking request notification for booking #{$booking->getKey()} at {$now->format('Y-m-d H:i')}",
  1074. 'pickup_date_time' => $booking->getPickUpDateTime()->format('Y-m-d H:i:s')
  1075. ],
  1076. ], [
  1077. 'title' => "You have a new broadcast booking request notification for booking #{$booking->getKey()} at {$now->format('Y-m-d H:i')}",
  1078. 'body' => 'Please check details.'
  1079. ]);
  1080. }
  1081. $em->persist($broadcast);
  1082. }
  1083. $expireBroadcastDate = new \DateTime();
  1084. $expireBroadcastDate->modify("+1 hours");
  1085. $booking->setExpireBroadcastDate($expireBroadcastDate);
  1086. $booking->setStatus(Booking::STATUS_BROADCAST);
  1087. $booking->setDriversConfirmedNumber(0);
  1088. $em->persist($booking);
  1089. $em->flush();
  1090. return new JsonResponse([
  1091. 'success' => true,
  1092. 'status' => JsonResponse::HTTP_OK,
  1093. ]);
  1094. }
  1095. public function getDashboardBookingsAction(Request $request)
  1096. {
  1097. $doctrine = $this->get('doctrine');
  1098. $lastUpdate = $request->request->get('lastTime');
  1099. /** @var QueryBuilder $queryBuilderHistory */
  1100. $queryBuilderHistory = $doctrine
  1101. ->getRepository(BookingHistory::class)
  1102. ->createQueryBuilder('h')
  1103. ->select('b.id AS bookingId')
  1104. ->leftJoin(Booking::class, 'b', Join::WITH, 'h.booking=b.id')
  1105. ->groupBy('h.booking')
  1106. ->orderBy('h.date', 'DESC')
  1107. ;
  1108. if ($lastUpdate > 0) {
  1109. $queryBuilderHistory
  1110. ->andWhere('h.date > :fromDate')
  1111. ->setParameter('fromDate', (new \DateTime())->setTimestamp($lastUpdate))
  1112. ;
  1113. }
  1114. $bookingsIds = $queryBuilderHistory
  1115. ->setMaxResults(50)
  1116. ->getQuery()
  1117. ->getArrayResult()
  1118. ;
  1119. $inIds = array_column($bookingsIds, 'bookingId');
  1120. if (empty($inIds)) {
  1121. return new JsonResponse([
  1122. 'results' => [],
  1123. 'lastTime' => $lastUpdate,
  1124. ]);
  1125. }
  1126. $statuses = [];
  1127. foreach ($request->request->get('status', []) as $value) {
  1128. $statuses = array_merge($statuses, self::$mapDashboardStatusRequest[$value]);
  1129. }
  1130. if (empty($statuses)) {
  1131. $statuses[] = '-1';
  1132. }
  1133. /** @var QueryBuilder $queryBuilder */
  1134. $queryBuilder = $doctrine
  1135. ->getRepository(Booking::class)
  1136. ->createQueryBuilder('b')
  1137. ;
  1138. $queryBuilder
  1139. ->where($queryBuilder->expr()->in('b.status', $statuses))
  1140. ->andWhere($queryBuilder->expr()->in('b.id', $inIds))
  1141. ;
  1142. $queryBuilderPickUpAddress = null;
  1143. $queryBuilderDestinationAddress = null;
  1144. $queryBuilderDriver = null;
  1145. $queryBuildersClient = [
  1146. 'first_name' => null,
  1147. 'last_name' => null,
  1148. 'phone' => null,
  1149. 'email' => null,
  1150. ];
  1151. $searchKey = $request->request->get('key');
  1152. if (!empty($searchKey)) {
  1153. $queryBuilderPickUpAddress = clone $queryBuilder;
  1154. $queryBuilderDestinationAddress = clone $queryBuilder;
  1155. $queryBuilderDriver = clone $queryBuilder;
  1156. $queryBuildersClient = [
  1157. 'first_name' => clone $queryBuilder,
  1158. 'last_name' => clone $queryBuilder,
  1159. 'phone' => is_numeric(str_replace('+', '', $searchKey)) ? clone $queryBuilder : null,
  1160. 'email' => clone $queryBuilder,
  1161. ];
  1162. $queryBuilder->andWhere($queryBuilder->expr()->like('b.key', "'$searchKey%'"));
  1163. $queryBuilderPickUpAddress->andWhere($queryBuilderPickUpAddress->expr()->like('b.pickUpAddress', "'%$searchKey%'"));
  1164. $queryBuilderDestinationAddress->andWhere($queryBuilderDestinationAddress->expr()->like('b.destinationAddress', "'%$searchKey%'"));
  1165. $queryBuilderDriver
  1166. ->innerJoin('b.driver', 'd', Join::WITH, 'd.internalName like :search')
  1167. ->setParameter('search', "$searchKey%")
  1168. ;
  1169. $queryBuildersClient['first_name']->andWhere('b.clientFirstName like :search')->setParameter('search', "$searchKey%");
  1170. $queryBuildersClient['last_name']->andWhere('b.clientLastName like :search')->setParameter('search', "$searchKey%");
  1171. if ($queryBuildersClient['phone'] != null) {
  1172. $queryBuildersClient['phone']->andWhere('b.clientPhone like :search')->setParameter('search', "$searchKey%");
  1173. }
  1174. $queryBuildersClient['email']->andWhere('b.clientEmail like :search')->setParameter('search', "$searchKey%");
  1175. }
  1176. // $queryBuilder
  1177. // ->setFirstResult($request->request->get('startWith', 0))
  1178. // ->setMaxResults($request->request->get('limit', 5))
  1179. // ;
  1180. // $ignoreIds = $request->request->get('ignoreIds', []);
  1181. // if (!empty($ignoreIds)) {
  1182. // $queryBuilder->andWhere($queryBuilder->expr()->not($queryBuilder->expr()->in('b.id', $ignoreIds)));
  1183. // }
  1184. /** @var Booking[] $bookings */
  1185. $bookings = $queryBuilder
  1186. ->setMaxResults(50)
  1187. ->getQuery()
  1188. ->getResult()
  1189. ;
  1190. $limit = $request->request->get('limit', 5);
  1191. $ignoreIds = array_map(function (Booking $booking) {
  1192. return $booking->getId();
  1193. }, $bookings);
  1194. if (count($bookings) < $limit && $queryBuilderPickUpAddress != null) {
  1195. $queryBuilderPickUpAddress->setMaxResults($limit);
  1196. if (!empty($ignoreIds)) {
  1197. $queryBuilderPickUpAddress->andWhere($queryBuilderPickUpAddress->expr()->not($queryBuilderPickUpAddress->expr()->in('b.id', $ignoreIds)));
  1198. }
  1199. /** @var Booking $b */
  1200. foreach ($queryBuilderPickUpAddress->getQuery()->getResult() as $b) {
  1201. $ignoreIds[] = $b->getId();
  1202. if (count($bookings) < $limit) {
  1203. $bookings[] = $b;
  1204. } else {
  1205. break;
  1206. }
  1207. }
  1208. }
  1209. if (count($bookings) < $limit && $queryBuilderDestinationAddress != null) {
  1210. $queryBuilderDestinationAddress->setMaxResults($limit);
  1211. if (!empty($ignoreIds)) {
  1212. $queryBuilderDestinationAddress->andWhere($queryBuilderDestinationAddress->expr()->not($queryBuilderDestinationAddress->expr()->in('b.id', $ignoreIds)));
  1213. }
  1214. /** @var Booking $b */
  1215. foreach ($queryBuilderDestinationAddress->getQuery()->getResult() as $b) {
  1216. $ignoreIds[] = $b->getId();
  1217. if (count($bookings) < $limit) {
  1218. $bookings[] = $b;
  1219. } else {
  1220. break;
  1221. }
  1222. }
  1223. }
  1224. if (count($bookings) < $limit && $queryBuilderDriver != null) {
  1225. $queryBuilderDriver->setMaxResults($limit);
  1226. if (!empty($ignoreIds)) {
  1227. $queryBuilderDriver->andWhere($queryBuilderDriver->expr()->not($queryBuilderDriver->expr()->in('b.id', $ignoreIds)));
  1228. }
  1229. /** @var Booking $b */
  1230. foreach ($queryBuilderDriver->getQuery()->getResult() as $b) {
  1231. $ignoreIds[] = $b->getId();
  1232. if (count($bookings) < $limit) {
  1233. $bookings[] = $b;
  1234. } else {
  1235. break;
  1236. }
  1237. }
  1238. }
  1239. if (count($bookings) < $limit) {
  1240. /** @var QueryBuilder $qb */
  1241. foreach ($queryBuildersClient as $key => $qb) {
  1242. if ($qb != null) {
  1243. $qb->setMaxResults($limit);
  1244. if (!empty($ignoreIds)) {
  1245. $qb->andWhere($qb->expr()->not($qb->expr()->in('b.id', $ignoreIds)));
  1246. }
  1247. /** @var Booking $b */
  1248. foreach ($qb->getQuery()->getResult() as $b) {
  1249. $ignoreIds[] = $b->getId();
  1250. if (count($bookings) < $limit) {
  1251. $bookings[] = $b;
  1252. } else {
  1253. break 2;
  1254. }
  1255. }
  1256. }
  1257. }
  1258. }
  1259. $response = [];
  1260. /** @var RouterInterface $router */
  1261. $router = $this->get('router');
  1262. $cachedClassColors = [];
  1263. foreach (self::$mapDashboardStatusRequest as $key => $statuses) {
  1264. foreach ($statuses as $status) {
  1265. $cachedClassColors[$status] = $key;
  1266. }
  1267. }
  1268. $defaultCarType = Car::$carCtlfTypes[Car::CAR_TYPE_SALOON];
  1269. /** @var Booking $booking */
  1270. foreach ($bookings as $booking) {
  1271. /** @var \DateTime $lastBookingHistoryDate */
  1272. $lastBookingHistoryDate = $booking
  1273. ->getBookingHistory()
  1274. ->last()
  1275. ->getDate()
  1276. ;
  1277. $lastBookingHistoryTimestamp = $lastBookingHistoryDate->getTimestamp();
  1278. $response[] = [
  1279. 'id' => $booking->getId(),
  1280. 'key' => $booking->getKey(),
  1281. 'url' => $router->generate('admin_admin_booking_edit', ['id' => $booking->getId()]),
  1282. 'status' => Booking::$statusTypes[$booking->getStatus()],
  1283. 'classColor' => array_key_exists($booking->getStatus(), $cachedClassColors)
  1284. ? $cachedClassColors[$booking->getStatus()]
  1285. : '',
  1286. 'pickUpAddress' => $booking->getPickUpAddress(),
  1287. 'dropOfAddress' => $booking->getDestinationAddress(),
  1288. 'pickUpTime' => "{$booking->getPickUpDate()->format('F d')} {$booking->getPickUpTime()}",
  1289. 'price' => $booking->getOverridePrice(),
  1290. 'carType' => empty($booking->getCarType())
  1291. ? $defaultCarType
  1292. : $booking->getCarType()->getShortName(),
  1293. 'updateTime' => $lastBookingHistoryDate->format('H:i:s'),
  1294. 'updateDateTime' => $lastBookingHistoryTimestamp,
  1295. ];
  1296. $lastUpdate = $lastUpdate < $lastBookingHistoryTimestamp
  1297. ? $lastBookingHistoryTimestamp
  1298. : $lastUpdate
  1299. ;
  1300. }
  1301. usort($response, function ($a, $b) {
  1302. return $a['updateDateTime'] - $b['updateDateTime'];
  1303. });
  1304. return new JsonResponse([
  1305. 'results' => $lastUpdate == 1 ? array_reverse($response) : $response,
  1306. 'lastTime' => $lastUpdate,
  1307. 'dt' => (new \DateTime())
  1308. ->setTimestamp($lastUpdate)
  1309. ->format('d-m-Y H:i:s'),
  1310. ]);
  1311. }
  1312. public function updateDashboardBookingsAction(Request $request)
  1313. {
  1314. $ids = $request->request->get('ids');
  1315. if (!empty($ids)) {
  1316. /** @var QueryBuilder $queryBuilder */
  1317. $queryBuilder = $this->get('doctrine')->getRepository(Booking::class)->createQueryBuilder('b');
  1318. $queryBuilder->where($queryBuilder->expr()->in('b.id', $ids));
  1319. $bookings = $queryBuilder->getQuery()->getResult();
  1320. $response = [];
  1321. /** @var Booking $booking */
  1322. foreach ($bookings as $booking) {
  1323. $response[] = [
  1324. 'id' => $booking->getId(),
  1325. 'key' => $booking->getKey(),
  1326. 'url' => $this->get('router')->generate('admin_admin_booking_edit', ['id' => $booking->getId()]),
  1327. 'status' => Booking::$statusTypes[$booking->getStatus()],
  1328. 'classColor' => key(array_filter(self::$mapDashboardStatusRequest, function ($v, $k) use ($booking) {
  1329. return in_array($booking->getStatus(), $v);
  1330. }, ARRAY_FILTER_USE_BOTH)),
  1331. 'pickUpAddress' => $booking->getPickUpAddress(),
  1332. 'dropOfAddress' => $booking->getDestinationAddress(),
  1333. 'pickUpTime' => $booking->getPickUpDate()->format('F d') . ' ' . $booking->getPickUpTime(),
  1334. 'price' => $booking->getOverridePrice(),
  1335. 'carType' => empty($booking->getCarType()) ? Car::$carCtlfTypes[Car::CAR_TYPE_SALOON] : $booking->getCarType()->getName(),
  1336. 'updateTime' => count($booking->getBookingHistory()) ? $booking->getBookingHistory()->last()->getDate()->format('H:i:s') : $booking->getBookingDate()->format('H:i:s'),
  1337. 'updateDateTime' => count($booking->getBookingHistory()) ? $booking->getBookingHistory()->last()->getDate()->getTimestamp() : $booking->getBookingDate()->getTimestamp(),
  1338. ];
  1339. }
  1340. usort($response, function ($a, $b) {
  1341. return $a['updateDateTime'] - $b['updateDateTime'];
  1342. });
  1343. // $response = array_reverse($response);
  1344. $hash = md5(serialize($response) . $_SERVER['REMOTE_ADDR']);
  1345. if (isset($_SESSION['hash_list'])) {
  1346. if ($_SESSION['hash_list'] == $hash) {
  1347. $response = [];
  1348. }
  1349. }
  1350. $_SESSION['hash_list'] = $hash;
  1351. return new JsonResponse($response);
  1352. }
  1353. return new JsonResponse([]);
  1354. }
  1355. public function officeCancellationAction(Request $request)
  1356. {
  1357. $bookingId = $request->request->get('bookingId');
  1358. $cancelReason = $request->request->get('cancelReason');
  1359. $cancelRefund = $request->request->get('cancelRefund');
  1360. $booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
  1361. $booking->setStatus(Booking::STATUS_OFFICE_CANCELLATION);
  1362. $booking->setCancelReason($cancelReason);
  1363. $cancelPercent = 0;
  1364. if ($cancelRefund) {
  1365. //$cancelPercent = $cancelRefund/100;
  1366. $cancelPercent = $cancelRefund; // to be checked as the value inserted is in percent
  1367. }
  1368. $booking->setCancelRefund($cancelPercent);
  1369. $this->getDoctrine()->getManager()->persist($booking);
  1370. $this->getDoctrine()->getManager()->flush();
  1371. return new JsonResponse([
  1372. 'success' => true,
  1373. 'status' => 200,
  1374. ]);
  1375. }
  1376. public function deleteAction(Request $request)
  1377. {
  1378. $bookingId = $request->request->get('bookingId');
  1379. $booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
  1380. $booking->setStatus(Booking::STATUS_DELETED);
  1381. $this->getDoctrine()->getManager()->persist($booking);
  1382. $this->getDoctrine()->getManager()->flush();
  1383. return new JsonResponse([
  1384. 'success' => true,
  1385. 'status' => 200,
  1386. ]);
  1387. }
  1388. public function deleteASAPAction(Request $request)
  1389. {
  1390. $bookingId = $request->request->get('bookingId');
  1391. $booking_request = $this->getDoctrine()->getRepository(BookingRequest::class)->findOneBy(['id' => $bookingId]);
  1392. $booking_extras = $this->getDoctrine()->getRepository(BookingBookingExtra::class)->findOneBy(['bookingRequest' => $bookingId]);
  1393. $this->getDoctrine()->getManager()->remove($booking_request);
  1394. $this->getDoctrine()->getManager()->flush();
  1395. return new JsonResponse([
  1396. 'success' => true,
  1397. 'status' => 200,
  1398. ]);
  1399. }
  1400. public function completedAction(Request $request)
  1401. {
  1402. $em = $this->getDoctrine()->getManager();
  1403. $bookingId = $request->request->get('bookingId');
  1404. $booking = $em->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
  1405. $booking->setStatus(Booking::STATUS_COMPLETED);
  1406. $em->persist($booking);
  1407. $em->flush();
  1408. return new JsonResponse([
  1409. 'success' => true,
  1410. 'status' => JsonResponse::HTTP_OK,
  1411. ]);
  1412. }
  1413. public function isOpenAction(Request $request)
  1414. {
  1415. $bookingId = $request->request->get('bookingId');
  1416. $booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
  1417. $booking->isOpen($this->get('security.token_storage')->getToken()->getUser()->getEmail());
  1418. $this->getDoctrine()->getManager()->persist($booking);
  1419. $this->getDoctrine()->getManager()->flush();
  1420. return new JsonResponse([
  1421. 'success' => true,
  1422. 'status' => 200,
  1423. ]);
  1424. }
  1425. /**
  1426. * @param Request $request
  1427. * @param $bookingKey
  1428. *
  1429. * @return JsonResponse
  1430. */
  1431. public function getJourneyLogsAction(Request $request, $bookingKey)
  1432. {
  1433. $show_history_log_map = $this->get('doctrine')->getRepository(Settings::class)->findOneBy([
  1434. 'key' => 'show_history_log_map',
  1435. ]);
  1436. if ($show_history_log_map->getValue() == 0) {
  1437. return new JsonResponse(array(
  1438. 'status' => Response::HTTP_FORBIDDEN,
  1439. 'message' => 'not enabled',
  1440. ));
  1441. }
  1442. try {
  1443. /** @var Booking $booking */
  1444. $booking = $this->get('doctrine')->getRepository(Booking::class)->findOneBy([
  1445. 'key' => $bookingKey,
  1446. ]);
  1447. if ($booking && $booking->getId()) {
  1448. $logs = $this->get('doctrine')->getRepository(DriverHistoryLocations::class)
  1449. ->getLocationsById($booking->getId());
  1450. if (count($logs) > 0) {
  1451. $stepTimeMarker = 120;
  1452. $initTime = ($logs[0]['date']);
  1453. $markers[] = reset($logs);
  1454. foreach ($logs as $log) {
  1455. $compareTime = ($log['date']);
  1456. $diff = $compareTime->getTimestamp() - $initTime->getTimestamp();
  1457. if ($diff > $stepTimeMarker) {
  1458. $markers[] = $log;
  1459. $initTime = $compareTime;
  1460. }
  1461. }
  1462. $markers[] = end($logs);
  1463. $logs = $this->get('jms_serializer')->toArray($logs);
  1464. $totals = count($logs);
  1465. if ($totals > 23) {
  1466. $step = $totals / 23;
  1467. $c = 0;
  1468. while ($c < $totals) {
  1469. if ($logs[ceil($c)]) {
  1470. $waypoints[] = $logs[ceil($c)];
  1471. }
  1472. $c += $step;
  1473. }
  1474. } else {
  1475. $waypoints = $logs;
  1476. if (count($waypoints) > 3) {
  1477. unset($waypoints[0]);
  1478. unset($waypoints[count($waypoints) - 1]);
  1479. }
  1480. }
  1481. $lat = 0.0;
  1482. $lng = 0.0;
  1483. foreach ($waypoints as $marker) {
  1484. if ($marker['lat'] != 0 && $marker['lng'] != 0) {
  1485. $lat += $marker['lat'];
  1486. $lng += $marker['lng'];
  1487. }
  1488. }
  1489. $centerlat = $lat / count($markers);
  1490. $centerlon = $lng / count($markers);
  1491. $start = $logs[0];
  1492. $end = end($logs);
  1493. return new JsonResponse([
  1494. 'success' => true,
  1495. 'status' => Response::HTTP_OK,
  1496. 'journey' => $logs,
  1497. 'waypoints' => $waypoints,
  1498. 'markers' => $markers,
  1499. 'start' => $start,
  1500. 'end' => $end,
  1501. 'center' => ['lat' => $centerlat, 'lng' => $centerlon],
  1502. 'returnBookingId' => $booking->getReturnBooking() ? $booking->getReturnBooking()->getKey() : null,
  1503. 'urlReturn' => $booking->getReturnBooking() ? $this->generateUrl('admin_bookings_get_journey_logs', ['bookingKey' => $booking->getReturnBooking()->getKey()]) : null,
  1504. ]);
  1505. } elseif (isset($booking) && $booking->getPickUpLat()) {
  1506. return new JsonResponse([
  1507. 'success' => true,
  1508. 'status' => Response::HTTP_OK,
  1509. 'start' => ['lat' => $booking->getPickUpLat(), 'lng' => $booking->getPickUpLng()],
  1510. 'end' => ['lat' => $booking->getDestinationLat(), 'lng' => $booking->getDestinationLng()],
  1511. 'center' => ['lat' => $booking->getDestinationLat(), 'lng' => $booking->getDestinationLng()],
  1512. 'returnBookingId' => $booking->getReturnBooking() ? $booking->getReturnBooking()->getId() : null,
  1513. ]);
  1514. }
  1515. } else {
  1516. return new JsonResponse(array(
  1517. 'status' => Response::HTTP_BAD_REQUEST,
  1518. 'message' => 'invalid details',
  1519. ));
  1520. }
  1521. } catch (\Exception $e) {
  1522. return new JsonResponse(array(
  1523. 'status' => Response::HTTP_BAD_REQUEST,
  1524. 'message' => $e->getMessage(),
  1525. ));
  1526. }
  1527. }
  1528. public function getBookingsStatusAction(Request $request)
  1529. {
  1530. $bookingIds = $request->request->get('bookingIds');
  1531. $queryBuilder = $this->get('doctrine')->getRepository(Booking::class)->createQueryBuilder('b');
  1532. $queryBuilder->select('b.id, b.status')
  1533. ->where("b.id IN(:bookingIds)")
  1534. ->setParameter('bookingIds', $bookingIds);
  1535. $bookingsStatus = $queryBuilder->getQuery()->getArrayResult();
  1536. foreach ($bookingsStatus as $key => $bookingStatus) {
  1537. $bookingsStatus[$key]['statusName'] = Booking::$statusTypes[$bookingStatus['status']];
  1538. }
  1539. return new JsonResponse($bookingsStatus);
  1540. }
  1541. public function getBookingCancelReasonsAction(Request $request)
  1542. {
  1543. $reasons = $this->get('doctrine')->getRepository(BookingCancelReason::class)->findAll();
  1544. $response = [];
  1545. /** @var BookingCancelReason $reason */
  1546. foreach ($reasons as $reason) {
  1547. $response[] = [
  1548. 'id' => $reason->getId(),
  1549. 'reason' => $reason->getReason(),
  1550. ];
  1551. }
  1552. return new JsonResponse($response);
  1553. }
  1554. public function removeDriverAction(Request $request)
  1555. {
  1556. $bookingId = $request->request->get('bookingId');
  1557. $booking = $this->getDoctrine()->getRepository(Booking::class)->findOneBy(['id' => $bookingId]);
  1558. $booking->setDriver(null);
  1559. $this->getDoctrine()->getManager()->persist($booking);
  1560. $this->getDoctrine()->getManager()->flush();
  1561. return new JsonResponse([
  1562. 'success' => true,
  1563. 'status' => 200,
  1564. ]);
  1565. }
  1566. public function notifiedDriversAction(Request $request)
  1567. {
  1568. $bookingId = $request->request->get('asap');
  1569. $allDrivers = array();
  1570. $bookingRequest = $this->get('doctrine')->getRepository(BookingRequest::class)->findOneBy(array('id' => $bookingId));
  1571. if (!empty($bookingRequest)) {
  1572. $notifiedDrivers = $bookingRequest->getNotifiedDrivers();
  1573. if (!empty($notifiedDrivers)) {
  1574. $decodedNotifiedDrivers = json_decode($notifiedDrivers, true);
  1575. foreach ($decodedNotifiedDrivers as $driver) {
  1576. $driverData = $this->get('doctrine')->getRepository(Driver::class)->findOneBy(array('id' => $driver['driverId']));
  1577. $driverCarType = $driverData->getCar()->getType();
  1578. $entry = [
  1579. 'id' => $driverData->getId(),
  1580. 'name' => $driverData->getUser()->getFirstname() . ' ' . $driverData->getUser()->getLastname(),
  1581. 'internalName' => $driverData->getInternalName(),
  1582. 'carType' => $driverCarType->getName(),
  1583. ];
  1584. array_push($allDrivers, $entry);
  1585. }
  1586. }
  1587. }
  1588. return new JsonResponse($allDrivers);
  1589. }
  1590. public function resendDriverNotificationsAction(Request $request)
  1591. {
  1592. $bookingRequestId = $request->request->get('bookingRequestId');
  1593. $bookingRequest = $this->getDoctrine()->getRepository(BookingRequest::class)->findOneBy(['id' => $bookingRequestId]);
  1594. if (!empty($bookingRequest)) {
  1595. $findDriversService = $this->get('find-matching-jobs.service');
  1596. $interval = $bookingRequest->getEstimatedTime();
  1597. $intervalComponents = explode(':', $interval);
  1598. $minutes = intval($intervalComponents[0]) * 60 + intval($intervalComponents[1]);
  1599. $pickUpFullDateTime = $bookingRequest->getPickUpDateTime();
  1600. $car_type_id = !empty($bookingRequest->getCarType()) ? $bookingRequest->getCarType()->getId() : null;
  1601. $all_drivers = $findDriversService->findDriversForLocations($bookingRequest->getPickUpLat(), $bookingRequest->getPickUpLng(), $minutes, $pickUpFullDateTime, $car_type_id);
  1602. if (!empty($all_drivers)) {
  1603. $bookingRequest->setNotifiedDrivers(json_encode($all_drivers));
  1604. } else {
  1605. return new JsonResponse([
  1606. 'success' => true,
  1607. 'status' => 200,
  1608. 'message' => 'Drivers not found for this location.',
  1609. ]);
  1610. }
  1611. $this->getDoctrine()->getManager()->flush();
  1612. return new JsonResponse([
  1613. 'success' => true,
  1614. 'status' => 200,
  1615. 'message' => 'Driver notifications refreshed.',
  1616. ]);
  1617. }
  1618. return new JsonResponse([
  1619. 'success' => true,
  1620. 'status' => 200,
  1621. 'message' => 'Booking request not found.',
  1622. ]);
  1623. }
  1624. public function createBookingFromASAPAction(Request $request)
  1625. {
  1626. $bookingId = $request->request->get('bookingId');
  1627. $booking_request = $this->getDoctrine()->getRepository(BookingRequest::class)->findOneBy(['id' => $bookingId]);
  1628. if (!empty($booking_request)) {
  1629. $paymentMethod = $request->request->get('payment_method', Payment::TYPE_CARD);
  1630. if (!in_array($paymentMethod, array_keys(Payment::TYPE))) {
  1631. return new JsonResponse([
  1632. 'status' => 400,
  1633. 'message' => 'Invalid paymentMethod. The method allowed are: ' . implode(" ", array_keys(Payment::TYPE)),
  1634. ]);
  1635. }
  1636. $clientEmail = $booking_request->getClientEmail();
  1637. $clientFirstName = $booking_request->getClientFirstName();
  1638. $clientLastName = $booking_request->getClientLastName();
  1639. $clientPhone = $booking_request->getClientPhone();
  1640. $notes = !empty($booking_request->getNotes()) ? $booking_request->getNotes() : '';
  1641. $user = null;
  1642. $sendEmailCheckBooking = false;
  1643. if (!empty($clientEmail)) {
  1644. $user = $this->get('doctrine')->getRepository(User::class)->findOneBy([
  1645. 'email' => $clientEmail,
  1646. ]);
  1647. if ($user) {
  1648. if ($user->getAccount()) {
  1649. if ($user->getFirstname() != $clientFirstName ||
  1650. $user->getLastname() != $clientLastName ||
  1651. $user->getPhone() != $clientPhone) {
  1652. $notes .= 'Alternative Passenger Travelling: ' . $clientFirstName . ' ' . $clientLastName . '/' . $clientPhone;
  1653. $sendEmailCheckBooking = true;
  1654. }
  1655. } else {
  1656. $user = null;
  1657. }
  1658. } else {
  1659. //if not user that is account then will create one
  1660. $user = new User();
  1661. $user->setUsernameCanonical($clientEmail);
  1662. $user->setUsername($clientEmail);
  1663. $user->addRole(User::ROLE_CLIENT);
  1664. $user->setEnabled(true);
  1665. $user->setPassword(substr(md5(microtime()), rand(0, 26), 10));
  1666. $user->setFirstname($clientFirstName);
  1667. $user->setLastname($clientLastName);
  1668. $user->setEmail($clientEmail);
  1669. $user->setPhone($clientPhone);
  1670. $this->get('doctrine')->getManager()->persist($user);
  1671. $account = new Account();
  1672. $account->setUser($user);
  1673. $account->setPhone($clientPhone);
  1674. $account->setEmail($clientEmail);
  1675. $account->setName($clientFirstName . ' ' . $clientLastName);
  1676. $account->setTitle('Mr');
  1677. $this->get('doctrine')->getManager()->persist($account);
  1678. $user->setAccount($account);
  1679. }
  1680. }
  1681. $distanceUnit = $booking_request->getDistanceUnit();
  1682. $price = $booking_request->getQuotePrice();
  1683. $estimateTime = $booking_request->getEstimatedTime();
  1684. $pmgValue = $booking_request->getPmg();
  1685. $booking = new Booking();
  1686. $booking->setPmg($pmgValue);
  1687. $booking->setStatus(Booking::STATUS_PENDING);
  1688. $booking->setPickUpAddress($booking_request->getPickupAddress());
  1689. $booking->setPickUpPostCode($booking_request->getPickUpPostCode());
  1690. $booking->setDestinationAddress($booking_request->getDestinationAddress());
  1691. $booking->setDestinationPostCode($booking_request->getDestinationPostCode());
  1692. $booking->setPickUpDate($booking_request->getPickUpDate());
  1693. $booking->setPickUpTime($booking_request->getPickUpTime());
  1694. $booking->setCarType($booking_request->getCarType());
  1695. $booking->setHandLuggage($booking_request->getHandLuggage());
  1696. $booking->setCheckinLuggage($booking_request->getCheckinLuggage());
  1697. $booking->setPassengersNumber($booking_request->getPassengersNumber());
  1698. $booking->setFlightLandingTime($booking_request->getFlightLandingTime());
  1699. $booking->setFlightNumber($booking_request->getFlightNumber());
  1700. $booking->setClientFirstName($clientFirstName);
  1701. $booking->setClientLastName($clientLastName);
  1702. $booking->setClientPhone($clientPhone);
  1703. $booking->setClientEmail($clientEmail);
  1704. $booking->setClientAlternativePhone($booking_request->getClientAlternativePhone());
  1705. $booking->setClientAlternativeEmail($booking_request->getClientAlternativeEmail());
  1706. $booking->setNotes($notes);
  1707. $booking->setQuotePrice($price);
  1708. $booking->setOverridePrice($price);
  1709. $booking->setDriverPrice($price - 1);
  1710. $booking->setDistanceUnit($distanceUnit);
  1711. $booking->setEstimatedTime($estimateTime);
  1712. $booking->setPaymentType($paymentMethod);
  1713. $booking->setCreateAccount(false);
  1714. $booking->setClientUser($user);
  1715. $booking->setPickUpLat($booking_request->getPickupLat());
  1716. $booking->setPickUpLng($booking_request->getPickupLng());
  1717. $booking->setDestinationLat($booking_request->getDestinationLat());
  1718. $booking->setDestinationLng($booking_request->getDestinationLng());
  1719. $booking->setDriver($booking_request->getDriver());
  1720. $booking->setBookingDataSerialized($booking_request->getBookingDataSerialized());
  1721. $vias_custom = $booking_request->getVias();
  1722. foreach ($vias_custom as $via) {
  1723. // Vias might already be BookingViasAddress objects.
  1724. if ($via instanceof BookingViasAddress) {
  1725. $new_via = $via;
  1726. } else {
  1727. $new_via = new BookingViasAddress();
  1728. $new_via->setAddress($via['address']);
  1729. $new_via->setMapAddress($via['value']);
  1730. $new_via->setPostCode($via['postcode']);
  1731. }
  1732. $new_via->setBooking($booking);
  1733. $booking->addVias($new_via);
  1734. $this->get('doctrine')->getManager()->persist($new_via);
  1735. }
  1736. $bookingExtras = $booking_request->getExtras();
  1737. /** @var BookingBookingExtra $bE */
  1738. foreach ($bookingExtras as $bE) {
  1739. $bE->setBooking($booking);
  1740. }
  1741. $booking->setExtras($bookingExtras);
  1742. if (!empty($booking_request->getReturnBooking()) and !empty($booking_request->getReturnBooking()->getId())) {
  1743. $returnBooking = $this->addReturnBooking($booking, $booking_request, $bookingExtras, $vias_custom);
  1744. $this->get('doctrine')->getManager()->persist($returnBooking);
  1745. }
  1746. $voucherCode = $booking_request->getVoucherCode();
  1747. try {
  1748. if (!empty($voucherCode)) {
  1749. $booking->setVoucherCode($voucherCode);
  1750. $this->get('voucher.service')->applyVoucher($booking);
  1751. }
  1752. } catch (\Exception $e) {
  1753. return new JsonResponse([
  1754. 'status' => 500,
  1755. 'message' => $e->getMessage(),
  1756. ]);
  1757. }
  1758. if (!empty($booking_request)) {
  1759. $booking_request->setBookingCreatedKey($booking->getKey());
  1760. }
  1761. $this->get('doctrine')->getManager()->persist($booking);
  1762. $this->get('doctrine')->getManager()->flush();
  1763. $this->get('admin.booking')->createObjectSecurity($booking);
  1764. // Record booking request history.
  1765. $requestService = $this->get('request.service');
  1766. $payload = [
  1767. 'details' => 'Booking created from this booking request',
  1768. 'method' => 'createBookingFromASAPAction'
  1769. ];
  1770. $action = BookingRequestHistory::SYSTEM_ACTION;
  1771. $requestService->addHistory($bookingRequest->getKey(), $action, $payload);
  1772. $this->sendEmailNewBooking($sendEmailCheckBooking, $booking);
  1773. return new JsonResponse([
  1774. 'status' => 200,
  1775. 'message' => "A new booking was created from this booking asap",
  1776. 'booking' => $this->get('jms_serializer')->toArray($booking),
  1777. ]);
  1778. } else {
  1779. return new JsonResponse([
  1780. 'status' => 400,
  1781. 'message' => "Could not find any booking asap",
  1782. ]);
  1783. }
  1784. }
  1785. public function addReturnBooking($booking, $booking_request, $bookingExtras, $vias_custom)
  1786. {
  1787. $returnPrice = $booking_request->getReturnDriverPrice();
  1788. $returnNotes = $booking_request->getReturnBookingNotes();
  1789. $pmgValueReturn = $booking_request->getReturnPmg();
  1790. $returnBooking = clone $booking;
  1791. $booking->setReturnPmg($pmgValueReturn);
  1792. $returnBooking->setPmg($pmgValueReturn);
  1793. $returnBooking->generateKey();
  1794. $returnBooking->setFlightLandingTime($booking_request->getReturnFlightLandingTime());
  1795. $returnBooking->setFlightNumber($booking_request->getReturnFlightNumber());
  1796. $returnBooking->setPickUpAddress($booking->getDestinationAddress());
  1797. $returnBooking->setPickUpMapAddress($booking->getDestinationMapAddress());
  1798. $returnBooking->setPickUpPostCode($booking->getDestinationPostCode());
  1799. $returnBooking->setPickUpDate($booking_request->getReturnPickUpDate());
  1800. $returnBooking->setPickUpTime($booking_request->getReturnPickUpTime());
  1801. $returnBooking->setDestinationAddress($booking->getPickUpAddress());
  1802. $returnBooking->setDestinationMapAddress($booking->getPickUpMapAddress());
  1803. $returnBooking->setDestinationPostCode($booking->getPickUpPostCode());
  1804. $returnBooking->setNotes($returnNotes);
  1805. $returnBooking->setQuotePrice($returnPrice);
  1806. $returnBooking->setOverridePrice($returnPrice);
  1807. $returnBooking->setDriverPrice($returnPrice - 1);
  1808. /** @var BookingBookingExtra $bE */
  1809. foreach ($bookingExtras as $bE) {
  1810. $bE->setBooking($returnBooking);
  1811. }
  1812. $returnBooking->setExtras($bookingExtras);
  1813. foreach ($vias_custom as $via) {
  1814. // Vias might already be BookingViasAddress objects.
  1815. if ($via instanceof BookingViasAddress) {
  1816. $new_via = $via;
  1817. } else {
  1818. $new_via = new BookingViasAddress();
  1819. $new_via->setAddress($via['address']);
  1820. $new_via->setMapAddress($via['value']);
  1821. $new_via->setPostCode($via['postcode']);
  1822. }
  1823. $new_via->setBooking($returnBooking);
  1824. $returnBooking->addVias($new_via);
  1825. $this->get('doctrine')->getManager()->persist($new_via);
  1826. }
  1827. $booking->setReturnFlightLandingTime($booking_request->getReturnFlightLandingTime());
  1828. $booking->setReturnFlightNumber($booking_request->getReturnFlightNumber());
  1829. $booking->setReturnPickUpDate($booking_request->getReturnPickUpDate());
  1830. $booking->setReturnPickUpTime($booking_request->getReturnPickUpTime());
  1831. $booking->setReturnBookingNotes($returnNotes);
  1832. $booking->setReturnDriverPrice($returnPrice - 1);
  1833. $booking->setReturnBooking($returnBooking);
  1834. $returnBooking->setParentBooking($booking);
  1835. return $returnBooking;
  1836. }
  1837. public function sendEmailNewBooking($sendEmailCheckBooking, $booking)
  1838. {
  1839. if ($sendEmailCheckBooking) {
  1840. $distance_unit = $this->get('doctrine')->getRepository(Settings::class)->findOneBy([
  1841. 'key' => 'distance_unit',
  1842. ]);
  1843. $distance_unit = $distance_unit ? $distance_unit->getValue() : 'Miles';
  1844. $officeEmail = $this->get('settings_repo')->getOfficeEmail();
  1845. $this->get('mandrill.manager')->sendTemplate(
  1846. MandrillManager::$TEMPLATE_OPERATOR_BOOKING_CHECK, [],
  1847. [
  1848. 'subject' => 'New Booking has been Created - Manual Check Details',
  1849. 'from_email' => $officeEmail,
  1850. 'to' => [
  1851. 'email' => $officeEmail,
  1852. 'name' => 'Twelve Transfers',
  1853. 'type' => 'to',
  1854. ],
  1855. 'global_merge_vars' => [
  1856. "passenger_name" => $booking->getClientFirstName() . ' ' . $booking->getClientLastName(),
  1857. "passenger_phone" => $booking->getClientPhone(),
  1858. "passenger_email" => $booking->getClientEmail(),
  1859. "booking_key" => $booking->getKey(),
  1860. "booking_creation_date" => $booking->getBookingDate()->format('d/m/Y'),
  1861. "booking_creation_time" => $booking->getBookingDate()->format('H:i'),
  1862. "booking_origin" => 'API',
  1863. "booking_pickup_date" => $booking->getPickUpDate()->format('d/m/Y'),
  1864. "booking_pickup_time" => $booking->getPickUpTime(),
  1865. "booking_pickup_location" => $booking->getPickUpAddress(),
  1866. "booking_dropoff_location" => $booking->getDestinationAddress(),
  1867. "booking_vias_content" => "<ul>" . implode("", array_map(function ($address) {
  1868. return "<li>$address</li>";
  1869. }, $booking->getViasAsArray())) . "</ul>",
  1870. "booking_passengers" => $booking->getPassengersNumber(),
  1871. "booking_luggage" => $booking->getCheckinLuggage(),
  1872. "booking_notes" => $booking->getNotes(),
  1873. "booking_cost" => $booking->getOverridePrice(),
  1874. "currency_symbol" => $this->get('currency.service')->getSystemCurrency(),
  1875. "booking_duration" => $booking->getEstimatedTimePrettyFormat(),
  1876. "booking_distance" => $booking->getDistanceUnit() . ' ' . $distance_unit,
  1877. "booking_hand_luggage" => $booking->getHandLuggage(),
  1878. "booking_car_type" => $booking->getCarType()->getName(),
  1879. "flight_number" => !empty($booking->getFlightNumber()) ? $booking->getFlightNumber() : null,
  1880. "landing_time" => $booking->getFlightLandingTime(),
  1881. "mg_timeframe" => $booking->getMeetAndGreetTimePrettyFormat(),
  1882. ],
  1883. 'merge_language' => 'mailchimp',
  1884. ]
  1885. );
  1886. }
  1887. }
  1888. public function getBookingsKeysAction(Request $request)
  1889. {
  1890. $em = $this->get('doctrine')->getManager();
  1891. $search = $request->query->get('search');
  1892. $bookingKeys = [];
  1893. $result = $em->getRepository(Booking::class)->searchByKey($search);
  1894. foreach ($result as $booking) {
  1895. $client = $booking['clientId']
  1896. ? [
  1897. 'id' => $booking['clientId'],
  1898. 'text' => "{$booking['clientFirstName']} {$booking['clientLastName']} - {$booking['phone']} - {$booking['clientEmail']}",
  1899. ]
  1900. : [];
  1901. $driver = $booking['driverId']
  1902. ? [
  1903. 'id' => $booking['driverId'],
  1904. 'text' => "{$booking['driverFirstName']} {$booking['driverLastName']} - {$booking['driverPhone']} - {$booking['driverEmail']}",
  1905. ]
  1906. : [];
  1907. $bookingKeys[] = [
  1908. 'id' => $booking['bookingKey'],
  1909. 'value' => $booking['bookingKey'],
  1910. 'client' => $client,
  1911. 'driver' => $driver,
  1912. ];
  1913. }
  1914. return new JsonResponse($bookingKeys);
  1915. }
  1916. public function adminManualPaymentAction(Request $request)
  1917. {
  1918. $response = [
  1919. 'status' => 400,
  1920. 'message' => 'Something went wrong.',
  1921. ];
  1922. $paymentId = $request->request->get('paymentId');
  1923. $paymentCard = $request->request->get('paymentCard');
  1924. if (!empty($paymentId) and !empty($paymentId)) {
  1925. $payment = $this->getDoctrine()->getRepository(Payment::class)->findOneBy(['id' => $paymentId]);
  1926. if (!empty($payment)) {
  1927. $typeExplode = explode('_', $paymentCard);
  1928. $type = $typeExplode[0];
  1929. $card = $typeExplode[1];
  1930. $response = $this->get('payment.service')->automaticPaymentForCustomer($payment, $type, $card);
  1931. return new JsonResponse($response);
  1932. } else {
  1933. $response = [
  1934. 'status' => 400,
  1935. 'message' => 'Payment not found for this booking.',
  1936. ];
  1937. return new JsonResponse($response);
  1938. }
  1939. } else {
  1940. $response = [
  1941. 'status' => 400,
  1942. 'message' => 'Missing parameters.',
  1943. ];
  1944. return new JsonResponse($response);
  1945. }
  1946. return new JsonResponse($response);
  1947. }
  1948. public function updateBookingExtraOrderAction(Request $request)
  1949. {
  1950. try {
  1951. $bookingExtraIdsSorted = $request->request->get('bookingExtraIdsSorted');
  1952. if(!empty($bookingExtraIdsSorted)) {
  1953. $em = $this->get('doctrine')->getManager();
  1954. $bookingExtras = $em->getRepository(BookingExtra::class)->findAll();
  1955. /** @var BookingExtra $extra */
  1956. foreach ($bookingExtras as $extra) {
  1957. $extra->setPriority(
  1958. intval($bookingExtraIdsSorted[$extra->getId()])
  1959. );
  1960. $em->persist($extra);
  1961. }
  1962. $em->flush();
  1963. }
  1964. return new JsonResponse('ok');
  1965. } catch (\Exception $e) {
  1966. return new JsonResponse('An error has occured!');
  1967. }
  1968. }
  1969. }