src/Controller/CheckoutController.php line 251

Open in your IDE?
  1. <?php
  2. /**
  3.  * Pimcore
  4.  *
  5.  * This source file is available under two different licenses:
  6.  * - GNU General Public License version 3 (GPLv3)
  7.  * - Pimcore Enterprise License (PEL)
  8.  * Full copyright and license information is available in
  9.  * LICENSE.md which is distributed with this source code.
  10.  *
  11.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  12.  *  @license    http://www.pimcore.org/license     GPLv3 and PEL
  13.  */
  14. namespace App\Controller;
  15. use App\Form\DeliveryAddressFormType;
  16. use App\Form\JoinFormType;
  17. use App\Form\PasswordFormType;
  18. use App\Model\SecretsManager;
  19. use App\Model\Product\AbstractProduct;
  20. use App\Services\PermissionService;
  21. use App\Services\TrycareService;
  22. use App\Stripe\UserHandler;
  23. use App\Website\Navigation\BreadcrumbHelperService;
  24. use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
  25. use Pimcore\Controller\FrontendController;
  26. use Pimcore\Model\DataObject;
  27. use Pimcore\Model\DataObject\OnlineShopOrder;
  28. use Pimcore\Model\Redirect;
  29. use Pimcore\Bundle\EcommerceFrameworkBundle\Model\AbstractOrder;
  30. use Symfony\Component\Form\FormError;
  31. use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
  32. use Symfony\Component\HttpFoundation\RedirectResponse;
  33. use Symfony\Component\HttpFoundation\Request;
  34. use Symfony\Component\HttpFoundation\Response;
  35. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  36. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  37. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  38. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  39. use Symfony\Component\Intl\Countries;
  40. use Symfony\Component\Routing\Annotation\Route;
  41. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  42. class CheckoutController extends FrontendController
  43. {
  44.     const SUB_LICENSE_ID 2454;
  45.     const TRYCARE_CART_NAME 'trycare';
  46.     const PLAN_OPTIONS = ['annual''monthly'];
  47.     const PLAN_TYPES = ['starter''premium'];
  48.     private $stripeSK;
  49.     public function __construct()
  50.     {
  51.         $secretsManager = new SecretsManager();
  52.         $this->stripeSK $secretsManager->getSecret('stripe-private-key');
  53.     }
  54.     /**
  55.      * @Route("/checkout-address", name="shop-checkout-address")
  56.      *
  57.      * @param Factory $factory
  58.      * @param Request $request
  59.      * @param BreadcrumbHelperService $breadcrumbHelperService
  60.      * @param Factory $ecommerceFactory
  61.      *
  62.      * @return Response|RedirectResponse
  63.      */
  64.     public function checkoutAddressAction(Factory $factoryRequest $requestBreadcrumbHelperService $breadcrumbHelperServiceFactory $ecommerceFactory)
  65.     {
  66.         $cartManager $factory->getCartManager();
  67.         $cart $cartManager->getOrCreateCartByName('cart');
  68.         $checkoutManager $factory->getCheckoutManager($cart);
  69.         $deliveryAddress $checkoutManager->getCheckoutStep('deliveryaddress');
  70.         $deliveryAddressDataArray $this->fillDeliveryAddressFromCustomer($deliveryAddress->getData());
  71.         $form $this->createForm(DeliveryAddressFormType::class, $deliveryAddressDataArray, []);
  72.         $form->handleRequest($request);
  73.         $breadcrumbHelperService->enrichCheckoutPage();
  74.         if ($request->getMethod() == Request::METHOD_POST) {
  75.             $address = new \stdClass();
  76.             $formData $form->getData();
  77.             foreach ($formData as $key => $value) {
  78.                 $address->{$key} = $value;
  79.             }
  80.             // save address if we have no errors
  81.             if (count($form->getErrors()) === 0) {
  82.                 // commit step
  83.                 $checkoutManager->commitStep($deliveryAddress$address);
  84.                 //TODO remove this - only needed, because one step only is not supported by the framework right now
  85.                 $confirm $checkoutManager->getCheckoutStep('confirm');
  86.                 $checkoutManager->commitStep($confirmtrue);
  87.                 return $this->redirectToRoute('shop-checkout-payment');
  88.             }
  89.         }
  90.         $trackingManager $ecommerceFactory->getTrackingManager();
  91.         $trackingManager->trackCheckoutStep($deliveryAddress$cart1);
  92.         return $this->render('checkout/checkout_address.html.twig', [
  93.             'cart' => $cart,
  94.             'form' => $form->createView(),
  95.         ]);
  96.     }
  97.     /**
  98.      * @param $deliveryAddress
  99.      *
  100.      * @return array|null
  101.      */
  102.     protected function fillDeliveryAddressFromCustomer($deliveryAddress)
  103.     {
  104.         $user $this->getUser();
  105.         $deliveryAddress = (array) $deliveryAddress;
  106.         if ($user) {
  107.             if ($deliveryAddress === null) {
  108.                 $deliveryAddress = [];
  109.             }
  110.             $params = ['email''firstname''lastname''street''zip''city''countryCode'];
  111.             foreach ($params as $param) {
  112.                 if (empty($deliveryAddress[$param])) {
  113.                     $deliveryAddress[$param] = $user->{'get' ucfirst($param)}();
  114.                 }
  115.             }
  116.         }
  117.         return $deliveryAddress;
  118.     }
  119.     /**
  120.      * @Route("/sign-up", name="sign-up")
  121.      *
  122.      * @param Factory $factory
  123.      * @param Request $request
  124.      * @param BreadcrumbHelperService $breadcrumbHelperService
  125.      * @param Factory $ecommerceFactory
  126.      *
  127.      * @return Response|RedirectResponse
  128.      */
  129.     public function SignUpAction(Factory $factoryRequest $request)
  130.     {
  131.         $queryPlan 'monthly';
  132.         $id $request->query->get('id');
  133.         $errors = [];
  134.         $licence DataObject\License::getById($id);
  135.         if (!$licence) {
  136.             $errors[] = "Invalid licence type";
  137.         } elseif (!$this->checkStripeProductHasUsers($licence->getStripeId())) {
  138.             $errors[] = "Something went wrong, please contact our support.";
  139.         }
  140.         $form $this->createForm(JoinFormType::class);
  141.         $form->handleRequest($request);
  142.         if ($form->isSubmitted() && $form->isValid() && $licence && $this->checkStripeProductHasUsers($licence->getStripeId())) {
  143.             $formData $form->getData();
  144.             if (!$formData['termsAndPrivacy']) {
  145.                 $errors[] = 'Sorry, an error occured. Go back to memberships page and try again.';
  146.             } else {
  147.                 $entries = new DataObject\Customer\Listing();
  148.                 $entries->setCondition("email LIKE ?", ["%" $formData['email'] . "%"]);
  149.                 $entries->load();
  150.                 if (!empty($entries->load())) {
  151.                     $errors[] = 'Invalid email.';
  152.                 } else {
  153.                     $environment Factory::getInstance()->getEnvironment();
  154.                     $environment->setCurrentCheckoutTenant('licence');
  155.                     $environment->save();
  156.                     $cartManager $factory->getCartManager();
  157.                     $cart $cartManager->getOrCreateCartByName('licence');
  158.                     $cart->clear();
  159.                     $checkoutManager $factory->getCheckoutManager($cart);
  160.                     $mainInfo $checkoutManager->getCheckoutStep('collectInfo');
  161.                     $cart->addItem($licence1);
  162.                     $cart->save();
  163.                     $userData = new \stdClass();
  164.                     foreach ($formData as $key => $value) {
  165.                         $userData->{$key} = $value;
  166.                     }
  167.                     $userData->{'plan'} = $queryPlan;
  168.                     // commit step
  169.                     $checkoutManager->commitStep($mainInfo$userData);
  170.                     //TODO remove this - only needed, because one step only is not supported by the framework right now
  171.                     $confirm $checkoutManager->getCheckoutStep('confirm');
  172.                     $checkoutManager->commitStep($confirmtrue);
  173.                     return $this->redirectToRoute('stripe-subscription-payment');
  174.                 }
  175.             }
  176.         }
  177.         if ($form->isSubmitted() && !$form->isValid()) {
  178.             foreach ($form->getErrors(true) as $error) {
  179.                 $errors[] = $error->getMessage();
  180.             }
  181.         }
  182.         $name $licence $licence->getName() : '';
  183.         return $this->render('checkout/sign-up.html.twig', [
  184.             'form' => $form->createView(),
  185.             'errors' => $errors,
  186.             'plan' => $queryPlan,
  187.             'name' => $name
  188.         ]);
  189.     }
  190.     /**
  191.      * THis function checks if users are defined in the metadata field
  192.      */
  193.     public function checkStripeProductHasUsers($productId)
  194.     {
  195.         \Stripe\Stripe::setApiKey($this->stripeSK);
  196.         $product \Stripe\Product::retrieve($productId);
  197.         return is_numeric($product->metadata->users);
  198.     }
  199.     /**
  200.      * @Route("/join-us", name="join-us")
  201.      *
  202.      * @param Factory $factory
  203.      * @param Request $request
  204.      * @param BreadcrumbHelperService $breadcrumbHelperService
  205.      * @param Factory $ecommerceFactory
  206.      *
  207.      * @return Response|RedirectResponse
  208.      */
  209.     public function JoinAction(Factory $factoryRequest $requestBreadcrumbHelperService $breadcrumbHelperServiceFactory $ecommerceFactory)
  210.     {
  211.         $cartManager $factory->getCartManager();
  212.         $cart $cartManager->getOrCreateCartByName('cart');
  213.         $checkoutManager $factory->getCheckoutManager($cart);
  214.         $mainInfo $checkoutManager->getCheckoutStep('collectInfo');
  215.         /*  $mainInfoArray = $this->fillDeliveryAddressFromCustomer($deliveryAddress->getData()); */
  216.         $form $this->createForm(JoinFormType::class);
  217.         $form->handleRequest($request);
  218.         $breadcrumbHelperService->enrichCheckoutPage();
  219.         if ($request->getMethod() == Request::METHOD_POST) {
  220.             $userData = new \stdClass();
  221.             $formData $form->getData();
  222.             $subLicensesQty $formData['sublicenses'];
  223.             $entries = new DataObject\Customer\Listing();
  224.             $entries->setCondition("email LIKE ?", ["%" $formData['email'] . "%"]);
  225.             $entries->load();
  226.             if (!empty($entries->load())) {
  227.                 $form->addError(new FormError('Invalid Email.'));
  228.             }
  229.             if (!is_null($subLicensesQty) && $subLicensesQty !== 0) {
  230.                 $subLicense AbstractProduct::getById(self::SUB_LICENSE_ID);
  231.                 $cartManager->removeFromCart(self::SUB_LICENSE_ID$cart->getId());
  232.                 $cart->addItem($subLicense$subLicensesQty);
  233.                 $cart->save();
  234.             }
  235.             foreach ($formData as $key => $value) {
  236.                 $userData->{$key} = $value;
  237.             }
  238.             // save address if we have no errors
  239.             if (count($form->getErrors()) === 0) {
  240.                 // commit step
  241.                 $response $checkoutManager->commitStep($mainInfo$userData);
  242.                 //TODO remove this - only needed, because one step only is not supported by the framework right now
  243.                 $confirm $checkoutManager->getCheckoutStep('confirm');
  244.                 $checkoutManager->commitStep($confirmtrue);
  245.                 /*  return $this->redirectToRoute('shop-checkout-start-payment'); */
  246.                 return $this->redirectToRoute('stripe-checkout-payment');
  247.                 /* return $this->redirectToRoute('shop-checkout-payment'); */
  248.             }
  249.         }
  250.         // $cart = $this->addMainLicenseToCart($cart);
  251.         /* $trackingManager = $ecommerceFactory->getTrackingManager();
  252.         $trackingManager->trackCheckoutStep($deliveryAddress, $cart, 1); */
  253.         $errors = [];
  254.         foreach ($form->getErrors() as $error) {
  255.             $errors[] = $error->getMessage();
  256.         }
  257.         return $this->render('checkout/join.html.twig', [
  258.             'cart' => $cart,
  259.             'form' => $form->createView(),
  260.             'errors' => $errors
  261.         ]);
  262.     }
  263.     /**
  264.      * @Route("/rejoin", name="rejoin")
  265.      *
  266.      * @param Factory $factory
  267.      * @param Request $request
  268.      * @param BreadcrumbHelperService $breadcrumbHelperService
  269.      * @param Factory $ecommerceFactory
  270.      *
  271.      * @return Response|RedirectResponse
  272.      */
  273.     public function rejoinAction(Factory $factoryRequest $requestUserHandler $userHandler)
  274.     {
  275.         $planId $request->query->get('id');
  276.         $loggedUser $this->getUser();
  277.         if (!$loggedUser) {
  278.             return $this->redirect('/account/login?referer=' urlencode('/rejoin?id=' $planId));
  279.         }
  280.         if ($loggedUser->getTypeOfUser() != 'superuser') {
  281.             return $this->redirect('/');
  282.         }
  283.         $mainSubscriptionStatus $loggedUser->getSubscription()->getStatus();
  284.         if ($mainSubscriptionStatus === 'active') {
  285.             return $this->redirect('/');
  286.         }
  287.         $queryPlan 'monthly';
  288.         $errors = [];
  289.         $licence DataObject\License::getById($planId);
  290.         if (!$licence) {
  291.             $errors[] = "Invalid licence type";
  292.         } elseif (!$this->checkStripeProductHasUsers($licence->getStripeId())) {
  293.             $errors[] = "Something went wrong, please contact our support.";
  294.         }
  295.         $licenceMaxSubusers $userHandler->getAdditionalUsersFromLicence($licence->getStripeId());
  296.         $superUserIncludedSubs count($loggedUser->getIncludedSubscriptions());
  297.         if ($superUserIncludedSubs $licenceMaxSubusers) {
  298.             $errors[] = 'This plan does not support the number of additional users you currently have. Please choose Another plan or contact support.';
  299.         }
  300.         $name $licence $licence->getName() : 'Custom Plan';
  301.         if ($request->isMethod('get') || !empty($errors)) {
  302.             return $this->render('checkout/rejoin.html.twig', [
  303.                 'errors' => $errors,
  304.                 'plan' => $queryPlan,
  305.                 'name' => $name,
  306.                 'id' => $planId
  307.             ]);
  308.         }
  309.         $userSubscription $loggedUser->getSubscription();
  310.         $isFreeTrial $userSubscription->getIsFreeTrial();
  311.         //check if stripe sub is expired, if yes redirect to customer portal, otherwise create a new stripe sub
  312.         if (!$isFreeTrial && $userHandler->hasExpiredStripeSubscription($userSubscription)) {
  313.             return $this->redirect('/create-customer-portal-session');
  314.         }
  315.         $cartManager $factory->getCartManager();
  316.         $cart $cartManager->getOrCreateCartByName('licence');
  317.         $cart->clear();
  318.         $checkoutManager $factory->getCheckoutManager($cart);
  319.         $mainInfo $checkoutManager->getCheckoutStep('collectInfo');
  320.         $mainLicence $isFreeTrial $licence $userHandler->getOrCreateLicenceFromStripeProduct($userSubscription->getStripeProductId());
  321.         $cart->addItem($mainLicence1);
  322.         $cart->save();
  323.         $userData = new \stdClass();
  324.         $userData->{'reactivation'} = $loggedUser->getStripeCustomerId();
  325.         $userData->{'superuserId'} = $loggedUser->getId();
  326.         $userData->{'email'} = $loggedUser->getEmail();
  327.         $userData->{'plan'} = $queryPlan;
  328.         $userData->{'stripeProductId'} = $mainLicence->getStripeId();
  329.         $userData->{'stripeId'} = $userSubscription->getStripeId();
  330.         // commit step
  331.         $checkoutManager->commitStep($mainInfo$userData);
  332.         //TODO remove this - only needed, because one step only is not supported by the framework right now
  333.         $confirm $checkoutManager->getCheckoutStep('confirm');
  334.         $checkoutManager->commitStep($confirmtrue);
  335.         return $this->redirectToRoute('stripe-subscription-payment');
  336.     }
  337.     /**
  338.      * @Route("/additional-users/reactivation", name="subuser-reactivation")
  339.      *
  340.      * @param Factory $factory
  341.      * @param Request $request
  342.      * @param BreadcrumbHelperService $breadcrumbHelperService
  343.      * @param Factory $ecommerceFactory
  344.      *
  345.      * @return Response|RedirectResponse
  346.      */
  347.     public function subuserReactivationAction(Request $requestUserHandler $userHandler)
  348.     {
  349.         //authorization checks
  350.         $loggedUser $this->getUser();
  351.         if (!$loggedUser) {
  352.             throw new UnauthorizedHttpException('Not authorized.');
  353.         }
  354.         if (!$loggedUser || $loggedUser->getTypeOfUser() != 'superuser') {
  355.             return $this->redirect('/');
  356.         }
  357.         $mainSubscription $loggedUser->getSubscription();
  358.         if ($mainSubscription->getStatus() != 'active') {
  359.             return $this->redirect('/');
  360.         }
  361.         //check if it has expired or canceled pimcore subscriptions
  362.         $expiredOrCancelledExtraSub array_filter($loggedUser->getExtraSubscriptions(), function ($sub) {
  363.             return $sub->getStatus() != 'active';
  364.         });
  365.         $hasExpiredOrCancelledExtraSubscriptions = !empty($expiredOrCancelledExtraSub);
  366.         if (!$hasExpiredOrCancelledExtraSubscriptions) {
  367.             return $this->redirect('/');
  368.         }
  369.         $paymentFailed $request->query->get('failed');
  370.         if ($request->isMethod('get')) {
  371.             return $this->render('checkout/add-users-reactivation.html.twig', ['clientSecret' => null'paymentFailed' => $paymentFailed]);
  372.         }
  373.         if ($request->request->get('yes') !== null) {
  374.             $stripeResponse $userHandler->reactivateSublicences($loggedUser);
  375.             if ($stripeResponse['status'] === 'requires_action') {
  376.                 return $this->render('checkout/add-users-reactivation.html.twig', ['clientSecret' => $stripeResponse['secret'], 'paymentFailed' => null]);
  377.             }
  378.             if ($stripeResponse['status'] === 'failed') {
  379.                 return $this->render('checkout/add-users-reactivation.html.twig', ['clientSecret' => null'paymentFailed' => true]);
  380.             }
  381.         }
  382.         if (
  383.             $request->request->get('no') !== null
  384.         ) {
  385.             $userHandler->deactivateSublicences($loggedUser);
  386.         }
  387.         return $this->redirect('/workplace/home');
  388.     }
  389.     /**
  390.      * @Route("/set-password", name="set-password")
  391.      *
  392.      * @param SessionInterface $session
  393.      * @param Factory $ecommerceFactory
  394.      *
  395.      * @return Response
  396.      */
  397.     public function setPasswordAction(Request $requestFactory $ecommerceFactorySessionInterface $sessionTokenStorageInterface $tokenStorage)
  398.     {
  399.         $user $this->getUser();
  400.         if (!$this->isGranted('ROLE_USER')) {
  401.             return $this->redirect('/');
  402.         }
  403.         if (!$user) {
  404.             throw new AccessDeniedException('Not authorized.');
  405.         }
  406.         $form $this->createForm(PasswordFormType::class);
  407.         $form->handleRequest($request);
  408.         $errors = [];
  409.         if ($form->isSubmitted() && $form->isValid()) {
  410.             $plainPass $form->getData()['password'];
  411.             $user->setPassword($plainPass);
  412.             $user->save();
  413.             return $this->redirect('/home');
  414.         }
  415.         if ($form->isSubmitted() && !$form->isValid()) {
  416.             foreach ($form->get('password')->getErrors() as $error) {
  417.                 $errors[] = $error->getMessage();
  418.             }
  419.         }
  420.         return $this->render('account/first_time_password.html.twig', [
  421.             'form' => $form->createView(),
  422.             'errors' => $errors,
  423.         ]);
  424.     }
  425.     /**
  426.      * @Route("/checkout-completed", name="shop-checkout-completed")
  427.      *
  428.      * @param SessionInterface $session
  429.      * @param Factory $ecommerceFactory
  430.      *
  431.      * @return Response
  432.      */
  433.     public function checkoutCompletedAction(SessionInterface $sessionFactory $ecommerceFactory)
  434.     {
  435.         $orderId $session->get('last_order_id');
  436.         $order OnlineShopOrder::getById($orderId);
  437.         $trackingManager $ecommerceFactory->getTrackingManager();
  438.         $trackingManager->trackCheckoutComplete($order);
  439.         $cartManager $ecommerceFactory->getCartManager();
  440.         $cart $cartManager->getOrCreateCartByName('cart');
  441.         $checkoutManager $ecommerceFactory->getCheckoutManager($cart);
  442.         return $this->render('checkout/checkout_completed.html.twig', [
  443.             'order' => $order,
  444.             'hideBreadcrumbs' => true
  445.         ]);
  446.     }
  447.     /**
  448.      * @Route("/api/checkout-completed/{orderNumber}", name="api-shop-checkout-completed")
  449.      *
  450.      * @param SessionInterface $session
  451.      * @param Factory $ecommerceFactory
  452.      *
  453.      * @return Response
  454.      */
  455.     public function getCompletedCheckoutAction(SessionInterface $sessionFactory $ecommerceFactory$orderNumber)
  456.     {
  457.         $loggedUser $this->getUser();
  458.         if (!$loggedUser) {
  459.             throw new UnauthorizedHttpException('Not authorized.');
  460.         }
  461.         $order OnlineShopOrder::getByOrdernumber($orderNumber);
  462.         if (!$order) {
  463.             throw new BadRequestHttpException('No valid order provided.');
  464.         }
  465.         $orderData $order->getData()[0];
  466.         if ($loggedUser->getEmail() != $orderData->getCustomerEmail() && $loggedUser->getId() != $orderData->getCustomerOrderedBy()) {
  467.             throw new AccessDeniedException('You have no access to this order.');
  468.         }
  469.         
  470.         $items = [];
  471.         foreach ($orderData->getItems() as $item) {
  472.             $items[] = [
  473.                 'sku' => $item->getPart(),
  474.                 'name' => $item->getProductName(),
  475.                 'quantity' => $item->getAmount(),
  476.                 'totalPrice' => (float)$item->getTotalNetPrice(),
  477.             ];
  478.         }
  479.         foreach ($orderData->getGiftItems() as $item) {
  480.             $items[] = [
  481.                 'sku' => $item->getPart(),
  482.                 'name' => $item->getProductName(),
  483.                 'quantity' => $item->getAmount(),
  484.                 'totalPrice' => 'FREE',
  485.             ];
  486.         }
  487.         $deliveryAddress = [];
  488.         $deliveryAddress['addressLine1'] = $orderData->getDeliveryLine1();
  489.         $deliveryAddress['addressLine2'] = $orderData->getDeliveryLine2();
  490.         $deliveryAddress['city'] = $orderData->getDeliveryCity();
  491.         $deliveryAddress['county'] = $orderData->getDeliveryCounty();
  492.         $deliveryAddress['postcode'] = $orderData->getDeliveryZip();
  493.         $deliveryAddress['country'] = Countries::getName($orderData->getDeliveryCountry() == 'UK' 'GB' $orderData->getDeliveryCountry());
  494.         $customerInfo = [];
  495.         $customerInfo['firstName'] = $orderData->getCustomerFirstname();
  496.         $customerInfo['lastName'] = $orderData->getCustomerLastname();
  497.         $customerInfo['emailAddress'] = $orderData->getCustomerEmail();
  498.         $customerInfo['gdcNumber'] = $orderData->getCustomerGdcNumber();
  499.         $data = [
  500.             'state' => $orderData->getOrderState(),
  501.             'deliveryAddress' => $deliveryAddress,
  502.             'customerInfo' => $customerInfo,
  503.             'items' => $items,
  504.             'amount' => [
  505.                 'net' => $orderData->getTotalNetPrice(),
  506.                 'delivery' => floatval($orderData->getTotalNetPrice()) - floatval($orderData->getSubTotalNetPrice()),
  507.                 'gross' => $orderData->getTotalPrice()
  508.             ]
  509.         ];
  510.         $response = new Response();
  511.         $response->headers->set('Content-Type''application/json');
  512.         $response->headers->set('Access-Control-Allow-Origin''*');
  513.         $response->setContent(json_encode(['order' => $data]));
  514.         return $response;
  515.     }
  516.     /**
  517.      * @Route("/api/checkout-default", name="checkout-default", methods="POST")
  518.      *
  519.      * @param Factory $factory
  520.      * @param Request $request
  521.      * @param BreadcrumbHelperService $breadcrumbHelperService
  522.      * @param Factory $ecommerceFactory
  523.      *
  524.      * @return Response|RedirectResponse
  525.      */
  526.     public function defaultCheckoutAction(Factory $factoryRequest $requestBreadcrumbHelperService $breadcrumbHelperServicePermissionService $permissionProviderTrycareService $trycareProvider)
  527.     {
  528.         $loggedUser $this->getUser();
  529.         if (!$loggedUser) {
  530.             throw new UnauthorizedHttpException('Not authorized.');
  531.         }
  532.         // $permissions = $permissionProvider->checkPermissions('placeOrder', $loggedUser);
  533.         $data json_decode($request->getContent(), true);
  534.         $environment Factory::getInstance()->getEnvironment();
  535.         $environment->setCurrentCheckoutTenant('oscare');
  536.         $environment->save();
  537.         $cartManager $factory->getCartManager();
  538.         $cart $cartManager->getOrCreateCartByName(self::TRYCARE_CART_NAME);
  539.         $items $cart->getItems();
  540.         if (empty($items)) {
  541.             throw new BadRequestHttpException('Cart is empty');
  542.         }
  543.         if (!$data['deliveryAddress'] || !$data['billingAddress']) {
  544.             throw new BadRequestHttpException('Addresses must be provided.');
  545.         }
  546.         $checkoutManager $factory->getCheckoutManager($cart);
  547.         $clinic $loggedUser->getClinic();
  548.         $deliveryAddress DataObject::getById($data['deliveryAddress']);
  549.         if (!$deliveryAddress) {
  550.             throw new BadRequestHttpException('Delivery id required');
  551.         }
  552.         $deliveryInputData = [
  553.             'comment' => $data['comment'],
  554.             'line1' => $deliveryAddress->getLine1(),
  555.             'line2' => $deliveryAddress->getLine2(),
  556.             'city' => $deliveryAddress->getCity(),
  557.             'zip' => $deliveryAddress->getPostcode(),
  558.             'county' => $deliveryAddress->getCounty(),
  559.             'countryCode' => $deliveryAddress->getCountry(),
  560.             'phone' => $clinic->getPhone(),
  561.             'company' => $clinic->getDisplayName(),
  562.         ];
  563.         //commit delivery data step
  564.         $deliveryData = new \stdClass();
  565.         foreach ($deliveryInputData as $key => $value) {
  566.             $deliveryData->{$key} = $value;
  567.         }
  568.         $deliveryStep $checkoutManager->getCheckoutStep('deliveryaddress');
  569.         $checkoutManager->commitStep($deliveryStep$deliveryData);
  570.         $billingAddress DataObject::getById($data['billingAddress']);
  571.         if (!$billingAddress) {
  572.             throw new BadRequestHttpException('Billing id required');
  573.         }
  574.         $billingInputData = [
  575.             'line1' => $billingAddress->getLine1(),
  576.             'line2' => $billingAddress->getLine2(),
  577.             'city' => $billingAddress->getCity(),
  578.             'zip' => $billingAddress->getPostcode(),
  579.             'county' => $billingAddress->getCounty(),
  580.             'countryCode' => $billingAddress->getCountry(),
  581.             'company' => $clinic->getDisplayName(),
  582.         ];
  583.         //commit billing data step
  584.         $billingData = new \stdClass();
  585.         foreach ($billingInputData as $key => $value) {
  586.             $billingData->{$key} = $value;
  587.         }
  588.         $billingStep $checkoutManager->getCheckoutStep('billingaddress');
  589.         $checkoutManager->commitStep($billingStep$billingData);
  590.         $superuser $clinic->getSuperuser();
  591.         $userData = new \stdClass();
  592.         $customerData = [
  593.             'firstname' => $superuser->getFirstname(),
  594.             'lastname' => $superuser->getLastname(),
  595.             'email' => $clinic->getSuperuser()->getEmail(),
  596.             'company' => $clinic->getDisplayName(),
  597.             'orderedBy' => $loggedUser->getId(),
  598.             'gdcNumber' =>  $clinic->getSuperuser()->getGdcNumber(),
  599.         ];
  600.         foreach ($customerData as $key => $value) {
  601.             $userData->{$key} = $value;
  602.         }
  603.         // commit customer data step
  604.         $customerStep $checkoutManager->getCheckoutStep('collectInfo');
  605.         $checkoutManager->commitStep($customerStep$userData);
  606.         //TODO remove this - only needed, because one step only is not supported by the framework right now
  607.         $confirm $checkoutManager->getCheckoutStep('confirm');
  608.         $checkoutManager->commitStep($confirmtrue);
  609.         $order $checkoutManager->commitOrder();
  610.         
  611.         if ($order->getOrderState() == AbstractOrder::ORDER_STATE_ABORTED) {
  612.             throw new AccessDeniedHttpException('Order processing has failed.');
  613.         }
  614.         $response = new Response();
  615.         $response->headers->set('Content-Type''application/json');
  616.         $response->headers->set('Access-Control-Allow-Origin''*');
  617.         $response->setContent(json_encode(['order' => $order->getOrdernumber()]));
  618.         return $response;
  619.     }
  620.     /**
  621.      * @param Request $request
  622.      *
  623.      * @return Response
  624.      */
  625.     public function confirmationMailAction(Request $request)
  626.     {
  627.         $order $request->get('order');
  628.         if ($request->get('order-id')) {
  629.             $order OnlineShopOrder::getById($request->get('order-id'));
  630.         }
  631.         return $this->render('checkout/confirmation_mail.html.twig', [
  632.             'order' => $order,
  633.             'ordernumber' => $request->get('ordernumber')
  634.         ]);
  635.     }
  636. }