src/Controller/OrderController.php line 186

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