src/Controller/OrderController.php line 188

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Order;
  4. use App\Entity\Person;
  5. use App\Entity\Invoice;
  6. use App\Form\OrderType;
  7. use App\Entity\WaitItem;
  8. use App\Entity\OrderItem;
  9. use App\Service\UiService;
  10. use App\Form\OrderStatusType;
  11. use App\Service\OrderService;
  12. use Doctrine\DBAL\Connection;
  13. use App\Service\MailerService;
  14. use App\Entity\OrderItemPerson;
  15. use App\Service\InvoiceService;
  16. use App\Service\ZoomService;
  17. use App\Service\IbanService;
  18. use App\Entity\CourseOccurrence;
  19. use App\Form\OrderItemPersonCopy;
  20. use App\Repository\OrderRepository;
  21. use App\Repository\WaitItemRepository;
  22. use App\Service\EmailHistoryService;
  23. use App\Repository\PersonRepository;
  24. use App\Repository\InvoiceRepository;
  25. use App\Service\ConfigurationService;
  26. use App\Form\OrderItemPersonCancelDate;
  27. use App\Entity\CourseSubscriptionBooking;
  28. use Doctrine\Persistence\ManagerRegistry;
  29. use Doctrine\Common\Collections\Collection;
  30. use Psr\Log\LoggerInterface;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use App\Repository\OrderItemPersonRepository;
  33. use App\Repository\CourseOccurrenceRepository;
  34. use Symfony\Component\HttpFoundation\Response;
  35. use Symfony\Component\Routing\Annotation\Route;
  36. use App\Repository\CourseOccurrenceTimeRepository;
  37. use Symfony\Component\HttpFoundation\RequestStack;
  38. use Menke\UserBundle\Controller\AbstractClientableController;
  39. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  40. use Menke\UserBundle\Entity\Client;
  41. use Symfony\Component\Validator\Constraints\Iban;
  42. /**
  43.  * @Route("/order")
  44.  * @IsGranted("ROLE_MANAGER")
  45.  */
  46. class OrderController extends AbstractClientableController
  47. {
  48.     const LISTING_LIMIT 25;
  49.     /**
  50.      * @Route("/", name="order_index", methods="GET")
  51.      */
  52.     public function index(
  53.         UiService $uiService,
  54.         OrderRepository $orderRepo,
  55.         OrderItemPersonRepository $orderItemPersonRepository,
  56.         Request $request,
  57.         RequestStack $requestStack
  58.     ): Response {
  59.         $order $uiService->getSortOrder('order-index-listing');
  60.         $em $this->getDoctrine()->getManager();
  61.         $filterOrders $request->get('orderAction');
  62.         if ($filterOrders) {
  63.             $requestStack->getSession()->set('orderFilter'$filterOrders);
  64.         } else {
  65.             $requestStack->getSession()->set('orderFilter''pending');
  66.         }
  67.         $dateareas $request->get('datearea');
  68.         if ($dateareas) {
  69.             $requestStack->getSession()->set('datearea'$dateareas);
  70.         }
  71. /*  Alle Member in den Orders und order item persons abgleichen und aktualisieren
  72.         $orderstest = $orderRepo->findAll();
  73.         foreach ($orderstest as $ordertest) {
  74.             if($ordertest->getCustomer() && $ordertest->getCustomer()->getMember()){
  75.             $ordertest->setCustomerMember($ordertest->getCustomer()->getMember());
  76.             $em->persist($ordertest);}
  77.         }
  78.         $entries = $orderItemPersonRepository->findAll();
  79.         foreach ($entries as $entry) {
  80.             // Hier wird der aktualisierte Member-Wert gesetzt
  81.             if($entry->getPerson() && $entry->getPerson()->getMember()){
  82.             $entry->setMember($entry->getPerson()->getMember());
  83.             $em->persist($entry);}
  84.         }
  85.   */     
  86.         $orders $orderRepo->getByClientPaged(
  87.             $this->getCurrentClient(),
  88.             self::LISTING_LIMIT,
  89.             $order['orderDirection'] ?? 'desc',
  90.             $order['orderBy'] ?? 'id',
  91.             1,
  92.             ($filterOrders) ? $filterOrders 'pending',
  93.             ($dateareas) ? $dateareas null,
  94.         );
  95.         return $this->render('order/index.html.twig', [
  96.             'uiService' => $uiService,
  97.             'orders' => $orders->getIterator(),
  98.             'total' => $orders->count(),
  99.             'pages' => ceil($orders->count() / self::LISTING_LIMIT),
  100.             'page' => 1,
  101.             'orderAction' => $request->get('orderAction'),
  102.             'datearea' => $request->get('datearea'),
  103.         ]);
  104.     }
  105.     /**
  106.      * @Route("/fast", name="order_index_fast", methods="GET")
  107.      */
  108.     public function indexfast(
  109.         UiService $uiService,
  110.         OrderRepository $orderRepo,
  111.         Request $request,
  112.         RequestStack $requestStack
  113.     ): Response {
  114.         $order $uiService->getSortOrder('order-index-listing');
  115.         $filterOrders $request->get('orderAction');
  116.         if ($filterOrders) {
  117.             $requestStack->getSession()->set('orderFilter'$filterOrders);
  118.         } else {
  119.             $requestStack->getSession()->set('orderFilter''pending');
  120.         }
  121.         $orders $orderRepo->getByClientPaged(
  122.             $this->getCurrentClient(),
  123.             self::LISTING_LIMIT,
  124.             $order['orderDirection'] ?? 'desc',
  125.             $order['orderBy'] ?? 'date',
  126.             1,
  127.             ($filterOrders) ? $filterOrders ''
  128.         );
  129.         return $this->render('order/fastindex.html.twig', [
  130.             'uiService' => $uiService,
  131.             'orders' => $orders->getIterator(),
  132.             'total' => $orders->count(),
  133.             'pages' => ceil($orders->count() / self::LISTING_LIMIT),
  134.             'page' => 1,
  135.             'orderAction' => $request->get('orderAction'),
  136.         ]);
  137.     }
  138.     /**
  139.      * @Route("/{page}/{orderby}/{order}", name="order_index_listing", methods="GET", requirements={"page"="\d+","order"="asc|desc"})
  140.      */
  141.     public function indexListing(
  142.         OrderRepository $orderRepo,
  143.         UiService $uiService,
  144.         $page,
  145.         $orderby,
  146.         $order,
  147.         Request $request,
  148.         RequestStack $requestStack): Response {
  149.         $uiService->storeSortOrder('order-index-listing'$orderby$order);
  150.         $orders $orderRepo->getByClientPaged(
  151.             $this->getCurrentClient(),
  152.             self::LISTING_LIMIT,
  153.             $order,
  154.             $orderby,
  155.             $page,
  156.             $requestStack->getSession()->get('orderFilter')
  157.         );
  158.         return $this->render('order/_index_listing.html.twig', [
  159.             'uiService' => $uiService,
  160.             'orders' => $orders->getIterator(),
  161.             'total' => $orders->count(),
  162.             'pages' => ceil($orders->count() / self::LISTING_LIMIT),
  163.             'page' => $page,
  164.         ]);
  165.     }
  166.     /**
  167.      * @Route("/new/{return}", name="order_new", methods="GET|POST")
  168.      */
  169.     public function new(
  170.         Request $request,
  171.         $return null,
  172.         PersonRepository $personRepo,
  173.         ConfigurationService $configService,
  174.         OrderService $orderService,
  175.         ZoomService $zoomService,
  176.         IbanService $ibanService): Response {
  177.         $customer null;
  178.         $invoiceRecipient null;
  179.         $isEmptyParticipants false;
  180.         if ($return) {
  181.             $customer $personRepo->find($return);
  182.             $invoiceRecipient $personRepo->getInvoiceReciepientMembers($return);
  183.             $invoiceRecipient $this->createInvoiceRecipientValues($invoiceRecipient$customer);
  184.             $customerChildrens $personRepo->getMembersByClient($customer);
  185.             $isEmptyParticipants = (empty($customerChildrens)) ? true false;
  186.         }
  187.         $em $this->getDoctrine()->getManager();
  188.         $order = new Order();
  189.         $order->setDate(new \DateTime());
  190.         $order->setStatus(Order::STATUS_PENDING);
  191.         $order->setNumber($configService->getNewOrderNumberByClient($this->getCurrentClient()));
  192.         $order->setClient($this->getCurrentClient());
  193.         $order->setCustomer($customer);
  194.     
  195.         $order->setCustomerData($customer);
  196.         $order->setCreated(new \DateTime());
  197.         $order->setPerson($customer);
  198.         $form $this->createForm(OrderType::class, $order, [
  199.             'client' => $this->getCurrentClient(),
  200.             'taxes' => $configService->getTaxConfigbyClient($this->getCurrentClient()),
  201.             'customer' => $customer,
  202.             'invoiceRecipient' => $invoiceRecipient,
  203.             'form_type' => OrderType::TYPE_CREATE_FOR_CUSTOMER
  204.         ]);
  205.         $form->handleRequest($request);
  206.         //   $em->persist($order);
  207.         // Check if creation is possible
  208.         if ($form->isSubmitted() && $form->isValid()) {
  209.             if (!$order->checkCustomerData($customer)) {
  210.                 $this->addFlash('error''Die Kundendaten sind unvollständig. Es kann keine neue Bestellung angelegt werden.');
  211.                 if ($return) {
  212.                     return $this->redirectToRoute('customer_orders', ['id' => $return]);
  213.                 } else {
  214.                     return $this->redirectToRoute('order_index');
  215.                 }
  216.             }
  217.             foreach ($order->getOrderItems() as $orderItem) {
  218.                 if ($orderItem->getCourseOccurrence()) {
  219.                     $orderItem->setCourseOccurrence($orderItem->getCourseOccurrence());
  220.                     if ($orderItem->getCourseOccurrence()->getCourse()->getMaterialCost() > || $orderItem->getCourseOccurrence()->getMaterialCost() > 0) {
  221.                         $item = new OrderItem();
  222.                         $item->setCourseOccurrence($orderItem->getCourseOccurrence());
  223.                         $item->setPrice($orderItem->getCourseOccurrence()->getMaterialCost() ?? $orderItem->getCourseOccurrence()->getCourse()->getMaterialCost());
  224.                         $item->setTaxRate($orderItem->getCourseOccurrence()->getTaxRate() ?? $orderItem->getCourseOccurrence()->getCourse()->getTaxRate());
  225.                         $item->setName('Materialkosten');
  226.                         $item->setQuantity($orderItem->getQuantity());
  227.                         // $item->setCourseItem($orderItem->getCourseOccurrence()->getCourse());
  228.                          $item->setCourseItem($orderItem);
  229.                         $item->setIsFree(false);
  230.                         $item->setOrder($order);
  231.                         $item->setCreated(new \Datetime());
  232.                         // $item->setCourseItem($orderItem);
  233.                         $em->persist($item);
  234.                     }
  235.                     $em->persist($orderItem);
  236.                 }
  237.                 // Skip participants check for free items
  238.                 if ($orderItem->getCourseOccurrence() === null) {
  239.                     continue;
  240.                 }
  241.                 // Check if order item has at least one participant
  242.                 if (count($orderItem->getParticipants()) == 0) {
  243.                     $this->addFlash('error''Der Kurs enthält keine Teilnehmer.');
  244.                     return $this->redirectToRoute('order_new', ['return' => $return]);
  245.                 }
  246.             }
  247.             $allItemsBookable true;
  248.             // $em->flush();
  249.             foreach ($order->getOrderItems() as $orderItem) {
  250.                 $orderItem->setCourseOccurrence($orderItem->getCourseOccurrence());
  251.                 
  252.              
  253.                 $orderItem->setCreated(new \DateTime());
  254.                 if ($orderItem->getCourse()) {
  255.                     $orderItem->setName($orderItem->getCourse()->getTitle());
  256.                     $orderItem->setDescription($orderItem->getCourse()->getSubtitle());
  257.                 } else {
  258.                     $orderItem->setName($orderItem->getName());
  259.                     $orderItem->setDescription($orderItem->getDescription());
  260.                 }
  261.                 //    $em->persist($orderItem);
  262.                 //    $em->flush($orderItem);
  263.                 if ($orderItem->getCourseOccurrence()) {
  264.                     $occurrence $orderItem->getCourseOccurrence();
  265.                     ///// testen und abgleichen was in der Datenbank steht und wie viele Buchungen es wirklich gibt ////
  266.                     //  $occurrence->setBookedSlots($occurrence->getBookedSlots());
  267.                     //    $em->persist($occurrence);
  268.                     //    $em->flush($occurrence);
  269.                     if (($occurrence->getSlots() < ($orderItem->getQuantity() + $occurrence->getBookedSlots())) && $occurrence->getReservationAllowed()) {
  270.                         $waitItem WaitItem::fromOrderItem($orderItem);
  271.                         $waitItem->setCreated(new \DateTime());
  272.                         $em->persist($waitItem);
  273.                         foreach ($orderItem->getParticipants() as $participant) {
  274.                             $participant->setOrderItem(null);
  275.                             $participant->setTitle($participant->getPerson()->getTitle());
  276.                             $participant->setSalutation($participant->getPerson()->getSalutation());
  277.                             $participant->setMember($participant->getPerson()->getMember());
  278.                             $participant->setFirstname($participant->getPerson()->getFirstname());
  279.                             $participant->setLastname($participant->getPerson()->getLastname());
  280.                             $participant->setDateOfBirth($participant->getPerson()->getDateOfBirth());
  281.                             $participant->setComment($participant->getPerson()->getComment());
  282.                             $participant->setOrderItem($orderItem);
  283.                             $participant->setCreated(new \DateTime());
  284.                             // $orderItem->removeParticipant($participant);
  285.                             //$orderItem->setQuantity($orderItem->getQuantity() - 1);
  286.                             $em->persist($participant);
  287.                         }
  288.                         $order->addWaitItem($waitItem);
  289.                         $this->addFlash('error''Im Kurs "' $occurrence->getTitle() . '" sind nicht mehr genug Plätze verfügbar. Es fehlen "' . ($orderItem->getQuantity() + $occurrence->getBookedSlots()) - $occurrence->getSlots() . '" Plätze. Die komplette Buchung wurde stattdessen zur Warteliste hinzugefügt.');
  290.                         $em->flush();
  291.                         // $order->removeOrderItem($orderItem);
  292.                         $orderItem->setOrder(null);
  293.                         $orderItem->setStatus('wait_item');
  294.                         //$orderItem->setCancelledQuantity($orderItem->getQuantity());
  295.                         //   $orderItem->setQuantity($orderItem->getQuantity());
  296.                         $em->persist($orderItem);
  297.                         $em->persist($order);
  298.                         //$em->remove($orderItem);
  299.                         $em->flush();
  300.                         //  var_dump($orderItem->getOrder());
  301.                         return $this->redirectToRoute('customer_orders', ['id' => $return]);
  302.                     } elseif (($occurrence->getSlots() < ($orderItem->getQuantity() + $occurrence->getBookedSlots())) && !$occurrence->getReservationAllowed()) {
  303.                         //  $occurrence->setBookedSlots($occurrence->getBookedSlots());
  304.                         $em->persist($occurrence);
  305.                         $em->remove($order);
  306.                         $em->flush();
  307.                         $allItemsBookable false;
  308.                         $this->addFlash('error''Im Kurs "' $occurrence->getTitle() . '" sind nicht mehr genug Plätze verfügbar. Es fehlen "' . ($orderItem->getQuantity() + $occurrence->getBookedSlots()) - $occurrence->getSlots() . '" Plätze.');
  309.                         return $this->redirectToRoute('customer_orders', ['id' => $return]);
  310.                     } else {
  311.                         if ($orderItem->getCourseOccurrence()->getCourse()->getCourseNature() == 'CourseSubscription') {
  312.                             $this->addFlash('warning''courseSubsciption');
  313.                             //    $courseSubscriptionBooking = new CourseSubscriptionBooking($orderItem, $orderItem->getCourse());
  314.                             //    $courseSubscriptionBooking->setOrderItem($orderItem);
  315.                             //    $courseSubscriptionBooking->setCourse($orderItem->getCourseOccurrence()->getCourse());
  316.                             //    $courseSubscriptionBooking->setCourseSubscription($orderItem->getCourseOccurrence()->getCourse()->getSubscription());
  317.                             //    $orderItem->setCourseSubscriptionBooking($courseSubscriptionBooking);
  318.                             //    $em->persist($courseSubscriptionBooking);
  319.                         }
  320.                         /*
  321.                         foreach ($orderItem->getParticipants() as $participant) 
  322.                         { 
  323.                             $occurrence->setBookedSlots($occurrence->getBookedSlots() + 1);
  324.                         }
  325.                         $em->persist($occurrence);
  326.                         */
  327.                         // $em->persist($occurrence);
  328.                         //            $occurrence = $orderItem->getCourseOccurrence();
  329.                         //  $occurrence->setBookedSlots($occurrence->getBookedSlotsDirectly() + $orderItem->getQuantity());
  330.                         //  $occurrence->setBookedSlots($occurrence->getBookedSlots() + $orderItem->getQuantity());
  331.                         //            $em->persist($occurrence);
  332.                         //     $em->flush();
  333.                         //   $occurrences[] = $occurrence;
  334.                     }
  335.                 }
  336.                 //  $em->flush();
  337.             }
  338.             $this->updateParticipantsOfOrder($order);
  339.             if ($orderItem->getCourse()) {
  340.                 $occurrence->setBookedSlots($occurrence->getBookedSlots() + $orderItem->getQuantity());
  341.             }
  342.             //  $em->flush();
  343.             if ($allItemsBookable) {
  344.                 if (count($order->getOrderItems()) > ||  count($order->getWaitItems()) > 0) {
  345.                     $order->setClient($this->getCurrentClient());
  346.                     $order->setCustomer($customer);
  347.                     $order->setCustomerData($customer);
  348.                     if ($customer->getIban()) {
  349.                         $order->setPaymentType(Order::PAYMENT_DEBIT);
  350.                         $order->setIban(
  351.                             strtoupper(
  352.                             preg_replace('/\s+/'''$customer->getIban())
  353.                                        )
  354.                                );
  355.                         $order->setBic($customer->getBic());
  356.                         $order->setBank($customer->getBank());
  357.                     }
  358.                     $orderItem->setOrder($order);
  359.                     $orderItem->getCourseOccurrence();
  360.                     // Ggf. nachfolgende Bestellungen fuer Abokurse generieren und speichern
  361.                     $flashs = [];
  362.                     $followingOrders $orderService->generateOrdersForSubscriptionCoursesAllFollowingOccurrences($this->getCurrentClient(), $order$flashs);
  363.                     foreach ($followingOrders as $orderToSave) {
  364.                         $em->persist($orderToSave);
  365.                     }
  366.                     foreach ($flashs as $flashToShow) {
  367.                         foreach ($flashToShow as $key => $value) {
  368.                             $this->addFlash($key$value);
  369.                         }
  370.                     }
  371.                 }
  372.                 /*
  373.                 foreach ($order->getOrderItems() as $orderItem) {
  374.                     if ($orderItem->getMaterialCosts()) {
  375.                                    $item = new OrderItem();
  376.                                    $item->setCourseOccurrence($orderItem->getCourseOccurrence());
  377.                                    $item->setPrice($orderItem->getCourseOccurrence()->getCourse()->getMaterialCost());
  378.                                    $item->setTaxRate($orderItem->getCourseOccurrence()->getCourse()->getTaxRate());
  379.                                    $item->setQuantity(1);
  380.                                    $item->setIsFree(false);
  381.                                    $item->setOrder($order);
  382.                                    $item->setCourseItem($orderItem);
  383.                                    $item->setCreated(new \Datetime());
  384.                        }
  385.                        $em->persist($item);
  386.                    }
  387.                    */
  388. ###################################### ZOOM MEETING ########################################
  389.     if (isset($_ENV['ZOOM_WEBINAR']) && $_ENV['ZOOM_WEBINAR'] === 1){
  390.         foreach ($order->getOrderItems() as $orderItem) {
  391.             foreach ($orderItem->getParticipants() as $participant) {
  392.                 $registrant $zoomService->addRegistrantToWebinar(
  393.                     $orderItem->getCourseOccurrence()->getCode(),
  394.                     $participant->getPerson()->getContactEmail(),
  395.                     $participant->getPerson()->getFirstname(),
  396.                     $participant->getPerson()->getLastname()
  397.                 );
  398.             }
  399.         }
  400.     }
  401. ###################################### ZOOM MEETING ########################################
  402.                 $em->persist($order);
  403.                 $em->flush();
  404.                 if ($return) {
  405.                     if ($orderItem->getCourse()) {
  406.                         $this->addFlash('warning''Der Kurs "' $occurrence->getTitle() . '" wurde mit ' $orderItem->getQuantity() . ' Plätzen bebucht');
  407.                     }
  408.                     return $this->redirectToRoute('customer_orders', ['id' => $return]);
  409.                 } else {
  410.                     return $this->redirectToRoute('order_index');
  411.                 }
  412.             }
  413.             $em->remove($orderItem);
  414.             $em->remove($order);
  415.             $em->flush();
  416.             $this->addFlash('warning''LETZTE MÖGLICHKEIT "' $occurrence->getTitle() . '" ' $occurrence->getSlots() . ' | ' $occurrence->getBookedSlots() . '|' . ($occurrence->getSlots() - $occurrence->getBookedSlots()) . ' | ' $orderItem->getQuantity());
  417.         }
  418.         return $this->render('order/new.html.twig', [
  419.             'order' => $order,
  420.             'form' => $form->createView(),
  421.             'customer' => $customer,
  422.             'invoiceRecipient' => $invoiceRecipient,
  423.             'invalidCustomerData' => !$order->checkCustomerData($customer),
  424.             'isEmptyParticipants' => $isEmptyParticipants,
  425.             'isInvoiceClosed' => false
  426.         ]);
  427.     }
  428.     /**
  429.      * @Route("/{id}", name="order_show", methods="GET|POST", requirements={"id"="\d+"})
  430.      */
  431.     public function show(
  432.         Request $request,
  433.         Order $order,
  434.         InvoiceRepository $invoiceRepo
  435.     ): Response {
  436.         $this->denyAccessUnlessGranted('ROLE_MANAGER'$order);
  437.         $form $this->createForm(OrderStatusType::class, $order);
  438.         $form->handleRequest($request);
  439.         if ($form->isSubmitted() && $form->isValid()) {
  440.             $this->getDoctrine()->getManager()->flush();
  441.             return $this->redirectToRoute('order_show', ['id' => $order->getId()]);
  442.         }
  443.       
  444.         $orderedInvoices $invoiceRepo->getOrderedInvoices($order->getId());
  445.         $isInvoiceWithCancillation $this->isInvoiceWithCancillation($order->getInvoices());
  446.         return $this->render('order/show.html.twig', [
  447.             'order' => $order,
  448.             'form' => $form->createView(),
  449.             'isInvoiceWithCancillation' => $isInvoiceWithCancillation,
  450.             'orderedInvoices' => $orderedInvoices
  451.         ]);
  452.     }
  453.     /**
  454.      * @Route("/search/{occurrenceId}/{timeId}", name="order_search", methods="GET|POST", requirements={"id"="\d+"})
  455.      */
  456.     public function search(
  457.         Request $request,
  458.         Connection $connection,
  459.         CourseOccurrenceTimeRepository $timeRepository
  460.     ): Response {
  461.         $time $timeRepository->find($request->get('timeId'));
  462.         $sql 'SELECT
  463.             oi.*
  464.         FROM
  465.             customer_order_item oi,
  466.             course_occurrence o
  467.         WHERE
  468.             o.id = oi.course_occurrence_id AND
  469.             o.start = "' $time->getStart()->format('Y-m-d H:i:s') . '"
  470.         GROUP BY
  471.             oi._order_id';
  472.         $result $connection->fetchAssoc($sql);
  473.         if (empty($result)) {
  474.             $sql 'SELECT
  475.                 oi.*
  476.             FROM
  477.                 wait_item oi,
  478.                 course_occurrence o
  479.             WHERE
  480.                 o.id = oi.course_occurrence_id AND
  481.                 o.start = "' $time->getStart()->format('Y-m-d H:i:s') . '"
  482.             GROUP BY
  483.                 oi._order_id';
  484.             $result $connection->fetchAssoc($sql);
  485.         }
  486.         return $this->redirectToRoute('order_show', ['id' => $result['_order_id']]);
  487.     }
  488.     /**
  489.      * @Route("/{id}/edit/{return}", name="order_edit", methods="GET|POST", requirements={"id"="\d+","return"="\d+"})
  490.      */
  491.     public function edit(
  492.         Request $request,
  493.         Order $order,
  494.         $return '',
  495.         ConfigurationService $configService,
  496.         PersonRepository $personRepo
  497.     ): Response {
  498.         $isEmptyParticipants false;
  499.         $invoiceRecipient null;
  500.         $isInvoiceClosed false;
  501.         $this->denyAccessUnlessGranted('ROLE_MANAGER'$order);
  502.         $order->setModified(new \DateTime());
  503.         $customer null;
  504.         if ($order->getCustomer()) {
  505.             $customer $order->getCustomer();
  506.         }
  507.         if (
  508.             $order->getInvoices()->first() &&
  509.             $order->getInvoices()->first()->getStatus() == Invoice::STATUS_CLOSED
  510.         ) {
  511.             $isInvoiceClosed true;
  512.         }
  513.         if ($return) {
  514.             $customer $personRepo->find($return);
  515.             $invoiceRecipient $personRepo->getInvoiceReciepientMembers($return);
  516.             $invoiceRecipient $this->createInvoiceRecipientValues($invoiceRecipient$customer);
  517.             $customerChildrens $personRepo->getMembersByClient($customer);
  518.             $isEmptyParticipants = (empty($customerChildrens)) ? true false;
  519.         }
  520.         if ($order->getStatus() != Order::STATUS_PENDING) {
  521.             $this->addFlash('notice''Die Bestellung kann nur bearbeitet werden wenn Sie in Wartestellung ist.');
  522.             if ($return) {
  523.                 return $this->redirectToRoute('customer_orders', ['id' => $return]);
  524.             } else {
  525.                 return $this->redirectToRoute('order_index');
  526.             }
  527.         }
  528.         $form $this->createForm(OrderType::class, $order, [
  529.             'client' => $this->getCurrentClient(),
  530.             'taxes' => $configService->getTaxConfigbyClient($this->getCurrentClient()),
  531.             'invoiceRecipient' => $invoiceRecipient,
  532.             'customer' => $customer,
  533.             'form_type' => OrderType::TYPE_CREATE_FOR_CUSTOMER
  534.         ]);
  535.         $form->handleRequest($request);
  536.         if ($form->isSubmitted() && $form->isValid()) {
  537.            // $this->updateParticipantsOfOrder($order);
  538.             $em $this->getDoctrine()->getManager();
  539.             foreach ($order->getOrderItems() as $item) {
  540.                 $item->setModified(new \DateTime());
  541.                 if (!$item->isFree() && $item->getCourseOccurrence()) {
  542.                     $item->setName($item->getCourseOccurrence()->getTitle());
  543.                     $em->persist($item);
  544.                 } else {
  545.                    // $item->setCourseOccurrence(null);
  546.                     $em->persist($item);
  547.                 }
  548.             }
  549.             $em->flush();
  550.             $this->addFlash('notice''Die Bestellung wurde bearbeitet.');
  551.             return $this->redirectToRoute('order_index');
  552.             // }
  553.         }
  554.         return $this->render('order/edit.html.twig', [
  555.             'order' => $order,
  556.             'form' => $form->createView(),
  557.             'customer' => $customer,
  558.             'isEmptyParticipants' => $isEmptyParticipants,
  559.             'invoiceRecipient' => $invoiceRecipient,
  560.             'isInvoiceClosed' => $isInvoiceClosed
  561.         ]);
  562.     }
  563.     /**
  564.      * @Route("/{id}/cancel", name="order_cancel", methods="POST")
  565.      */
  566.     public function cancel(
  567.         Request $request,
  568.         Order $order,
  569.         ConfigurationService $configService,
  570.         OrderService $orderService
  571.     ): Response {
  572.         $this->denyAccessUnlessGranted('ROLE_MANAGER'$order);
  573.         if ($this->isCsrfTokenValid('cancel' $order->getId(), $request->request->get('_token'))) {
  574.             $em $this->getDoctrine()->getManager();
  575.             foreach ($order->getOrderItems() as $orderItem) {
  576.                 // If order item is connected to time slot mark it bookable again
  577.                 if ($time $orderItem->getCourseOccurrenceTime()) {
  578.                     $time->setAvailability('Bookable');
  579.                     $time->setOrderItem(null);
  580.                 }
  581.                 if ($orderItem) {
  582.                     $orderItem->setStatus('cancelled');
  583.                     foreach ($orderItem->getParticipants() as $person) {
  584.                         $person->setStatus('cancelled');
  585.                         $person->setCancelled(new \DateTime());
  586.                         $person->setModified(new \DateTime());
  587.                         $em->persist($person);
  588.                     }
  589.                     $orderItem->setCancelledQuantity($orderItem->getCancelledQuantity() + 1);
  590.                     $orderItem->setQuantity($orderItem->getQuantity() - 1);
  591.                     $orderItem->setModified(new \DateTime());
  592.                     //$orderItem->setQuantity('0');
  593.                 }
  594.             }
  595.             foreach ($order->getWaitItems() as $waitItem) {
  596.                 if ($time $waitItem->getCourseOccurrenceTime()) {
  597.                     $time->setAvailability('Requestable');
  598.                     $time->setWaitItem(null);
  599.                 }
  600.             }
  601.             foreach ($order->getInvoices() as $invoice) {
  602.                 if (!$invoice->isCancelled() && !$invoice->isCancellation()) {
  603.                     $cancellation $orderService->createCancellation($invoice);
  604.                     $cancellation->setSignedBy($this->getCurrentUser());
  605.                     $invoice->setCancelled(true);
  606.                     $em->persist($cancellation);
  607.                 }
  608.             }
  609.             $order->setStatus(Order::STATUS_CANCELLED);
  610.             $order->setModified(new \DateTime());
  611.             $orderService->calculateCancelOrderItems($order);
  612.             $em->flush();
  613.             $this->addFlash('notice''Bestellung storniert');
  614.         }
  615.         return $this->redirectToRoute('order_show', ['id' => $order->getId()]);
  616.     }
  617.     /**
  618.      * @Route("/set-cancel-date/{id}", name="participant_set-cancel-date")
  619.      */
  620.     public function setCancelDateForParticicpant(
  621.         Request $request,
  622.         OrderItemPerson $participant,
  623.         OrderService $orderService,
  624.         RequestStack $requestStack,
  625.         ManagerRegistry $managerRegistry
  626.         //  LoggerInterface $logger
  627.     ): Response {
  628.         $this->denyAccessUnlessGranted('ROLE_MANAGER'$participant->getOrderItem()->getOrder());
  629.         $form $this->createForm(OrderItemPersonCancelDate::class, null, [
  630.             'action' => $this->generateUrl('participant_set-cancel-date', ['id' => $participant->getId()])
  631.         ]);
  632.         $form->handleRequest($request);
  633.         $participant->setCancelled($orderService->getCancelDateForParticipantInCourse($this->getCurrentClient(), $participant));
  634.         if ($form->isSubmitted() && $form->isValid()) {
  635.             /**
  636.              * @var \DateTimeInterface $cancelDate
  637.              */
  638.             $cancelDate $form->getData()['cancelDate'];
  639.             // Kuendigungsdatum in entsprechenden Teilnehmereintrag im Kurs schreiben
  640.             $participant->setCancelled($cancelDate);
  641.             $em $managerRegistry->getManager();
  642.             $booking $participant->getOrderItem()->getCourseSubscriptionBooking();
  643.             if (!empty($booking)) {
  644.                 $terminationPeriod $booking->getCourseSubscription()->getTerminationPeriod();
  645.                 $cancelDate->modify('+' $terminationPeriod ' months');
  646.             }
  647.             $result $orderService->setCancelDateForParticipantInCourse(
  648.                 $this->getCurrentClient(),
  649.                 $participant,
  650.                 $cancelDate
  651.             );
  652.             $em->flush();
  653.             // Aktive Eintraege/Bestellpositionen/Bestellungen fuer Kurstermine nach dem Kuendigungsdatum erhalten
  654.             $oipsToCancel $orderService->getAllActiveParticipationsAfterCancelDateByParticipant(
  655.                 $this->getCurrentClient(),
  656.                 $participant
  657.             );
  658.             // Diese Eintraege einzeln durchlaufen und stornieren
  659.             foreach ($oipsToCancel as $oipToCancel) {
  660.                 // Bei schon vorhandenen Rechnungen ggf. Storno-Rechnungen erstellen
  661.                 foreach ($oipToCancel->getOrderItem()->getOrder()->getInvoices() as $invoice) {
  662.                     if (!$invoice->isCancelled() && !$invoice->isCancellation() && $invoice->containsOrderItem($oipToCancel->getOrderItem())) {
  663.                         $cancellation $orderService->createCancellation($invoice$oipToCancel->getOrderItem(), $oipToCancel->getId());
  664.                         $cancellation->setSignedBy($this->getCurrentUser());
  665.                         $em->persist($cancellation);
  666.                     }
  667.                 }
  668.                 // Eintrag stornieren
  669.                 $orderService->cancelOrderItemParticipant($oipToCancel->getOrderItem(), $oipToCancel->getId());
  670.                 // Ggf. Bestellposition stornieren
  671.                 if (!$oipToCancel->getOrderItem()->hasUncancelledParticipants()) {
  672.                     $oipToCancel->getOrderItem()->setStatus(OrderItem::STATUS_CANCELLED);
  673.                     foreach ($oipToCancel->getOrderItem()->getMaterialCosts() as $materialCost) {
  674.                         $materialCost->setStatus(OrderItem::STATUS_CANCELLED);
  675.                     }
  676.                 }
  677.                 // Ggf. Bestellung stornieren
  678.                 if (!$oipToCancel->getOrderItem()->getOrder()->hasUncancelledItems()) {
  679.                     $oipToCancel->getOrderItem()->getOrder()->setStatus(Order::STATUS_CANCELLED);
  680.                 }
  681.                 $orderService->calculateCancelOrderItem($oipToCancel->getOrderItem());
  682.             }
  683.             // Aenderungen in Datenbank speichern
  684.             $em->flush();
  685.             $flashExists false;
  686.             foreach ($requestStack->getSession()->all() as $flashType => $flashTitle) {
  687.                 if ($flashType == 'notice' && $flashTitle == 'Kündigungsdatum eingetragen'$flashExists true;
  688.             }
  689.             if (!$flashExists$this->addFlash('notice''Kündigungsdatum eingetragen');
  690.             $route $request->headers->get('referer');
  691.             return $this->redirect($route);
  692.         }
  693.         return $this->render('course/_set-cancel-date.html.twig', [
  694.             'person' => $participant->getPerson(),
  695.             'form' => $form->createView(),
  696.             'cancelDate' => $participant->getCancelled(),
  697.             'today' => new \DateTime()
  698.         ]);
  699.     }
  700.     /**
  701.      * @Route("/{id}/cancel-item/{participantId}/{return}", name="order-item_cancel", methods="GET")
  702.      */
  703.     public function cancelItem(
  704.         Request $request,
  705.         OrderItem $orderItem,
  706.         int $participantId 0,
  707.         string $return '',
  708.         ConfigurationService $configService,
  709.         OrderService $orderService
  710.     ): Response {
  711.         $order $orderItem->getOrder();
  712.         $this->denyAccessUnlessGranted('ROLE_MANAGER'$order);
  713.         $em $this->getDoctrine()->getManager();
  714.         foreach ($order->getInvoices() as $invoice) {
  715.             if (!$invoice->isCancelled() && !$invoice->isCancellation() && $invoice->containsOrderItem($orderItem)) {
  716.                 $cancellation $orderService->createCancellation($invoice$orderItem$participantId);
  717.                 $cancellation->setSignedBy($this->getCurrentUser());
  718.                 $em->persist($cancellation);
  719.             }
  720.         }
  721.         if ($participantId 0) {
  722.             $orderService->cancelOrderItemParticipant($orderItem$participantId);
  723.         } else {
  724.             $orderItem->cancelAllParticipants();
  725.         }
  726.         if (!$orderItem->hasUncancelledParticipants()) {
  727.             $orderItem->setStatus(OrderItem::STATUS_CANCELLED);
  728.             foreach ($orderItem->getMaterialCosts() as $materialCost) {
  729.                 $materialCost->setStatus(OrderItem::STATUS_CANCELLED);
  730.             }
  731.         }
  732.         if (!$order->hasUncancelledItems()) {
  733.             $order->setStatus(Order::STATUS_CANCELLED);
  734.         }
  735.         $orderService->calculateCancelOrderItem($orderItem);
  736.         $orderItem->setModified(new \DateTime());
  737.         $order->setModified(new \DateTime());
  738.         $em->flush();
  739.         $this->addFlash('notice''Kurs storniert');
  740.         // return $this->redirect(urldecode($return));
  741.         return $this->redirectToRoute('course_invoices', ['id' => $request->get('course_id')]);
  742.     }
  743.     /**
  744.      * @Route("/copy-participant/{id}", name="participant_copy-to-other-occurrence")
  745.      */
  746.     public function copyParticipantToOtherOccurrence(
  747.         Request $request,
  748.         OrderItemPerson $participant,
  749.         OrderService $orderService,
  750.         CourseOccurrenceRepository $coRepo,
  751.         RequestStack $requestStack
  752.     ): Response {
  753.         $this->denyAccessUnlessGranted('ROLE_MANAGER'$participant->getOrderItem()->getOrder());
  754.         $selectableOccurrences $orderService->getAllOccurrencesOfCourseAParticipantIsNotInBeforeCancelDate($this->getCurrentClient(), $participant);
  755.         $selectableOccurrencesArray = [];
  756.         foreach ($selectableOccurrences as $selectableOccurrence) {
  757.             $selectableOccurrencesArray[$selectableOccurrence->getStart()->format('d.m.Y') . ' - ' $selectableOccurrence->getEnd()->format('d.m.Y')] = $selectableOccurrence->getId();
  758.         }
  759.         $form $this->createForm(OrderItemPersonCopy::class, null, [
  760.             'occurrences' => $selectableOccurrencesArray,
  761.             'action' => $this->generateUrl('participant_copy-to-other-occurrence', ['id' => $participant->getId()])
  762.         ]);
  763.         $form->handleRequest($request);
  764.         if ($form->isSubmitted() && $form->isValid()) {
  765.             $em $this->getDoctrine()->getManager();
  766.             $flashs = [];
  767.             $orders = [];
  768.             foreach ($form->getData()['occurrences'] as $occurrenceId) {
  769.                 $flash = [];
  770.                 $occurrence $coRepo->find($occurrenceId);
  771.                 $newOrder $orderService->generateOrderForCourseOccurrenceFromOrderItemPerson(
  772.                     $this->getCurrentClient(),
  773.                     $participant,
  774.                     $occurrence,
  775.                     $flash,
  776.                     false
  777.                 );
  778.                 if ($newOrder !== null) {
  779.                     $orders[] = $newOrder;
  780.                 }
  781.                 if (count($flash) > 0) {
  782.                     $flashs[] = $flash;
  783.                 }
  784.             }
  785.             foreach ($orders as $orderToSave) {
  786.                 $em->persist($orderToSave);
  787.             }
  788.             foreach ($flashs as $flashToShow) {
  789.                 foreach ($flashToShow as $key => $value) {
  790.                     $this->addFlash($key$value);
  791.                 }
  792.             }
  793.             // Aenderungen in Datenbank speichern
  794.             $em->flush();
  795.             $flashExists false;
  796.             foreach ($requestStack->getSession()->all() as $flashType => $flashTitle) {
  797.                 if ($flashType == 'notice' && $flashTitle == 'Teilnehmer in ' count($orders) . ' weitere Termine übernommen'$flashExists true;
  798.             }
  799.             if (!$flashExists$this->addFlash('notice''Teilnehmer in ' count($orders) . ' weitere Termine übernommen');
  800.             return $this->redirectToRoute('course_participants', ['id' => $participant->getOrderItem()->getCourseOccurrence()->getCourse()->getId()]);
  801.         }
  802.         return $this->render('course/_copy-to-occurrence.html.twig', [
  803.             'person' => $participant->getPerson(),
  804.             'form' => $form->createView(),
  805.         ]);
  806.     }
  807.     /**
  808.      * @Route("/{id}/create-invoice", name="order_invoice_create", methods="GET")
  809.      */
  810.     public function createInvoice(
  811.         Request $request,
  812.         Order $order,
  813.         InvoiceService $invoiceService
  814.     ): Response {
  815.         $results $invoiceService->createInvoiceFromOrder($order);
  816.         $em $this->getDoctrine()->getManager();
  817.         //Update the order status
  818.         $newOrderState $order->setStatus(Order::STATUS_PROCESSING);
  819.         $em->persist($newOrderState);
  820.         foreach ($results['attendees'] as $attendee) {
  821.             $em->persist($attendee);
  822.         }
  823.         $em->persist($results['invoice']);
  824.         $em->flush();
  825.         $this->addFlash('notice'' Rechnung erstellt');
  826.         return $this->redirectToRoute('order_show', ['id' => $order->getId()]);
  827.     }
  828.     /**
  829.      * @Route("/{id}", name="order_delete", methods="DELETE")
  830.      */
  831.     public function delete(Request $requestOrder $order): Response
  832.     {
  833.         if ($this->isCsrfTokenValid('delete' $order->getId(), $request->request->get('_token'))) {
  834.             $em $this->getDoctrine()->getManager();
  835.             $em->remove($order);
  836.             $em->flush();
  837.         }
  838.         return $this->redirectToRoute('order_index');
  839.     }
  840.     protected function updateParticipantsOfOrder(Order $order)
  841.     {
  842.         if (count($order->getOrderItems()) > 0) {
  843.             foreach ($order->getOrderItems() as $orderItem) {
  844.                 if (count($orderItem->getParticipants()) > 0) {
  845.                     foreach ($orderItem->getParticipants() as $participant) {
  846.                         $participant->updateFieldsFromPerson();
  847.                     }
  848.                 }
  849.             }
  850.         }
  851.     }
  852.     private function createInvoiceRecipientValues($persons$customer)
  853.     {
  854.         $res[] = $customer;
  855.         foreach ($persons as $person) {
  856.             $res[] = $person;
  857.         }
  858.         return $res;
  859.     }
  860.     /**
  861.      * isInvoiceWithCancillation
  862.      *
  863.      * Checks whether one of the invoices is a cancellation invoice
  864.      *
  865.      * @param  Collection $invoices
  866.      * @return boolean
  867.      */
  868.     private function isInvoiceWithCancillation(Collection $invoices)
  869.     {
  870.         $cancelation false;
  871.         if (empty($invoices)) return $cancelation;
  872.         $counter count($invoices);
  873.         if ($counter || !($invoices[$counter 1]->isCancellation())) return $cancelation;
  874.         foreach ($invoices as $invoice) {
  875.             if ($invoice->isCancellation()) {
  876.                 $cancelation true;
  877.                 break;
  878.             }
  879.         }
  880.         return $cancelation;
  881.     }
  882.     /**
  883.      * @Route("/changestatus/{id}/{status}", name="change_status")
  884.      */
  885.     public function changeStatus(Order $order$status): Response
  886.     {
  887.         $em $this->getDoctrine()->getManager();
  888.         $newstatus $order->setStatus($status);
  889.         $em->persist($newstatus);
  890.         $em->flush();
  891.         return $this->json([
  892.             'success' => 'Der Status wurde geändert.'
  893.         ]);
  894.     }
  895.     /**
  896.      * @Route("/sendordermail/{id}", name="send_order_mail")
  897.      */
  898.      public function sendordermail(Order $orderPersonRepository $personRepoEmailHistoryService $emailHistoryServiceMailerService $mailerServiceConnection $connection): Response
  899.     {
  900.         $orderItems $order->getOrderItems() ? $order->getOrderItems()->toArray() : [];
  901. $waitItems $order->getWaitItems() ? $order->getWaitItems()->toArray() : [];
  902. $allItems array_merge($orderItems$waitItems);
  903.         foreach ($allItems as $item) {
  904.             /////////////////////////////////// FIELDS Start //////////////////////////////////////
  905.             // Fetch course fields
  906.             $sql 'SELECT
  907.             f.*,
  908.             d.value_text,
  909.             d.value_integer
  910.         FROM
  911.             course_field f
  912.         LEFT JOIN
  913.             course_data d
  914.             ON 
  915.             d.field_id = f.id AND
  916.             d.course_id = :courseId
  917.         WHERE f.certificate = 0';
  918.             $stmt $connection->prepare($sql);
  919.             $stmt->bindValue(
  920.                 'courseId',
  921.                 $item->getCourseOccurrence()->getCourse()->getId()
  922.             );
  923.             $stmt->executeQuery();
  924.             $result $stmt->fetchAll();
  925.             $fields = [];
  926.             foreach ($result as $index => $field) {
  927.                 if (!empty($field['category'])) {
  928.                     if (!$item->getCourseOccurrence()->getCourse()->getCategory()) {
  929.                         continue;
  930.                     }
  931.                     if (!in_array($item->getCourseOccurrence()->getCourse()->getCategory()->getId(), json_decode($field['category'], true))) {
  932.                         continue;
  933.                     }
  934.                 }
  935.                 if (!empty($field['course_type'])) {
  936.                     if (!$item->getCourseOccurrence()->getCourse()->getType()) {
  937.                         continue;
  938.                     }
  939.                     if (!in_array($item->getCourseOccurrence()->getCourse()->getType()->getId(), json_decode($field['course_type'], true))) {
  940.                         continue;
  941.                     }
  942.                 }
  943.                 $fields[] = [
  944.                     'id' => $field['id'],
  945.                     'name' => $field['name'],
  946.                     'value' => !empty($field['value_integer']) ? $field['value_integer'] : $field['value_text'],
  947.                 ];
  948.             }
  949.             $order->setFields($fields);
  950.             $sentMessage $mailerService->sendCheckoutConfirmMessage($order);
  951.             $customer $order->getCustomer();
  952.             $emailHistoryService->saveProtocolEntryFromOrder(
  953.                 $order,
  954.                 $this->getCurrentClient(),
  955.                 $customer,
  956.                 'versandt',
  957.                 $sentMessage['subject'],
  958.                 $sentMessage['message'],
  959.                 'Bestellbestätigung gesendet',
  960.                 $sentMessage['email']
  961.             );
  962.             $message "Bestellbestätigung ist versendet" ;
  963.             $this->addFlash('notice'$message);
  964.             return $this->redirectToRoute('order_index');
  965.         }
  966.         // Ensure a return value if there are no order items
  967.         $this->addFlash('error''Keine Bestellpositionen gefunden.');
  968.         return $this->redirectToRoute('order_index');
  969.     }
  970. }