src/Controller/CashBox/CartController.php line 147

Open in your IDE?
  1. <?php
  2. namespace App\Controller\CashBox;
  3. use App\Entity\Cart;
  4. use App\Entity\CartHistory;
  5. use App\Entity\CartLog;
  6. use App\Entity\CartProduct;
  7. use App\Entity\CartProductToCart;
  8. use App\Entity\Cashbox;
  9. use App\Entity\Customer;
  10. use App\Entity\CustomerAddress;
  11. use App\Entity\CustomerGroup;
  12. use App\Entity\DevLog;
  13. use App\Entity\Discount;
  14. use App\Entity\Employee;
  15. use App\Entity\EmployeeGroup;
  16. use App\Entity\FiskalyTransaction;
  17. use App\Entity\Location;
  18. use App\Entity\PaymentMethod;
  19. use App\Entity\Price;
  20. use App\Entity\PriceGroup;
  21. use App\Entity\Product;
  22. use App\Entity\Receipt;
  23. use App\Entity\ReceiptCashbox;
  24. use App\Entity\ReceiptCustomer;
  25. use App\Entity\ReceiptCustomerAddress;
  26. use App\Entity\ReceiptCustomerGroup;
  27. use App\Entity\ReceiptDiscount;
  28. use App\Entity\ReceiptDocument;
  29. use App\Entity\ReceiptDocumentCustomer;
  30. use App\Entity\ReceiptDocumentCustomerAddress;
  31. use App\Entity\ReceiptDocumentPosition;
  32. use App\Entity\ReceiptEmployee;
  33. use App\Entity\ReceiptEmployeeGroup;
  34. use App\Entity\ReceiptLocation;
  35. use App\Entity\ReceiptPaymentMethod;
  36. use App\Entity\ReceiptPrice;
  37. use App\Entity\ReceiptPriceGroup;
  38. use App\Entity\ReceiptProduct;
  39. use App\Entity\ReceiptCartProduct;
  40. use App\Entity\ReceiptScalePrice;
  41. use App\Entity\ReceiptTax;
  42. use App\Entity\ReceiptTransaction;
  43. use App\Entity\ReceiptUnit;
  44. use App\Entity\ReceiptUser;
  45. use App\Entity\ScalePrice;
  46. use App\Entity\Tax;
  47. use App\Entity\Transaction;
  48. use App\Entity\Unit;
  49. use App\Repository\CartProductRepository;
  50. use App\Repository\CartProductToCartRepository;
  51. use App\Repository\CartRepository;
  52. use App\Repository\CashboxRepository;
  53. use App\Repository\ConfigurationRepository;
  54. use App\Repository\CustomerAddressRepository;
  55. use App\Repository\CustomerRepository;
  56. use App\Repository\FiskalyTransactionRepository;
  57. use App\Repository\LocationRepository;
  58. use App\Repository\ReceiptCustomerAddressRepository;
  59. use App\Repository\ReceiptCustomerGroupRepository;
  60. use App\Repository\ReceiptCustomerRepository;
  61. use App\Repository\ReceiptDiscountRepository;
  62. use App\Repository\ReceiptEmployeeGroupRepository;
  63. use App\Repository\ReceiptEmployeeRepository;
  64. use App\Repository\ReceiptLocationRepository;
  65. use App\Repository\ReceiptPriceGroupRepository;
  66. use App\Repository\ReceiptPriceRepository;
  67. use App\Repository\ReceiptProductRepository;
  68. use App\Repository\ReceiptCartProductRepository;
  69. use App\Repository\ReceiptRepository;
  70. use App\Repository\ReceiptScalePriceRepository;
  71. use App\Repository\ReceiptTaxRepository;
  72. use App\Repository\ReceiptUnitRepository;
  73. use App\Repository\ReceiptUserRepository;
  74. use App\Repository\UserRepository;
  75. use App\Service\CashBox\CartActionService;
  76. use App\Service\CashBox\CashboxService;
  77. use App\Service\CashBox\ProductService;
  78. use App\Service\Fiskaly\KassenSichVApiService;
  79. use Doctrine\ORM\EntityManagerInterface;
  80. use Endroid\QrCode\Builder\BuilderInterface;
  81. use Endroid\QrCode\Writer\SvgWriter;
  82. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  83. use Symfony\Component\HttpFoundation\Response;
  84. use Symfony\Component\HttpFoundation\JsonResponse;
  85. use Symfony\Component\HttpFoundation\Request;
  86. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  87. use Symfony\Component\Routing\Annotation\Route;
  88. use Symfony\Component\Security\Core\User\UserInterface;
  89. use Symfony\Component\Serializer\SerializerInterface;
  90. use App\Serializer\Normalizer\ReactCartNormalizer;
  91. use App\Service\CashBox\PriceService;
  92. use function is_array;
  93. /**
  94.  * @Route("/cart")
  95.  */
  96. class CartController extends AbstractController
  97. {
  98.     /**
  99.      * @var SessionInterface
  100.      */
  101.     private SessionInterface $session;
  102.     private PriceService $priceService;
  103.     /**
  104.      * CartController constructor.
  105.      * @param SessionInterface $session
  106.      */
  107.     public function __construct(SessionInterface $session)
  108.     {
  109.         $this->session $session;
  110.         $this->priceService = new PriceService();
  111.     }
  112.     /**
  113.      * @Route("/", name="cart_index")
  114.      * @return Response
  115.      */
  116.     public function index(): Response
  117.     {
  118.         return new Response('');
  119.     }
  120.     /**
  121.      * @Route("/create", name="cart_create", methods={"POST"})
  122.      * @param EntityManagerInterface $entity_manager
  123.      * @param LocationRepository $location_repository
  124.      * @param CashboxRepository $cashbox_repository
  125.      * @return JsonResponse
  126.      */
  127.     public function createCart(Request $requestEntityManagerInterface $entity_managerLocationRepository $location_repositoryCashboxRepository $cashbox_repositoryCustomerAddressRepository $customer_address_repository): JsonResponse
  128.     {
  129.         $customer_address null;
  130.         $customer null;
  131.         $request_data json_decode($request->getContent(), true);
  132.         if (isset($request_data['customer'], $request_data['customer']['cId']) && !empty($request_data['customer']) && !empty($request_data['customer']['cId'])) {
  133.             $customer_address $customer_address_repository->findOneBy(['id' => $request_data['customer']['cId']]);
  134.             if ($customer_address !== null) {
  135.                 $customer $customer_address->getCustomer();
  136.             }
  137.         }
  138.         $response = ['id' => null'_success' => false'_error' => 'Please choose a cashbox!'];
  139.         if ($this->session->has('cashbox')) {
  140.             /**
  141.              * @var Cashbox $cashbox
  142.              */
  143.             $cashbox $this->session->get('cashbox');
  144.             $location null;
  145.             $location_ $cashbox->getLocation();
  146.             if ($location_ !== null) {
  147.                 $location $location_repository->findOneBy(['id' => $location_->getId()]);
  148.             }
  149.             $entity_manager->createQueryBuilder()
  150.                 ->update('App:Cart''c')
  151.                 ->set('c.status'0)
  152.                 ->getQuery()
  153.                 ->execute();
  154.             try {
  155.                 $cart = new Cart();
  156.                 $cart->setCreateDate(new \DateTime('now'))
  157.                     ->setLocation($location)
  158.                     ->setEmployee($this->getUser()->getEmployees())
  159.                     ->setCashbox($cashbox_repository->findOneBy(['id' => $cashbox->getId()]))
  160.                     ->setParked(false)
  161.                     ->setFinished(false)
  162.                     ->setStatus('open')
  163.                     ->setSaved(false)
  164.                     ->setClosed(false);
  165.                 if ($customer !== null) {
  166.                     $cart->setCustomer($customer);
  167.                 }
  168.                 if ($customer_address !== null) {
  169.                     $cart->setCustomerAddress($customer_address);
  170.                 }
  171.                 $entity_manager->persist($cart);
  172.                 $entity_manager->flush();
  173.                 $response = ['id' => $cart->getId(), '_success' => true'_error' => null];
  174.             } catch (\Exception $exception) {
  175.                 // TODO: Error Handling
  176. //                dump($exception->getMessage());
  177.                 $response = ['id' => null'_success' => false'_error' => $exception->getMessage()];
  178.             }
  179.         }
  180.         return new JsonResponse($response);
  181.     }
  182.     /**
  183.      * @Route("/update", name="cart_update", methods={"POST"})
  184.      * @param Request $request
  185.      * @param CartActionService $cart_action_service
  186.      * @param EntityManagerInterface $entity_manager
  187.      * @return Response
  188.      * @throws \JsonException
  189.      */
  190.     public function updateCart(Request $requestCartActionService $cart_action_serviceEntityManagerInterface $entity_managerCartProductRepository $cart_product_repositoryCartProductToCartRepository $cart_product_to_cart_repository): Response
  191.     {
  192.         $dev_log = new DevLog();
  193.         $dev_log->setAction('LOG')
  194.             ->setType(__CLASS__)
  195.             ->setFile(__FILE__)
  196.             ->setLine(__LINE__)
  197.             ->setInfo(__METHOD__)
  198.             ->setData(json_decode(($request->getContent() && !empty($request->getContent())) ? $request->getContent() : [], true512JSON_THROW_ON_ERROR))
  199.             ->setMessage(__METHOD__)
  200.             ->setAddDate(new \DateTime('now'));
  201.         $entity_manager->persist($dev_log);
  202.         $entity_manager->flush();
  203.         $cart_action_service->setCartActionData($request->getContent());
  204.         $cart_action $cart_action_service->getCartAction();
  205.         /**
  206.          * @var Cart $persisted_cart
  207.          */
  208.         $persisted_cart $cart_action_service->getPersistedCart();
  209. //        dump($cartActionService->getCartActionData());
  210.         switch ($cart_action) {
  211.             case 'add':
  212.                 $this->addToCart($request$cart_action_service$entity_manager$cart_product_repository$cart_product_to_cart_repository);
  213.                 break;
  214.             case 'amount':
  215.                 $this->updateAmount($request$cart_action_service$entity_manager$cart_product_repository$cart_product_to_cart_repository);
  216.                 break;
  217.             case 'remove':
  218.                 $this->removeFromCart($request$cart_action_service$entity_manager$cart_product_to_cart_repository);
  219.                 break;
  220.         }
  221.         if ($persisted_cart) {
  222.             $cart $cart_action_service->getCart();
  223.             $cart_history = new CartHistory();
  224.             $cart_history->setCart($persisted_cart)
  225.                 ->setCreateDate(new \DateTime('now'))
  226.                 ->setCartData($cart);
  227.             $entity_manager->persist($cart_history);
  228.             $entity_manager->flush();
  229.             $persisted_cart
  230.                 ->setTotal($cart['total'])
  231.                 ->setTotalFixed($cart['total_fixed'])
  232.                 ->setTotalOtax($cart['total_otax'])
  233.                 ->setTotalOtaxFixed($cart['total_otax_fixed'])
  234.                 ->setTotalTax($cart['total_tax'])
  235.                 ->setTotalTaxFixed($cart['total_tax_fixed']);
  236.             $entity_manager->persist($persisted_cart);
  237.             $entity_manager->flush();
  238.             $cart_product_ null;
  239.             if ($cart_action_service->getPersistedCartProduct($cart_action_service->getCartProductHandle())) {
  240.                 $cart_product_ $cart_action_service->getPersistedCartProduct($cart_action_service->getCartProductHandle());
  241.             }
  242.             $cart_log = new CartLog();
  243.             $cart_log->setCreateDate(new \DateTime('now'))
  244.                 ->setCart($persisted_cart)
  245.                 ->setAmount((int)$cart_action_service->getAmount()['value'])
  246.                 ->setCartProduct($cart_product_)
  247.                 ->setCartAction($cart_action_service->getCartAction())
  248.                 ->setTotal($cart['total'])
  249.                 ->setTotalFixed($cart['total_fixed'])
  250.                 ->setTotalOtax($cart['total_otax'])
  251.                 ->setTotalOtaxFixed($cart['total_otax_fixed'])
  252.                 ->setTotalTax($cart['total_tax'])
  253.                 ->setTotalTaxFixed($cart['total_tax_fixed']);
  254.             $entity_manager->persist($cart_log);
  255.             $entity_manager->flush();
  256.         }
  257. //        dump($request->getContent());
  258. //        dump(json_decode($request->getContent(), true));
  259. //        dump(json_decode($request->getContent()));
  260.         return new Response('');
  261.     }
  262.     /**
  263.      * @Route("/add", name="cart_add", methods={"POST"})
  264.      * @param Request $request
  265.      * @param CartActionService $cart_action_service
  266.      * @param EntityManagerInterface $entity_manager
  267.      */
  268.     public function addToCart(Request $requestCartActionService $cart_action_serviceEntityManagerInterface $entity_managerCartProductRepository $cart_product_repositoryCartProductToCartRepository $cart_product_to_cart_repository): void
  269.     {
  270.         $cart_action_service->setCartActionData($request->getContent());
  271.         /* Daten prüfen */
  272.         /**
  273.          * @var Cart $persisted_cart
  274.          */
  275.         $persisted_cart $cart_action_service->getPersistedCart();
  276.         $handle_product $cart_action_service->getHandleProduct();
  277.         $action_data $cart_action_service->getCartActionData();
  278.         $cart $cart_action_service->getCart();
  279.         $connections = [];
  280.         if (isset($handle_product['connections']) && is_array($handle_product['connections']) && !empty($handle_product['connections'])) {
  281.             $connections $handle_product['connections'];
  282.         }
  283.         // Alle notwendigen Daten vorhanden?
  284.         if ($persisted_cart && $handle_product) {
  285.             // Schauen ob cartProduct schon existiert
  286.             /**
  287.              * @var CartProduct $persisted_cart_product
  288.              */
  289.             $persisted_cart_product $cart_action_service->getPersistedCartProduct($cart_action_service->getCartProductHandle());
  290.             if ($persisted_cart_product) {
  291.                 // CartProduct muss aktualisiert werden
  292.                 $this->updateCartProduct($persisted_cart_product$cart$cart_action_service->getCartProductAmountInCart($action_data['cart_product_handle']), $action_data['cart_product_handle'], $persisted_cart$cart_product_to_cart_repository$entity_manager);
  293.                 // Connections checken
  294.                 $persisted_connections $persisted_cart_product->getConnectedCartProducts();
  295.                 // Gibt es schon Connections?
  296.                 if (!$persisted_connections->isEmpty()) {
  297.                     // Gucken ob die aus dem Frontend-Cart so mitgekommen sind?
  298.                     foreach ($persisted_connections as $persisted_connection) {
  299.                         if (!isset($connections[$persisted_connection->getCartProductHandle()])) {
  300.                             // Noch woanders hin connected?
  301.                             $more_connections $persisted_connection->getCartProducts();
  302.                             // Diese Prüfung reicht völlig aus.
  303.                             if ($more_connections->count() === 1) {
  304.                                 // Wenn Connection nicht noch woanders connected ist, dann weg mit der Zuordnung von CartProductToCart.
  305.                                 $connection_cart_product_to_cart $cart_product_to_cart_repository->findOneBy(['cart' => $persisted_cart->getId(), 'cartProduct' => $persisted_connection->getId()]);
  306.                                 if ($connection_cart_product_to_cart) {
  307.                                     $entity_manager->remove($connection_cart_product_to_cart);
  308.                                 }
  309.                             } else {
  310.                                 // Connection Löschen, da im Frontend-Cart nicht mehr vorhanden
  311.                                 $persisted_cart_product->removeConnectedCartProduct($persisted_connection);
  312.                             }
  313.                         }
  314.                     }
  315.                 }
  316.                 // gibt_es_neue_connections? wenn_nicht, aktualisieren.
  317.                 foreach ($connections as $connection) {
  318.                     $persisted_cart_product_c $cart_product_repository->findOneBy(['cart_product_handle' => $connection]);
  319.                     if ($persisted_cart_product_c) {
  320.                         // Aktualisiere CartProduct_C
  321.                         $persisted_cart_product->addConnectedCartProduct($persisted_cart_product_c);
  322.                         $this->updateCartProduct($persisted_cart_product_c$cart$cart_action_service->getCartProductAmountInCart($connection), $connection$persisted_cart$cart_product_to_cart_repository$entity_manager);
  323.                     } else {
  324.                         // Erstelle CartProduct_C
  325.                         /**
  326.                          * @var Product $product
  327.                          */
  328.                         $connection_product $cart_action_service->getCartProductFromCart($connection);
  329.                         if ($connection_product !== false) {
  330.                             $product_ $cart_action_service->getProductFromConnectionProduct($connection_product);
  331.                             if ($product_) {
  332.                                 $connected_cart_product $this->createCartProduct($product_$persisted_cart$cart$cart_action_service->getCartProductAmountInCart($connection), $connectionnullnullfalsefalse$entity_manager);
  333.                                 $persisted_cart_product->addConnectedCartProduct($connected_cart_product);
  334.                             }
  335.                         }
  336.                     }
  337.                 }
  338.             } else {
  339.                 /**
  340.                  * addCartLog
  341.                  */
  342.                 // Erstelle cartProduct
  343.                 /**
  344.                  * @var Product $product
  345.                  */
  346.                 $product $cart_action_service->getProductFromHandleProduct();
  347.                 if ($product) {
  348.                     $use_component false;
  349.                     $deposit_refund false;
  350.                     if (isset($handle_product['useComponent'])) {
  351.                         $use_component $handle_product['useComponent'];
  352.                     }
  353.                     if (isset($handle_product['depositRefund'])) {
  354.                         $deposit_refund $handle_product['depositRefund'];
  355.                     }
  356.                     $cart_product $this->createCartProduct($product$persisted_cart$cart$cart_action_service->getCartProductAmountInCart($action_data['cart_product_handle']), $action_data['cart_product_handle'], $action_data['discount']['value'], $action_data['discount']['type'], $use_component$deposit_refund$entity_manager);
  357.                     // Connections
  358.                     if (isset($handle_product['connections']) && is_array($handle_product['connections']) && !empty($handle_product['connections'])) {
  359.                         foreach ($handle_product['connections'] as $connection) {
  360.                             $connection_product $cart_action_service->getCartProductFromCart($connection);
  361.                             if ($connection_product !== false) {
  362.                                 $product_ $cart_action_service->getProductFromConnectionProduct($connection_product);
  363.                                 if ($product_) {
  364.                                     $connected_cart_product $this->createCartProduct($product_$persisted_cart$cart$cart_action_service->getCartProductAmountInCart($connection), $connectionnullnullfalsefalse$entity_manager);
  365.                                     $cart_product->addConnectedCartProduct($connected_cart_product);
  366.                                 }
  367.                             }
  368.                         }
  369.                     }
  370.                 }
  371.             }
  372.         } else {
  373.             // TODO: Fehlerbehandlung
  374.         }
  375.     }
  376.     /**
  377.      * @Route("/amount", name="cart_update_amount", methods={"POST"})
  378.      * @param Request $request
  379.      * @param CartActionService $cartActionService
  380.      * @param EntityManagerInterface $entityManager
  381.      */
  382.     public function updateAmount(Request $requestCartActionService $cartActionServiceEntityManagerInterface $entityManagerCartProductRepository $cartProductRepositoryCartProductToCartRepository $cartProductToCartRepository)
  383.     {
  384.         $cartActionService->setCartActionData($request->getContent());
  385.         /* Daten prüfen */
  386.         /**
  387.          * @var Cart $persistedCart
  388.          */
  389.         $persistedCart $cartActionService->getPersistedCart();
  390.         $actionData $cartActionService->getCartActionData();
  391.         $cart $cartActionService->getCart();
  392.         if ($persistedCart) {
  393.             // Schauen ob cartProduct schon existiert
  394.             /**
  395.              * @var CartProduct $persistedCartProduct
  396.              */
  397.             $persistedCartProduct $cartActionService->getPersistedCartProduct($cartActionService->getCartProductHandle());
  398. //            dump($cartActionService->getCartProductHandle());
  399. //            dump($persistedCartProduct);
  400.             if ($persistedCartProduct) {
  401.                 $this->updateCartProduct($persistedCartProduct$cart$cartActionService->getCartProductAmountInCart($persistedCartProduct->getCartProductHandle()), $persistedCartProduct->getCartProductHandle(), $persistedCart$cartProductToCartRepository$entityManager);
  402.                 // Connections checken
  403.                 $persistedConnections $persistedCartProduct->getConnectedCartProducts();
  404.                 // Gibt es schon Connections?
  405.                 if (!$persistedConnections->isEmpty()) {
  406.                     // Gucken ob die aus dem Frontend-Cart so mitgekommen sind?
  407.                     foreach ($persistedConnections as $persistedConnection) {
  408.                         $this->updateCartProduct($persistedConnection$cart$cartActionService->getCartProductAmountInCart($actionData['cart_product_handle']), $persistedConnection->getCartProductHandle(), $persistedCart$cartProductToCartRepository$entityManager);
  409.                         /*
  410.                             if (!isset($connections[$persistedConnection->getCartProductHandle()])) {
  411.                                 // Noch woanders hin connected?
  412.                                 $cc = $persistedConnection->getCartProducts();
  413.                                 // Diese Prüfung reicht völlig aus.
  414.                                 if ($cc->count() === 1) {
  415.                                     // Wenn Connection nicht noch woanders connected ist, dann weg mit der Zuordnung von CartProductToCart.
  416.                                     $connectionCartProductToCart = $cartProductToCartRepository->findOneBy(['cart' => $persistedCart->getId(), 'cartProduct' => $persistedConnection->getId()]);
  417.                                     if ($connectionCartProductToCart) {
  418.                                         $entityManager->remove($connectionCartProductToCart);
  419.                                     }
  420.                                 } else {
  421.                                     // Connection Löschen, da im Frontend-Cart nicht mehr vorhanden
  422.                                     $persistedCartProduct->removeConnectedCartProduct($persistedConnection);
  423.                                 }
  424.                             }*/
  425.                     }
  426.                 }
  427.             }
  428.         }
  429.     }
  430.     /**
  431.      * @Route("/remove", name="cart_remove", methods={"POST"})
  432.      * @param Request $request
  433.      * @param CartActionService $cartActionService
  434.      * @param EntityManagerInterface $entityManager
  435.      */
  436.     public function removeFromCart(Request $requestCartActionService $cartActionServiceEntityManagerInterface $entityManagerCartProductToCartRepository $cartProductToCartRepository)
  437.     {
  438.         $cartActionService->setCartActionData($request->getContent());
  439.         /* Daten prüfen */
  440.         /**
  441.          * @var Cart $persistedCart
  442.          */
  443.         $persistedCart $cartActionService->getPersistedCart();
  444.         if ($persistedCart) {
  445.             /**
  446.              * @var CartProduct $persistedCartProduct
  447.              */
  448.             $persistedCartProduct $cartActionService->getPersistedCartProduct($cartActionService->getCartProductHandle());
  449.             // Connections checken
  450.             $persistedConnections $persistedCartProduct->getConnectedCartProducts();
  451.             // Gibt es schon Connections?
  452.             if (!$persistedConnections->isEmpty()) {
  453.                 // Gucken ob die aus dem Frontend-Cart so mitgekommen sind?
  454.                 foreach ($persistedConnections as $persistedConnection) {
  455.                     if (!isset($connections[$persistedConnection->getCartProductHandle()])) {
  456.                         // Noch woanders hin connected?
  457.                         $cc $persistedConnection->getCartProducts();
  458.                         // Diese Prüfung reicht völlig aus.
  459.                         if ($cc->count() === 1) {
  460.                             // Wenn Connection nicht noch woanders connected ist, dann weg mit der Zuordnung von CartProductToCart.
  461.                             $connectionCartProductToCart $cartProductToCartRepository->findOneBy(['cart' => $persistedCart->getId(), 'cartProduct' => $persistedConnection->getId()]);
  462.                             if ($connectionCartProductToCart) {
  463.                                 $entityManager->remove($connectionCartProductToCart);
  464.                             }
  465.                         } else {
  466.                             // Connection Löschen, da im Frontend-Cart nicht mehr vorhanden
  467.                             $persistedCartProduct->removeConnectedCartProduct($persistedConnection);
  468.                         }
  469.                     }
  470.                 }
  471.             }
  472.             if ($persistedCartProduct) {
  473.                 $cartProductToCart $cartProductToCartRepository->findOneBy(['cart' => $persistedCart->getId(), 'cartProduct' => $persistedCartProduct->getId()]);
  474.                 if ($cartProductToCart) {
  475.                     $entityManager->remove($cartProductToCart);
  476.                 }
  477.             } else {
  478.                 /**
  479.                  * Bevor etwas entfernt werden kann, muss es hinzugefügt worden sein.
  480.                  * Ein CartProduct wird nie aus der Tabelle entfernt, lediglich die Beziehung zum Cart wird aufgehoben.
  481.                  * Wenn an dieser Stelle das CartProduct nicht existiert ist das ein Fehler.
  482.                  */
  483.                 // TODO: Fehlerbehandlung
  484.             }
  485.         } else {
  486.             // TODO: Fehlerbehandlung
  487.         }
  488.     }
  489.     /**
  490.      * @Route("/load_last", name="cart_load_last", methods={"GET"})
  491.      * @param CashboxService $cashboxService
  492.      * @param SerializerInterface $serializer
  493.      * @return JsonResponse
  494.      */
  495.     public function loadLastCart(CashboxService $cashboxService): JsonResponse
  496.     {
  497.         if ($this->session->has('cashbox')) {
  498.             /**
  499.              * @var Cashbox $cashbox
  500.              */
  501.             $cashbox $this->session->get('cashbox');
  502.             if ($cashboxService->hasLastCart($cashbox)) {
  503.                 $cart $cashboxService->getLastCart($cashbox);
  504.                 if ($cart) {
  505.                     return $this->json(['_success' => true'cartId' => $cart->getId()]);
  506.                 }
  507.             }
  508.         }
  509.         return $this->json(['_success' => false]);
  510.     }
  511.     /**
  512.      * @Route("/load/{id}", name="cart_load", methods={"GET"})
  513.      * @param Cart $cart
  514.      */
  515.     public function loadCart(Cart $cartProductService $productServiceEntityManagerInterface $entity_managerCartRepository $cart_repository): JsonResponse
  516.     {
  517.         $cartProductToCarts $cart->getCartProductToCarts();
  518.         $cartProductContainer = [];
  519.         $toRemove = [];
  520.         $customer $cart->getCustomer();
  521.         $customer_address $cart->getCustomerAddress();
  522.         foreach ($cartProductToCarts as $cartProductToCart) {
  523.             $cartProduct $cartProductToCart->getCartProduct();
  524.             $product $cartProduct->getProduct();
  525.             $p['product'] = $productService->buildFrontendProductFromProduct($product$cartProduct$customer);
  526.             $p['product']['is_connected'] = false;
  527.             $p['product']['connections'] = [];
  528.             $p['amount'] = [
  529.                 'value' => $cartProductToCart->getAmount(),
  530.                 'locked' => $cartProductToCart->getAmountLocked(),
  531.             ];
  532.             $p['discount']['discount_type'] = $cartProduct->getDiscountType();
  533.             $p['discount']['discount'] = $cartProduct->getDiscountValue();
  534.             $p['cart_product_handle'] = $cartProduct->getCartProductHandle();
  535.             $p['deposit'] = [
  536.                 'deposit' => [],
  537.                 'hasDeposit' => false,
  538.                 'depositTotal' => 0
  539.             ];
  540.             $p['followup'] = [
  541.                 'followUpProductContainer' => [],
  542.             ];
  543.             $connectedCartProducts $cartProduct->getConnectedCartProducts();
  544.             if (!empty($connectedCartProducts)) {
  545.                 foreach ($connectedCartProducts as $connectedCartProduct) {
  546.                     $_product $connectedCartProduct->getProduct();
  547.                     $_d $productService->buildFrontendProductFromProduct($_product$cartProduct$customer);
  548.                     if ($_product !== null) {
  549.                         if ($_product->getDeposit() === true) {
  550.                             $p['deposit']['hasDeposit'] = true;
  551.                             $_d['is_connected'] = false;
  552.                             $_d['connections'] = [];
  553.                             $p['deposit']['deposit'][] = $_d;
  554.                             $p['deposit']['depositTotal'] = $p['deposit']['depositTotal'] + $_d['price'];
  555.                             if ($customer === null || $customer->getB2b() === null || $customer->getB2b() === false) {
  556.                                 $p['deposit']['depositTotal'] = $p['deposit']['depositTotal'] + $_d['price_otax'];
  557.                             }
  558.                         } else {
  559.                             $p['followup']['followUpProductContainer'][] = $_d;
  560.                         }
  561.                         $toRemove[$connectedCartProduct->getCartProductHandle()] = $connectedCartProduct->getCartProductHandle();
  562.                     }
  563.                 }
  564.             }
  565.             $cartProductContainer[$cartProduct->getCartProductHandle()] = $p;
  566.         }
  567.         foreach ($toRemove as $item) {
  568.             unset($cartProductContainer[$item]);
  569.         }
  570.         $cartProductContainer array_values($cartProductContainer);
  571.         $cartComment = ((null === $cart->getComment()) ? "" $cart->getComment());
  572.         $cartName = ((null === $cart->getName()) ? "" $cart->getName());
  573.         $query $entity_manager->createQueryBuilder()
  574.             ->update('App:Cart''c')
  575.             ->set('c.status'0)
  576.             ->getQuery()
  577.             ->execute();
  578.         $_query $entity_manager->createQueryBuilder()
  579.             ->update('App:Cart''c')
  580.             ->set('c.status'':status')
  581.             ->where('c.id=:cart_id')
  582.             ->setParameter('status''open')
  583.             ->setParameter('cart_id'$cart->getId())
  584.             ->getQuery()
  585.             ->execute();
  586.         return $this->json(['_success' => true'cartProductContainer' => $cartProductContainer'cartId' => $cart->getId(), 'cartComment' => $cartComment'cartName' => $cartName'customer' => (($customer !== null) ? $customer->getId() : null), 'customer_address' => (($customer_address !== null) ? $customer_address->getId() : null)]);
  587.     }
  588.     /**
  589.      * @Route("/get_comment/{id}", name="cart_get_comment", methods={"GET"})
  590.      * @param Cart $cart
  591.      */
  592.     public function getComment(Cart $cart)
  593.     {
  594.         return $this->json(['_success' => true'comment' => ((null === $cart->getComment()) ? "" $cart->getComment()), 'cartId' => $cart->getId()]);
  595.     }
  596.     /**
  597.      * @Route("/save/{id}", name="cart_save", methods={"POST"})
  598.      * @param Cart $cart
  599.      */
  600.     public function saveCart(Cart $cartstring $nameEntityManagerInterface $entity_manager)
  601.     {
  602.         $cart->setName($name)
  603.             ->setSaveDate(new \DateTime('now'))
  604.             ->setSaved(true);
  605.         $entity_manager->persist($cart);
  606.         $entity_manager->flush();
  607.         $entity_manager->createQueryBuilder()
  608.             ->update('App:Cart''c')
  609.             ->set('c.status'0)
  610.             ->getQuery()
  611.             ->execute();
  612.         return new JsonResponse(''200);
  613.     }
  614.     /**
  615.      * @Route("/save", name="cart_save_react", methods={"POST"})
  616.      * @param Request $request
  617.      * @param CartActionService $cart_action_service
  618.      * @param EntityManagerInterface $entity_manager
  619.      */
  620.     public function saveCartReact(Request $requestCartActionService $cart_action_serviceEntityManagerInterface $entity_manager): JsonResponse
  621.     {
  622.         $cart_action_service->setCartActionData($request->getContent());
  623.         $cart $cart_action_service->getPersistedCart();
  624.         $data $cart_action_service->getCartActionData();
  625.         if (null !== $cart) {
  626.             $cart->setName($data['name'])
  627.                 ->setSaveDate(new \DateTime('now'))
  628.                 ->setSaved(true);
  629.             $entity_manager->persist($cart);
  630.             $entity_manager->flush();
  631.             $entity_manager->createQueryBuilder()
  632.                 ->update('App:Cart''c')
  633.                 ->set('c.status'0)
  634.                 ->getQuery()
  635.                 ->execute();
  636.             return new JsonResponse('Erfolgreich gespeichert'200);
  637.         }
  638.         return new JsonResponse('Interner Fehler'500);
  639.     }
  640.     /**
  641.      * @Route("/add_comment", name="cart_add_comment", methods={"POST"})
  642.      * @param Request $request
  643.      * @param CartActionService $cartActionService
  644.      * @param EntityManagerInterface $entityManager
  645.      */
  646.     public function addComment(Request $requestCartActionService $cartActionServiceEntityManagerInterface $entityManager): JsonResponse
  647.     {
  648.         $cartActionService->setCartActionData($request->getContent());
  649.         $cart $cartActionService->getPersistedCart();
  650.         $data $cartActionService->getCartActionData();
  651.         if (null !== $cart) {
  652.             $cart->setComment($data['comment']);
  653.             $entityManager->persist($cart);
  654.             $entityManager->flush();
  655.             return new JsonResponse('Erfolgreich gespeichert'200);
  656.         }
  657.         return new JsonResponse('Interner Fehler'500);
  658.     }
  659.     /**
  660.      * @Route("/cart_list", name="cart_list", methods={"GET"})
  661.      * @return JsonResponse
  662.      */
  663.     public function cartList(CartRepository $cartRepository): JsonResponse
  664.     {
  665.         if ($this->session->has('cashbox')) {
  666.             /**
  667.              * @var Cashbox $cashbox
  668.              */
  669.             $cashbox $this->session->get('cashbox');
  670.             $_cartList $cartRepository->findBy(['saved' => true'location' => $cashbox->getLocation()]);
  671.             $cartList = [];
  672.             if ($_cartList) {
  673.                 foreach ($_cartList as $cart) {
  674.                     $cartList[] = [
  675.                         'id' => $cart->getId(),
  676.                         'name' => $cart->getName(),
  677.                         'save_date' => $cart->getSaveDate()->format("H:i:s"),
  678.                         'date' => $cart->getSaveDate()->format("d.m.Y"),
  679.                         'time' => $cart->getSaveDate()->format("H:i:s"),
  680.                         'y' => $cart->getSaveDate()->format("Y"),
  681.                         'm' => $cart->getSaveDate()->format("m"),
  682.                         'd' => $cart->getSaveDate()->format("d"),
  683.                         'h' => $cart->getSaveDate()->format("H"),
  684.                         'i' => $cart->getSaveDate()->format("i"),
  685.                         's' => $cart->getSaveDate()->format("s"),
  686.                     ];
  687.                 }
  688.                 return new JsonResponse($cartList200);
  689.             }
  690.         }
  691.         return new JsonResponse([], 200);
  692.     }
  693.     /**
  694.      * @Route("/finish/{id}", name="cart_finish", methods={"GET"})
  695.      * @param Cart $cart
  696.      */
  697.     public function finishCart(Cart $cartUserRepository $user_repositoryReceiptCustomerAddressRepository $receipt_customer_address_repositoryReceiptCustomerGroupRepository $customer_group_repositoryReceiptCustomerRepository $receipt_customer_repositoryReceiptDiscountRepository $receipt_discount_repositoryReceiptEmployeeGroupRepository $receipt_employee_group_repositoryReceiptEmployeeRepository $receipt_employee_repositoryReceiptLocationRepository $receipt_location_repositoryReceiptPriceGroupRepository $receipt_price_group_repositoryReceiptPriceRepository $receipt_price_repositoryReceiptProductRepository $receipt_product_repositoryReceiptCartProductRepository $receipt_cart_product_repositoryReceiptRepository $receipt_repositoryReceiptScalePriceRepository $receipt_scale_price_repositoryReceiptTaxRepository $receipt_tax_repositoryReceiptUnitRepository $receipt_unit_repositoryReceiptUserRepository $receipt_user_repositoryConfigurationRepository $configuration_repositoryCustomerRepository $customer_repositoryKassenSichVApiService $kassen_sichv_api_serviceFiskalyTransactionRepository $fiskaly_transaction_repositoryEntityManagerInterface $entity_managerBuilderInterface $builderSvgWriter $svgWriter): JsonResponse
  698.     {
  699.         $cart->setFinished(true)
  700.             ->setFinishedDate(new \DateTime('now'));
  701.         $entity_manager->persist($cart);
  702.         $entity_manager->flush();
  703.         $entity_manager->createQueryBuilder()
  704.             ->update('App:Cart''c')
  705.             ->set('c.status'0)
  706.             ->getQuery()
  707.             ->execute();
  708.         $receipt $this->buildReceipt($cart$user_repository$receipt_customer_address_repository$customer_group_repository$receipt_customer_repository$receipt_discount_repository$receipt_price_group_repository$receipt_price_repository$receipt_product_repository$receipt_cart_product_repository$receipt_scale_price_repository$receipt_tax_repository$receipt_unit_repository$receipt_repository$configuration_repository$customer_repository$entity_manager);
  709.         /*        $receipt_cart_products = $receipt->getReceiptCartProducts();
  710.                 $receipt_product_container = [];
  711.                 foreach ($receipt_cart_products as $receipt_cart_product) {
  712.                     $receipt_product = $receipt_cart_product->getReceiptProduct();
  713.                     if ($receipt_product) {
  714.                         $receipt_tax = $receipt_product->getReceiptTax();
  715.                         $product = $receipt_product->getProduct();
  716.                         if ($product && $receipt_tax) {
  717.                             $receipt_product_ = [];
  718.                             $receipt_product_['id'] = $receipt_cart_product->getId();
  719.                             $receipt_product_['receipt_product_id'] = $receipt_product->getId();
  720.                             $receipt_product_['receipt_product_handle'] = $receipt_cart_product->getId();
  721.                             $receipt_product_['amount'] = $receipt_cart_product->getAmount();
  722.                             $receipt_product_['product_id'] = $product->getId();
  723.                             $receipt_product_['name'] = $receipt_product->getName();
  724.                             $receipt_product_['model'] = $receipt_product->getModel();
  725.                             $receipt_product_['price'] = $receipt_product->getPrice() * ((100 + (int)$receipt_tax->getReceiptTax()) / 100);
  726.                             $receipt_product_['price_otax'] = $receipt_product->getPrice();
  727.                             $receipt_product_['discount'] = $receipt_cart_product->getDiscountValue();
  728.                             $receipt_product_['discount_type'] = $receipt_cart_product->getDiscountType();
  729.                             $receipt_product_['add_date'] = $product->getAddDate();
  730.                             $receipt_product_['description'] = $receipt_product->getDescription();
  731.                             $receipt_product_['tax'] = ['id' => $receipt_tax->getId(), 'name' => $receipt_tax->getName(), 'tax' => $receipt_tax->getReceiptTax()];
  732.                             $product_tags = $product->getProductTags();
  733.                             foreach ($product_tags as $product_tag) {
  734.                                 $receipt_product_['tags'][] = ['id' => $product_tag->getId(), 'name' => $product_tag->getName()];
  735.                             }
  736.                             $stock_container = $product->getProductToStocks();
  737.                             foreach ($stock_container as $product_to_stock) {
  738.                                 $stock = $product_to_stock->getStock();
  739.                                 if ($stock) {
  740.                                     $location = $stock->getLocation();
  741.                                     if ($location) {
  742.                                         $receipt_product_['stock'][] = ['id' => $product_to_stock->getId(), 'location' => $location->getName(), 'name' => $stock->getName(), 'amount' => $product_to_stock->getAmount()];
  743.                                     }
  744.                                 }
  745.                             }
  746.                             $receipt_product_['deposit'] = $receipt_product->getDeposit();
  747.                             $receipt_product_container[] = $receipt_product_;
  748.                         }
  749.                     }
  750.                 }*/
  751.         $receipt_comment = (string)$receipt->getComment();
  752.         $this->createReceiptDocument($receipt$entity_manager);
  753.         $transaction_structure $kassen_sichv_api_service->startTransaction($cart->getCashbox(), $receipt);
  754.         if ($transaction_structure->success === true) {
  755.             $fiskaly_transaction $fiskaly_transaction_repository->findOneBy(['transaction_id' => $transaction_structure->getId()]);
  756.             if ($fiskaly_transaction !== null) {
  757. //                $transaction_structure = $kassen_sichv_api_service->updateRawTransaction($fiskaly_transaction, $receipt);
  758.                 $transaction_structure $kassen_sichv_api_service->updateTransaction($fiskaly_transaction$receipt);
  759.                 if ($transaction_structure->success === true) {
  760.                     $kassen_sichv_api_service->finishTransaction($fiskaly_transaction$receipt);
  761.                 }
  762.             }
  763.         }
  764.         $tss_data = [
  765.             'finish_date' => null,
  766.             'finish_date_format' => null,
  767.             'finished' => null,
  768.             'fiskalyClient' => null,
  769.             'fiskalyTss' => null,
  770.             'id' => null,
  771.             'start_date' => null,
  772.             'start_date_format' => null,
  773.             'started' => null,
  774.             'transaction_id' => null,
  775.             'update_date' => null,
  776.             'update_date_format' => null,
  777.             'updated' => null,
  778.         ];
  779.         $fiskaly_transaction $fiskaly_transaction_repository->findOneBy(['transaction_id' => $transaction_structure->getId()]);
  780.         $qr_code "";
  781.         if ($fiskaly_transaction !== null) {
  782.             $tss_data = [
  783.                 'finish_date' => $fiskaly_transaction->getFinishDate(),
  784.                 'finish_date_total_format' => $fiskaly_transaction->getFinishDate()->format("d.m.Y H:i:s"),
  785.                 'finish_date_format' => $fiskaly_transaction->getFinishDate()->format("d.m.Y"),
  786.                 'finish_time_format' => $fiskaly_transaction->getFinishDate()->format("H:i:s"),
  787.                 'finished' => $fiskaly_transaction->getFinished(),
  788.                 'fiskalyClient' => $fiskaly_transaction->getFiskalyClient()->getClientId(),
  789.                 'fiskalyTss' => $fiskaly_transaction->getFiskalyClient()->getFiskalyTss()->getTssId(),
  790.                 'id' => $fiskaly_transaction->getId(),
  791.                 'start_date' => $fiskaly_transaction->getStartDate(),
  792.                 'start_date_total_format' => $fiskaly_transaction->getStartDate()->format("d.m.Y H:i:s"),
  793.                 'start_date_format' => $fiskaly_transaction->getStartDate()->format("d.m.Y"),
  794.                 'start_time_format' => $fiskaly_transaction->getStartDate()->format("H:i:s"),
  795.                 'started' => $fiskaly_transaction->getStarted(),
  796.                 'transaction_id' => $fiskaly_transaction->getTransactionId(),
  797.                 'update_date' => $fiskaly_transaction->getUpdateDate(),
  798.                 'update_date_total_format' => $fiskaly_transaction->getUpdateDate()->format("d.m.Y H:i:s"),
  799.                 'update_date_format' => $fiskaly_transaction->getUpdateDate()->format("d.m.Y"),
  800.                 'update_time_format' => $fiskaly_transaction->getUpdateDate()->format("H:i:s"),
  801.                 'updated' => $fiskaly_transaction->getUpdated(),
  802.             ];
  803.             $pixel_to_mm_factor 25.4;
  804.             $max_paper_mm 75// 80mm receipt
  805.             $printer_dpi 203//most default Thermal-Printer dpi
  806.             $size = ($max_paper_mm / ($pixel_to_mm_factor $printer_dpi));
  807.             $qr_code_result $builder
  808.                 ->writer($svgWriter)
  809.                 ->size($size)
  810.                 ->margin(0)
  811.                 ->data($fiskaly_transaction->getQrCodeData())
  812.                 ->build();
  813.             $qr_code $qr_code_result->getString();
  814.         }
  815.         $receipt_data = [
  816.             "cart_total" => null,
  817.             "cart_total_fixed" => null,
  818.             "cart_total_otax" => null,
  819.             "cart_total_otax_fixed" => null,
  820.             "cart_total_tax" => null,
  821.             "cart_total_tax_fixed" => null,
  822.             "comment" => null,
  823.             "create_date" => $receipt->getCreateDate(),
  824.             "create_date_total_format" => $receipt->getCreateDate()->format("d.m.Y H:i:s"),
  825.             "create_date_format" => $receipt->getCreateDate()->format("d.m.Y"),
  826.             "create_time_format" => $receipt->getCreateDate()->format("H:i:s"),
  827.             "customer" => null,
  828.             "customerAddress" => null,
  829.             "dailyFinancialStatement" => null,
  830.             "discount" => null,
  831.             "discount_type" => null,
  832.             "fiskalyReceiptTypes" => null,
  833.             "fiskalyTransactions" => null,
  834.             "id" => $receipt->getId(),
  835.             "number" => $receipt->getNumber(),
  836.             "receipt_transaction_id" => null,
  837.             "receiptCartProducts" => null,
  838.             "receiptCashbox" => null,
  839.             "receiptCustomerAddresses" => null,
  840.             "receiptCustomerGroups" => null,
  841.             "receiptCustomers" => null,
  842.             "receiptDiscounts" => null,
  843.             "receiptDocuments" => null,
  844.             "receiptEmployee" => null,
  845.             "receiptEmployeeGroups" => null,
  846.             "receiptLocation" => null,
  847.             "receiptPriceGroups" => null,
  848.             "receiptPrices" => null,
  849.             "receiptProducts" => null,
  850.             "receiptScalePrices" => null,
  851.             "receiptTaxes" => null,
  852.             "receiptUnits" => null,
  853.             "receiptUsers" => null,
  854.             "status" => null,
  855.             "total" => null,
  856.             "total_fixed" => null,
  857.             "total_otax" => null,
  858.             "total_otax_fixed" => null,
  859.             "total_tax" => null,
  860.             "total_tax_fixed" => null,
  861.             "transaction" => null,
  862.             "uuid" => null,
  863.         ];
  864.         $receipt_cashbox $receipt->getReceiptCashbox();
  865.         return $this->json([
  866.                 '_success' => true,
  867.                 'tss_data' => $tss_data,
  868.                 'receipt_data' => $receipt_data,
  869.                 'cashbox' => $receipt_cashbox->getId(),
  870.                 'qr_code' => $qr_code,
  871.             ]
  872.         );
  873.     }
  874.     /**
  875.      * @Route("/close/{id}", name="cart_close", methods={"GET"})
  876.      * @param Cart $cart
  877.      */
  878.     public function closeCart(Cart $cartEntityManagerInterface $entity_manager): void
  879.     {
  880.         $cart->setClosed(true)
  881.             ->setCloseDate(new \DateTime('now'));
  882.         $entity_manager->persist($cart);
  883.         $entity_manager->flush();
  884.         $entity_manager->createQueryBuilder()
  885.             ->update('App:Cart''c')
  886.             ->set('c.status'0)
  887.             ->getQuery()
  888.             ->execute();
  889.     }
  890.     /**
  891.      * @Route("/has_customer", name="cart_has_customer", methods={"POST"})
  892.      * @param Request $request
  893.      * @param CartActionService $cartActionService
  894.      */
  895.     public function cartHasCustomer(Request $requestCartActionService $cartActionService)
  896.     {
  897.         $cartActionService->setCartActionData($request->getContent());
  898.         $cart $cartActionService->getPersistedCart();
  899.         if ($cart !== null) {
  900.             $customer $cart->getCustomer();
  901.             if ($customer !== null) {
  902.                 return $this->json(['_success' => true'has_customer' => true]);
  903.             }
  904.             return $this->json(['_success' => true'has_customer' => false]);
  905.         }
  906.         return $this->json(['_success' => false]);
  907.     }
  908.     /**
  909.      * @param Cart $cart
  910.      * @param UserRepository $user_repository
  911.      * @param ReceiptCustomerAddressRepository $receipt_customer_address_repository
  912.      * @param ReceiptCustomerGroupRepository $receipt_customer_group_repository
  913.      * @param ReceiptCustomerRepository $receipt_customer_repository
  914.      * @param ReceiptDiscountRepository $receipt_discount_repository
  915.      * @param ReceiptPriceGroupRepository $receipt_price_group_repository
  916.      * @param ReceiptPriceRepository $receipt_price_repository
  917.      * @param ReceiptProductRepository $receipt_product_repository
  918.      * @param ReceiptCartProductRepository $receipt_cart_product_repository
  919.      * @param ReceiptScalePriceRepository $receipt_scale_price_repository
  920.      * @param ReceiptTaxRepository $receipt_tax_repository
  921.      * @param ReceiptUnitRepository $receipt_unit_repository
  922.      * @param EntityManagerInterface $entity_manager
  923.      * @return Receipt
  924.      */
  925.     private function buildReceipt(Cart $cartUserRepository $user_repositoryReceiptCustomerAddressRepository $receipt_customer_address_repositoryReceiptCustomerGroupRepository $receipt_customer_group_repositoryReceiptCustomerRepository $receipt_customer_repositoryReceiptDiscountRepository $receipt_discount_repositoryReceiptPriceGroupRepository $receipt_price_group_repositoryReceiptPriceRepository $receipt_price_repositoryReceiptProductRepository $receipt_product_repositoryReceiptCartProductRepository $receipt_cart_product_repositoryReceiptScalePriceRepository $receipt_scale_price_repositoryReceiptTaxRepository $receipt_tax_repositoryReceiptUnitRepository $receipt_unit_repositoryReceiptRepository $receipt_repositoryConfigurationRepository $configuration_repositoryCustomerRepository $customer_repositoryEntityManagerInterface $entity_manager): Receipt
  926.     {
  927.         /**
  928.          * addReceiptCartProduct
  929.          * setReceiptTransactionId
  930.          * setStatus
  931.          * setTransaction
  932.          */
  933.         $follow_up_is_deposit 0;
  934.         $follow_up_is_deposit_config $configuration_repository->findOneBy(['config_key' => 'FOLLOW_UP_IS_DEPOSIT''config_group' => 'POS']);
  935.         if ($follow_up_is_deposit_config !== null) {
  936.             $follow_up_is_deposit = (int)$follow_up_is_deposit_config->getConfigValue();
  937.         }
  938.         $new_receipt_number 1;
  939.         $receipt_number_start 1;
  940.         $receipt_number_start_config $configuration_repository->findOneBy(['config_key' => 'RECEIPT_NUMBER_START''config_group' => 'POS_RECEIPT']);
  941.         if ($receipt_number_start_config !== null) {
  942.             $receipt_number_start $receipt_number_start_config->getConfigValue();
  943.             $new_receipt_number $receipt_number_start_config->getConfigValue();
  944.         }
  945.         $last_receipt $receipt_repository->findBy([], ['number' => 'DESC'], 1);
  946.         if (!empty($last_receipt) && $last_receipt[0]->getNumber() >= $receipt_number_start) {
  947.             $new_receipt_number $last_receipt[0]->getNumber() + 1;
  948.         }
  949.         $receipt = new Receipt();
  950.         $receipt
  951.             ->setCreateDate(new \DateTime('now'))
  952.             ->setComment($cart->getComment())
  953.             ->setDiscount($cart->getDiscount())
  954.             ->setDiscountType($cart->getDiscountType())
  955.             ->setCartTotal($cart->getTotal())
  956.             ->setCartTotalFixed($cart->getTotalFixed())
  957.             ->setCartTotalOtax($cart->getTotalOtax())
  958.             ->setCartTotalOtaxFixed($cart->getTotalOtaxFixed())
  959.             ->setCartTotalTax($cart->getTotalTax())
  960.             ->setCartTotalTaxFixed($cart->getTotalTaxFixed())
  961.             ->setNumber($new_receipt_number);
  962.         $entity_manager->persist($receipt);
  963.         $entity_manager->flush();
  964.         // ReceiptCashbox
  965.         $cashbox $cart->getCashbox();
  966.         if ($cashbox) {
  967.             $receipt->setReceiptCashbox($this->buildReceiptCashbox($cashbox$receipt$entity_manager));
  968.         }
  969.         // ReceiptTransaction
  970.         $transaction $cart->getTransactions()->last();
  971.         if ($transaction !== false) {
  972.             $receipt->addReceiptTransaction($this->buildReceiptTransaction($transaction$receipt$entity_manager));
  973.         }
  974.         // Customer?
  975.         $customer $cart->getCustomer();
  976.         $has_customer false;
  977.         if ($customer) {
  978.             $has_customer true;
  979.         } else {
  980.             $default_pos_customer $configuration_repository->findOneBy(['config_key' => 'DEFAULT_POS_CUSTOMER''config_group' => 'POS_CUSTOMER']);
  981.             if ($default_pos_customer !== null) {
  982.                 $customer $customer_repository->findOneBy(['id' => $default_pos_customer]);
  983.                 if ($customer !== null) {
  984.                     $has_customer true;
  985.                 }
  986.             }
  987.         }
  988.         if ($has_customer) {
  989.             $receipt->setCustomer($customer);
  990.             $receipt->addReceiptCustomer($this->buildFullReceiptCustomer($customer$receipt$receipt_customer_repository$receipt_customer_group_repository$receipt_discount_repository$receipt_price_group_repository$receipt_customer_address_repository$receipt_price_repository$receipt_unit_repository$receipt_scale_price_repository$entity_manager));
  991.         }
  992.         $employee $cart->getEmployee();
  993.         if ($employee) {
  994.             $receipt->setReceiptEmployee($this->buildReceiptEmployee($employee$receipt$user_repository$entity_manager));
  995.         }
  996.         $location $cart->getLocation();
  997.         if ($location) {
  998.             $receipt->setReceiptLocation($this->buildReceiptLocation($location$entity_manager));
  999.         }
  1000.         $entity_manager->persist($receipt);
  1001.         $entity_manager->flush();
  1002.         foreach ($cart->getCartProductToCarts() as $cart_product_to_cart) {
  1003.             $cart_product $cart_product_to_cart->getCartProduct();
  1004.             $has_follow_up false;
  1005.             $is_follow_up false;
  1006.             if ($cart_product) {
  1007.                 $product $cart_product->getProduct();
  1008.                 if ($product) {
  1009.                     $is_follow_up $this->isFollowUp($product);
  1010.                     $has_follow_up $this->hasFollowUp($product);
  1011.                     $receipt_product $this->buildReceiptProduct($cart_product$receipt$receipt_customer_group_repository$receipt_customer_repository$receipt_discount_repository$receipt_price_group_repository$receipt_price_repository$receipt_product_repository$receipt_scale_price_repository$receipt_tax_repository$receipt_unit_repository$entity_manager);
  1012.                     if ($receipt_product) {
  1013.                         $pricing_structure $this->priceService->buildProductPrice($product);
  1014.                         $use_pricing_structure $pricing_structure->getPrice();
  1015.                         if ($has_customer === true && $pricing_structure->isHasCustomerPrices() && isset($pricing_structure->getCustomerPrice()[$customer->getId()])) {
  1016.                             $use_pricing_structure $pricing_structure->getCustomerPrice()[$customer->getId()];
  1017.                         }
  1018.                         if ($pricing_structure->isHasScalePrices() && isset($pricing_structure->getScalePrice()[$cart_product_to_cart->getAmount()])) {
  1019.                             $scale_pricing_structure $pricing_structure->getScalePrice()[$cart_product_to_cart->getAmount()];
  1020.                             $use_pricing_structure $scale_pricing_structure;
  1021.                             if ($has_customer === true && $scale_pricing_structure->isHasCustomerPrices() && isset($scale_pricing_structure->getCustomerPrice()[$customer->getId()])) {
  1022.                                 $use_pricing_structure $scale_pricing_structure->getCustomerPrice()[$customer->getId()];
  1023.                             }
  1024.                         }
  1025.                         $receipt_cart_product = new ReceiptCartProduct();
  1026.                         $receipt_cart_product
  1027.                             ->setReceipt($receipt)
  1028.                             ->setReceiptProduct($receipt_product)
  1029.                             ->setAmount($cart_product_to_cart->getAmount())
  1030.                             ->setBasePrice($pricing_structure->getBasePrice()->getPrice())
  1031.                             ->setBasePriceFixed($pricing_structure->getBasePrice()->getPriceFixed())
  1032.                             ->setBasePriceOtax($pricing_structure->getBasePrice()->getPriceNoTax())
  1033.                             ->setBasePriceOtaxFixed($pricing_structure->getBasePrice()->getPriceNoTaxFixed())
  1034.                             ->setBaseTotal($pricing_structure->getBasePrice()->getPrice() * $cart_product_to_cart->getAmount())
  1035.                             ->setBaseTotalFixed($this->priceService->priceFix($pricing_structure->getBasePrice()->getPrice() * $cart_product_to_cart->getAmount()))
  1036.                             ->setBaseTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getBaseTotal(),(float)$receipt_product->getReceiptTax()->getReceiptTax()))
  1037.                             ->setBaseTotalOtaxFixed($this->priceService->priceFix($receipt_cart_product->getBaseTotalOtax()))
  1038.                             ->setHasDiscount($cart_product->getHasDiscount())
  1039.                             ->setPrice($use_pricing_structure->getPrice())
  1040.                             ->setPriceFixed($use_pricing_structure->getPriceFixed())
  1041.                             ->setPriceOtax($use_pricing_structure->getPriceNoTax())
  1042.                             ->setPriceOtaxFixed($use_pricing_structure->getPriceNoTaxFixed())
  1043.                             ->setReceipt($receipt)
  1044.                             ->setTotal($use_pricing_structure->getPrice() * $cart_product_to_cart->getAmount())
  1045.                             ->setTotalFixed($this->priceService->priceFix($use_pricing_structure->getPrice() * $cart_product_to_cart->getAmount()))
  1046.                             ->setTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getTotal(),(float)$receipt_product->getReceiptTax()->getReceiptTax()))
  1047.                             ->setTotalOtaxFixed($receipt_cart_product->getTotalOtax())
  1048.                             ->setCartBasePrice($cart_product->getBasePrice())
  1049.                             ->setCartBasePriceFixed($cart_product->getBasePriceFixed())
  1050.                             ->setCartBasePriceOtax($cart_product->getBasePriceOtax())
  1051.                             ->setCartBasePriceOtaxFixed($cart_product->getBasePriceOtaxFixed())
  1052.                             ->setCartBaseTotal($cart_product->getBaseTotal())
  1053.                             ->setCartBaseTotalFixed($cart_product->getBaseTotalFixed())
  1054.                             ->setCartBaseTotalOtax($cart_product->getBaseTotalOtax())
  1055.                             ->setCartBaseTotalOtaxFixed($cart_product->getBaseTotalOtaxFixed())
  1056.                             ->setCartHasDiscount($cart_product->getHasDiscount())
  1057.                             ->setCartPrice($cart_product->getPrice())
  1058.                             ->setCartPriceFixed($cart_product->getPriceFixed())
  1059.                             ->setCartPriceOtax($cart_product->getPriceOtax())
  1060.                             ->setCartPriceOtaxFixed($cart_product->getPriceOtaxFixed())
  1061.                             ->setCartTotal($cart_product->getTotal())
  1062.                             ->setCartTotalFixed($cart_product->getTotalFixed())
  1063.                             ->setCartTotalOtax($cart_product->getTotalOtax())
  1064.                             ->setCartTotalOtaxFixed($cart_product->getTotalOtaxFixed())
  1065.                             ->setDiscountValue($cart_product->getDiscountValue())
  1066.                             ->setDiscountType($cart_product->getDiscountType())
  1067.                             ->setUseComponent($cart_product->getUseComponent())
  1068.                             ->setDepositRefund($cart_product->getDepositRefund())
  1069.                             ->setReceiptProductHandle($cart_product->getCartProductHandle())
  1070.                             ->setHasFollowUp($has_follow_up)
  1071.                             ->setIsFollowUp($is_follow_up);
  1072.                         if ($cart_product->getUseComponent() === true) {
  1073.                             $receipt_cart_product
  1074.                                 ->setPrice($use_pricing_structure->getComponentPrice())
  1075.                                 ->setPriceFixed($use_pricing_structure->getComponentPriceFixed())
  1076.                                 ->setBasePrice($pricing_structure->getBasePrice()->getComponentPrice())
  1077.                                 ->setBasePriceFixed($pricing_structure->getBasePrice()->getComponentPriceFixed())
  1078.                                 ->setTotal($receipt_cart_product->getPrice() * $cart_product_to_cart->getAmount())
  1079.                                 ->setTotalFixed($receipt_cart_product->getTotal())
  1080.                                 ->setBaseTotal($receipt_cart_product->getBasePrice() * $cart_product_to_cart->getAmount())
  1081.                                 ->setBaseTotalFixed($receipt_cart_product->getBasePriceFixed() * $cart_product_to_cart->getAmount())
  1082.                                 ->setBasePriceOtax($pricing_structure->getBasePrice()->getComponentPriceNoTax())
  1083.                                 ->setBasePriceOtaxFixed($pricing_structure->getBasePrice()->getComponentPriceNoTaxFixed())
  1084.                                 ->setPriceOtax($use_pricing_structure->getComponentPriceNoTax())
  1085.                                 ->setPriceOtaxFixed($use_pricing_structure->getComponentPriceNoTaxFixed())
  1086.                                 ->setTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getTotal(),(float)$receipt_product->getReceiptTax()->getReceiptTax()))
  1087.                                 ->setTotalOtaxFixed($receipt_cart_product->getTotalOtax())
  1088.                                 ->setBaseTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getBaseTotal(),(float)$receipt_product->getReceiptTax()->getReceiptTax()))
  1089.                                 ->setBaseTotalOtaxFixed($receipt_cart_product->getBaseTotalOtax());
  1090.                         }
  1091. //dump($product);
  1092. //dump($customer);
  1093.                         if ($product->getDeposit() === true && ($customer === null || $customer->getB2b() === null || $customer->getB2b() === false)) {
  1094.                             $receipt_cart_product
  1095.                                 ->setPrice($receipt_cart_product->getPriceOtax())
  1096.                                 ->setPriceFixed($receipt_cart_product->getPriceOtaxFixed())
  1097.                                 ->setBasePrice($receipt_cart_product->getBasePriceOtax())
  1098.                                 ->setBasePriceFixed($receipt_cart_product->getBasePriceOtaxFixed())
  1099.                                 ->setTotal($receipt_cart_product->getPrice() * $cart_product_to_cart->getAmount())
  1100.                                 ->setTotalFixed($receipt_cart_product->getPriceFixed() * $cart_product_to_cart->getAmount())
  1101.                                 ->setBaseTotal($receipt_cart_product->getBasePrice() * $cart_product_to_cart->getAmount())
  1102.                                 ->setBaseTotalFixed($receipt_cart_product->getBasePriceFixed() * $cart_product_to_cart->getAmount());
  1103. //                            dump($receipt_cart_product);
  1104.                         }
  1105.                         if ($follow_up_is_deposit === && $is_follow_up === true && ($customer === null || $customer->getB2b() === null || $customer->getB2b() === false)) {
  1106.                             $receipt_cart_product
  1107.                                 ->setPrice($receipt_cart_product->getPriceOtax())
  1108.                                 ->setPriceFixed($receipt_cart_product->getPriceOtaxFixed())
  1109.                                 ->setBasePrice($receipt_cart_product->getBasePriceOtax())
  1110.                                 ->setBasePriceFixed($receipt_cart_product->getBasePriceOtaxFixed())
  1111.                                 ->setTotal($receipt_cart_product->getPrice() * $cart_product_to_cart->getAmount())
  1112.                                 ->setTotalFixed($receipt_cart_product->getPriceFixed() * $cart_product_to_cart->getAmount())
  1113.                                 ->setBaseTotal($receipt_cart_product->getBasePrice() * $cart_product_to_cart->getAmount())
  1114.                                 ->setBaseTotalFixed($receipt_cart_product->getBasePriceFixed() * $cart_product_to_cart->getAmount());
  1115. //                            dump($receipt_cart_product);
  1116.                         }
  1117.                         if ($cart_product->getDepositRefund() === true) {
  1118.                             $receipt_cart_product
  1119.                                 ->setPrice($receipt_cart_product->getPrice())
  1120.                                 ->setPriceFixed($receipt_cart_product->getPriceFixed())
  1121.                                 ->setBasePrice($receipt_cart_product->getBasePrice())
  1122.                                 ->setBasePriceFixed($receipt_cart_product->getBasePriceFixed())
  1123.                                 ->setTotal($receipt_cart_product->getPrice() * $cart_product_to_cart->getAmount())
  1124.                                 ->setTotalFixed($receipt_cart_product->getPriceFixed() * $cart_product_to_cart->getAmount())
  1125.                                 ->setBaseTotal($receipt_cart_product->getBasePrice() * $cart_product_to_cart->getAmount())
  1126.                                 ->setBaseTotalFixed($receipt_cart_product->getBasePriceFixed() * $cart_product_to_cart->getAmount())
  1127.                                 ->setPriceOtax($receipt_cart_product->getPriceOtax())
  1128.                                 ->setPriceOtaxFixed($receipt_cart_product->getPriceOtaxFixed())
  1129.                                 ->setTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getTotal(),(float)$receipt_product->getReceiptTax()->getReceiptTax()))
  1130.                                 ->setTotalOtaxFixed($receipt_cart_product->getTotalOtax())
  1131.                                 ->setBasePriceOtax($receipt_cart_product->getBasePriceOtax())
  1132.                                 ->setBasePriceOtaxFixed($receipt_cart_product->getBasePriceOtaxFixed())
  1133.                                 ->setBaseTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getBaseTotal(),(float)$receipt_product->getReceiptTax()->getReceiptTax()))
  1134.                                 ->setBaseTotalOtaxFixed($receipt_cart_product->getBaseTotalOtax());
  1135.                         }
  1136.                         $receipt_cart_product->setBaseTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getBaseTotal(), (float)$receipt_product->getReceiptTax()->getReceiptTax()));
  1137.                         $receipt_cart_product->setBaseTotalOtaxFixed($this->priceService->priceFix($receipt_cart_product->getBaseTotalOtax()));
  1138.                         $receipt_cart_product->setTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getTotal(), (float)$receipt_product->getReceiptTax()->getReceiptTax()));
  1139.                         $receipt_cart_product->setTotalOtaxFixed($this->priceService->priceFix($receipt_cart_product->getTotalOtax()));
  1140.                         $entity_manager->persist($receipt_cart_product);
  1141.                         $receipt->addReceiptCartProduct($receipt_cart_product);
  1142.                         $receipt_product->addReceiptCartProduct($receipt_cart_product);
  1143.                     }
  1144.                 }
  1145.             }
  1146.         }
  1147.         $entity_manager->flush();
  1148.         //Connections
  1149.         foreach ($cart->getCartProductToCarts() as $cart_product_to_cart) {
  1150.             $cart_product $cart_product_to_cart->getCartProduct();
  1151.             /** Das ist eine Wirklich blöde Stelle. Denn wir müssen uns jetzt das
  1152.              * ReceiptCartProduct auf Basis des CartProduct holen.
  1153.              */
  1154.             $receipt_cart_product $receipt_cart_product_repository->findOneBy(['receipt_product_handle' => $cart_product->getCartProductHandle()]);
  1155.             $connected_cart_products $cart_product->getConnectedCartProducts();
  1156.             if (!$connected_cart_products->isEmpty()) {
  1157.                 foreach ($connected_cart_products as $connected_cart_product) {
  1158.                     /** Das ist eine Wirklich blöde Stelle. Denn wir müssen uns jetzt das
  1159.                      * ReceiptCartProduct auf Basis des CartProduct holen.
  1160.                      */
  1161.                     $connected_receipt_cart_product $receipt_cart_product_repository->findOneBy(['receipt_product_handle' => $connected_cart_product->getCartProductHandle()]);
  1162.                     if ($connected_receipt_cart_product) {
  1163.                         $receipt_cart_product->addConnectedReceiptCartProduct($connected_receipt_cart_product);
  1164.                         $entity_manager->persist($receipt_cart_product);
  1165.                     }
  1166.                 }
  1167.             }
  1168.         }
  1169.         $entity_manager->flush();
  1170.         $total 0;
  1171.         $total_fixed 0;
  1172.         $total_otax 0;
  1173.         $total_otax_fixed 0;
  1174.         $taxes = ['taxes' => [], 'positions' => [], 'total_otax' => [], 'total' => [], 'total_tax' => []];
  1175.         foreach ($receipt->getReceiptCartProducts() as $receipt_cart_product) {
  1176.             $taxes['taxes'][$receipt_cart_product->getReceiptProduct()->getReceiptTax()->getId()] = $receipt_cart_product->getReceiptProduct()->getReceiptTax()->getReceiptTax();
  1177.             $taxes['positions'][$receipt_cart_product->getReceiptProduct()->getReceiptTax()->getId()][] = $receipt_cart_product->getTotal();
  1178. //            $total += $receipt_cart_product->getTotal();
  1179. //            $total_fixed += $receipt_cart_product->getTotalOtaxFixed();
  1180. //            $total_otax += $receipt_cart_product->getTotalOtax();
  1181. //            $total_otax_fixed += $receipt_cart_product->getTotalOtaxFixed();
  1182.         }
  1183. //        $total_fixed = $this->priceService->priceFix($total);
  1184.         foreach ($taxes['taxes'] as $mtax_key => $mtax_item) {
  1185.             $taxes['total'][$mtax_key] = array_sum($taxes['positions'][$mtax_key]);
  1186.             $taxes['total_otax'][$mtax_key] = $taxes['total'][$mtax_key] / ((100 $taxes['taxes'][$mtax_key]) / 100);
  1187.             $taxes['total_otax'][$mtax_key] = $this->priceService->removeTax((float)$taxes['total'][$mtax_key], (float)$taxes['taxes'][$mtax_key]);
  1188.             $taxes['total_otax'][$mtax_key] = $this->priceService->priceFix($taxes['total_otax'][$mtax_key]);
  1189.             $taxes['total_tax'][$mtax_key] = $taxes['total'][$mtax_key] - $taxes['total_otax'][$mtax_key];
  1190.         }
  1191.         $total array_sum($taxes['total']);
  1192.         $total_fixed $this->priceService->priceFix($total);
  1193.         $total_otax array_sum($taxes['total_otax']);
  1194.         $total_otax_fixed $this->priceService->priceFix($total_otax);
  1195.         $total_tax array_sum($taxes['total_tax']);
  1196.         $total_tax_fixed $this->priceService->priceFix($total_tax);
  1197.         $receipt
  1198.             ->setTotal($total)
  1199.             ->setTotalFixed($total_fixed)
  1200.             ->setTotalOtax($total_otax)
  1201.             ->setTotalOtaxFixed($total_otax_fixed)
  1202.             ->setTotalTax($total_tax)
  1203.             ->setTotalTaxFixed($total_tax_fixed);
  1204.         $entity_manager->persist($receipt);
  1205.         $entity_manager->flush();
  1206.         return $receipt;
  1207.     }
  1208.     /**
  1209.      * @param Employee $employee
  1210.      * @param Receipt $receipt
  1211.      * @param UserRepository $user_repository
  1212.      * @param EntityManagerInterface $entity_manager
  1213.      * @return ReceiptEmployee
  1214.      */
  1215.     private function buildReceiptEmployee(Employee $employeeReceipt $receiptUserRepository $user_repositoryEntityManagerInterface $entity_manager): ReceiptEmployee
  1216.     {
  1217.         $receipt_employee = new ReceiptEmployee();
  1218.         $receipt_employee->setEmployee($employee)
  1219.             ->setExternalIdentifier($employee->getExternalIdentifier())
  1220.             ->setFamilyName($employee->getFamilyName())
  1221.             ->setFromApi($employee->getFromApi())
  1222.             ->setGivenName($employee->getGivenName())
  1223.             ->setLockPin($employee->getLockPin())
  1224.             ->setStatus($employee->getStatus())
  1225.             ->setTelephone($employee->getTelephone());
  1226.         $employee_group $employee->getEmployeeGroup();
  1227.         if ($employee_group) {
  1228.             $receipt_employee->setReceiptEmployeeGroup($this->buildReceiptEmployeeGroup($employee->getEmployeeGroup(), $receipt$entity_manager));
  1229.         }
  1230.         $user $this->getUser();
  1231.         if ($user) {
  1232.             $receipt_employee->setReceiptUser($this->buildReceiptUser($user$receipt$user_repository$entity_manager));
  1233.         }
  1234.         $entity_manager->persist($receipt_employee);
  1235.         $entity_manager->flush();
  1236.         return $receipt_employee;
  1237.     }
  1238.     private function buildReceiptEmployeeGroup(EmployeeGroup $employeeGroupReceipt $receiptEntityManagerInterface $entityManager): ReceiptEmployeeGroup
  1239.     {
  1240.         $receiptEmployeeGroup = new ReceiptEmployeeGroup();
  1241.         $receiptEmployeeGroup->setComment($employeeGroup->getComment())
  1242.             ->setEmployeeGroup($employeeGroup)
  1243.             ->setName($employeeGroup->getName())
  1244.             ->setReceipt($receipt)
  1245.             ->setStatus($employeeGroup->getStatus());
  1246.         $entityManager->persist($receiptEmployeeGroup);
  1247.         $entityManager->flush();
  1248.         return $receiptEmployeeGroup;
  1249.     }
  1250.     private function buildReceiptUser(UserInterface $userReceipt $receiptUserRepository $userRepositoryEntityManagerInterface $entityManager): ReceiptUser
  1251.     {
  1252.         $receiptUser = new ReceiptUser();
  1253.         $_user $userRepository->findOneBy(['id' => $user->getId()]);
  1254.         $receiptUser->setAccountId($user->getAccountId())
  1255.             ->setEmail($user->getEmail())
  1256.             ->setPassword($user->getPassword())
  1257.             ->setRoles($user->getRoles())
  1258. //            ->setReceipt($receipt)
  1259.             ->setUser($_user);
  1260.         $entityManager->persist($receiptUser);
  1261.         $entityManager->flush();
  1262.         return $receiptUser;
  1263.     }
  1264.     /**
  1265.      * @param Location $location
  1266.      * @param EntityManagerInterface $entity_manager
  1267.      * @return ReceiptLocation
  1268.      */
  1269.     private function buildReceiptLocation(Location $locationEntityManagerInterface $entity_manager): ReceiptLocation
  1270.     {
  1271.         $receipt_location = new ReceiptLocation();
  1272.         $receipt_location->setAddressAddition($location->getAddressAddition())
  1273.             ->setAddressCountry($location->getAddressCountry())
  1274.             ->setAddressLocality($location->getAddressLocality())
  1275.             ->setEmail($location->getEmail())
  1276.             ->setFaxNumber($location->getFaxNumber())
  1277.             ->setLocation($location)
  1278.             ->setLogo($location->getLogo())
  1279.             ->setName($location->getName())
  1280.             ->setPostalCode($location->getPostalCode())
  1281.             ->setShowAddressOnReceipt($location->getShowAddressOnReceipt())
  1282.             ->setShowContactOnReceipt($location->getShowContactOnReceipt())
  1283.             ->setStreetAddress($location->getStreetAddress())
  1284.             ->setTelephone($location->getTelephone())
  1285.             ->setWebsite($location->getWebsite());
  1286.         $entity_manager->persist($receipt_location);
  1287.         $entity_manager->flush();
  1288.         return $receipt_location;
  1289.     }
  1290.     /**
  1291.      * @param CartProduct $cart_product
  1292.      * @param Receipt $receipt
  1293.      * @param ReceiptCustomerGroupRepository $receipt_customer_group_repository
  1294.      * @param ReceiptCustomerRepository $receipt_customer_repository
  1295.      * @param ReceiptDiscountRepository $receipt_discount_repository
  1296.      * @param ReceiptPriceGroupRepository $receipt_price_group_repository
  1297.      * @param ReceiptPriceRepository $receipt_price_repository
  1298.      * @param ReceiptProductRepository $receipt_product_repository
  1299.      * @param ReceiptScalePriceRepository $receipt_scale_price_repository
  1300.      * @param ReceiptTaxRepository $receipt_tax_repository
  1301.      * @param ReceiptUnitRepository $receipt_unit_repository
  1302.      * @param EntityManagerInterface $entity_manager
  1303.      * @return ReceiptProduct|null
  1304.      */
  1305.     private function buildReceiptProduct(CartProduct $cart_productReceipt $receiptReceiptCustomerGroupRepository $receipt_customer_group_repositoryReceiptCustomerRepository $receipt_customer_repositoryReceiptDiscountRepository $receipt_discount_repositoryReceiptPriceGroupRepository $receipt_price_group_repositoryReceiptPriceRepository $receipt_price_repositoryReceiptProductRepository $receipt_product_repositoryReceiptScalePriceRepository $receipt_scale_price_repositoryReceiptTaxRepository $receipt_tax_repositoryReceiptUnitRepository $receipt_unit_repositoryEntityManagerInterface $entity_manager): ?ReceiptProduct
  1306.     {
  1307.         $product $cart_product->getProduct();
  1308.         $has_follow_up false;
  1309.         $is_follow_up false;
  1310.         if ($product) {
  1311.             $is_follow_up $this->isFollowUp($product);
  1312.             $has_follow_up $this->hasFollowUp($product);
  1313.             $receipt_product $receipt_product_repository->findOneBy(['receipt' => $receipt->getId(), 'product' => $product->getId()]);
  1314.             if (!$receipt_product) {
  1315.                 $receipt_product = new ReceiptProduct();
  1316.                 $receipt_product->setAddDate(new \DateTime('now'))
  1317.                     ->setComponentPrice($product->getComponentPrice())
  1318.                     ->setContainer($product->getContainer())
  1319.                     ->setContainerSize($product->getContainerSize())
  1320.                     ->setDeposit($product->getDeposit())
  1321.                     ->setDescription($product->getDescription())
  1322.                     ->setHandle($product->getHandle())
  1323.                     ->setImage($product->getImage())
  1324.                     ->setModel($product->getModel())
  1325.                     ->setName($product->getName())
  1326.                     ->setPrice($product->getPrice())
  1327.                     ->setPurchasingPrice($product->getPurchasingPrice())
  1328.                     ->setProduct($product)
  1329.                     ->setReceipt($receipt)
  1330.                     ->setSalesUnitFactor($product->getSalesUnitFactor())
  1331.                     ->setStatus($product->getStatus())
  1332.                     ->setStorageUnitContainerSize($product->getStorageUnitContainerSize())
  1333.                     ->setStorageUnitHeight($product->getStorageUnitHeight())
  1334.                     ->setStorageUnitLength($product->getStorageUnitLength())
  1335.                     ->setStorageUnitPalletSize($product->getStorageUnitPalletSize())
  1336.                     ->setStorageUnitTotalLiters($product->getStorageUnitTotalLiters())
  1337.                     ->setStorageUnitVolume($product->getStorageUnitVolume())
  1338.                     ->setStorageUnitWeight($product->getStorageUnitWeight())
  1339.                     ->setStorageUnitWidth($product->getStorageUnitWidth())
  1340.                     ->setHasFollowUp($has_follow_up)
  1341.                     ->setIsFollowUp($is_follow_up);
  1342.                 if ($cart_product->getPriceOverride() !== null && $cart_product->getPriceOverride() > 0) {
  1343.                     $receipt_product->setPrice($cart_product->getPriceOverride());
  1344.                 }
  1345.                 $entity_manager->persist($receipt_product);
  1346.                 $entity_manager->flush();
  1347.                 $tax $product->getTax();
  1348.                 if ($tax) {
  1349.                     $receipt_product->setReceiptTax($this->buildReceiptTax($tax$receipt$receipt_tax_repository$entity_manager));
  1350.                 }
  1351.                 $sales_unit $product->getSalesUnit();
  1352.                 if ($sales_unit) {
  1353.                     $receipt_product->setReceiptUnit($this->buildReceiptUnit($sales_unit$receipt$receipt_unit_repository$entity_manager));
  1354.                 }
  1355.                 foreach ($product->getPrices() as $price) {
  1356.                     $receipt_product->addReceiptPrice($this->buildReceiptPrice($price$receipt$receipt_price_repository$receipt_customer_repository$receipt_customer_group_repository$receipt_discount_repository$receipt_price_group_repository$receipt_unit_repository$entity_manager));
  1357.                 }
  1358.                 foreach ($product->getScalePrices() as $scale_price) {
  1359.                     $receipt_product->addReceiptScalePrice($this->buildReceiptScalePrice($scale_price$receipt$receipt_scale_price_repository$receipt_customer_repository$receipt_customer_group_repository$receipt_discount_repository$receipt_price_group_repository$receipt_unit_repository$entity_manager));
  1360.                 }
  1361.                 $entity_manager->persist($receipt_product);
  1362.                 $entity_manager->flush();
  1363.             }
  1364.             return $receipt_product;
  1365.         }
  1366.         return null;
  1367.     }
  1368.     /**
  1369.      * @param Tax $tax
  1370.      * @param Receipt $receipt
  1371.      * @param ReceiptTaxRepository $receipt_tax_repository
  1372.      * @param EntityManagerInterface $entity_manager
  1373.      * @return ReceiptTax
  1374.      */
  1375.     private function buildReceiptTax(Tax $taxReceipt $receiptReceiptTaxRepository $receipt_tax_repositoryEntityManagerInterface $entity_manager): ReceiptTax
  1376.     {
  1377.         $receipt_tax $receipt_tax_repository->findOneBy(['receipt' => $receipt->getId(), 'tax' => $tax->getId()]);
  1378.         if (!$receipt_tax) {
  1379.             $receipt_tax = new ReceiptTax();
  1380.             $receipt_tax->setName($tax->getName())
  1381.                 ->setReceipt($receipt)
  1382.                 ->setReceiptTax($tax->getTax())
  1383.                 ->setTax($tax);
  1384.             $entity_manager->persist($receipt_tax);
  1385.             $entity_manager->flush();
  1386.             return $receipt_tax;
  1387.         }
  1388.         return $receipt_tax;
  1389.     }
  1390.     /**
  1391.      * @param Unit $unit
  1392.      * @param Receipt $receipt
  1393.      * @param ReceiptUnitRepository $receipt_unit_repository
  1394.      * @param EntityManagerInterface $entity_manager
  1395.      * @return ReceiptUnit
  1396.      */
  1397.     private function buildReceiptUnit(Unit $unitReceipt $receiptReceiptUnitRepository $receipt_unit_repositoryEntityManagerInterface $entity_manager): ReceiptUnit
  1398.     {
  1399.         $receipt_unit $receipt_unit_repository->findOneBy(['receipt' => $receipt->getId(), 'unit' => $unit->getId()]);
  1400.         if (!$receipt_unit) {
  1401.             $receipt_unit = new ReceiptUnit();
  1402.             $receipt_unit->setName($unit->getName())
  1403.                 ->setReceipt($receipt)
  1404.                 ->setUnit($unit);
  1405.             $entity_manager->persist($receipt_unit);
  1406.             $entity_manager->flush();
  1407.             return $receipt_unit;
  1408.         }
  1409.         return $receipt_unit;
  1410.     }
  1411.     /**
  1412.      * @param Price $price
  1413.      * @param Receipt $receipt
  1414.      * @param ReceiptPriceRepository $receipt_price_repository
  1415.      * @param ReceiptCustomerRepository $receipt_customer_repository
  1416.      * @param ReceiptCustomerGroupRepository $receipt_customer_group_repository
  1417.      * @param ReceiptDiscountRepository $receipt_discount_repository
  1418.      * @param ReceiptPriceGroupRepository $receipt_price_group_repository
  1419.      * @param ReceiptUnitRepository $receipt_unit_repository
  1420.      * @param EntityManagerInterface $entity_manager
  1421.      * @return ReceiptPrice|null
  1422.      */
  1423.     private function buildReceiptPrice(Price $priceReceipt $receiptReceiptPriceRepository $receipt_price_repositoryReceiptCustomerRepository $receipt_customer_repositoryReceiptCustomerGroupRepository $receipt_customer_group_repositoryReceiptDiscountRepository $receipt_discount_repositoryReceiptPriceGroupRepository $receipt_price_group_repositoryReceiptUnitRepository $receipt_unit_repositoryEntityManagerInterface $entity_manager): ?ReceiptPrice
  1424.     {
  1425.         $receipt_price $receipt_price_repository->findOneBy(['receipt' => $receipt->getId(), 'sourcePrice' => $price->getId()]);
  1426.         if (!$receipt_price) {
  1427.             $receipt_price = new ReceiptPrice();
  1428.             $receipt_price->setComponentPrice($price->getComponentPrice())
  1429.                 ->setPrice($price->getPrice())
  1430.                 ->setReceipt($receipt)
  1431.                 ->setSalesUnitFactor($price->getSalesUnitFactor())
  1432.                 ->setSourcePrice($price)
  1433.                 ->setValidFrom($price->getValidFrom())
  1434.                 ->setValidTo($price->getValidTo());
  1435.             $customer $price->getCustomer();
  1436.             if ($customer) {
  1437.                 $receipt_price->setReceiptCustomer($this->buildReceiptCustomer($customer$receipt$receipt_customer_repository$receipt_customer_group_repository$receipt_discount_repository$receipt_price_group_repository$entity_manager));
  1438.             }
  1439.             $price_group $price->getPriceGroup();
  1440.             if ($price_group) {
  1441.                 $receipt_price->setReceiptPriceGroup($this->buildReceiptPriceGroup($price_group$receipt$receipt_price_group_repository$entity_manager));
  1442.             }
  1443.             $sales_unit $price->getSalesUnit();
  1444.             if ($sales_unit) {
  1445.                 $receipt_price->setReceiptUnit($this->buildReceiptUnit($sales_unit$receipt$receipt_unit_repository$entity_manager));
  1446.             }
  1447.             $entity_manager->persist($receipt_price);
  1448. //            $entity_manager->flush();
  1449.         }
  1450.         return $receipt_price;
  1451.     }
  1452.     /**
  1453.      * @param ScalePrice $scale_price
  1454.      * @param Receipt $receipt
  1455.      * @param ReceiptScalePriceRepository $receipt_scale_price_repository
  1456.      * @param ReceiptCustomerRepository $receipt_customer_repository
  1457.      * @param ReceiptCustomerGroupRepository $receipt_customer_group_repository
  1458.      * @param ReceiptDiscountRepository $receipt_discount_repository
  1459.      * @param ReceiptPriceGroupRepository $receipt_price_group_repository
  1460.      * @param ReceiptUnitRepository $receipt_unit_repository
  1461.      * @param EntityManagerInterface $entity_manager
  1462.      * @return ReceiptScalePrice|null
  1463.      */
  1464.     private function buildReceiptScalePrice(ScalePrice $scale_priceReceipt $receiptReceiptScalePriceRepository $receipt_scale_price_repositoryReceiptCustomerRepository $receipt_customer_repositoryReceiptCustomerGroupRepository $receipt_customer_group_repositoryReceiptDiscountRepository $receipt_discount_repositoryReceiptPriceGroupRepository $receipt_price_group_repositoryReceiptUnitRepository $receipt_unit_repositoryEntityManagerInterface $entity_manager): ?ReceiptScalePrice
  1465.     {
  1466.         $receipt_scale_price $receipt_scale_price_repository->findOneBy(['receipt' => $receipt->getId(), 'scalePrice' => $scale_price->getId()]);
  1467.         if (!$receipt_scale_price) {
  1468.             $receipt_scale_price = new ReceiptScalePrice();
  1469.             $receipt_scale_price->setComponentPrice($scale_price->getComponentPrice())
  1470.                 ->setPrice($scale_price->getPrice())
  1471.                 ->setReceipt($receipt)
  1472.                 ->setSalesUnitFactor($scale_price->getSalesUnitFactor())
  1473.                 ->setScalePrice($scale_price)
  1474.                 ->setValidFrom($scale_price->getValidFrom())
  1475.                 ->setValidTo($scale_price->getValidTo())
  1476.                 ->setQuantity($scale_price->getQuantity());
  1477.             $customer $scale_price->getCustomer();
  1478.             if ($customer) {
  1479.                 $receipt_scale_price->setReceiptCustomer($this->buildReceiptCustomer($customer$receipt$receipt_customer_repository$receipt_customer_group_repository$receipt_discount_repository$receipt_price_group_repository$entity_manager));
  1480.             }
  1481.             $price_group $scale_price->getPriceGroup();
  1482.             if ($price_group) {
  1483.                 $receipt_scale_price->setReceiptPriceGroup($this->buildReceiptPriceGroup($price_group$receipt$receipt_price_group_repository$entity_manager));
  1484.             }
  1485.             $sales_unit $scale_price->getSalesUnit();
  1486.             if ($sales_unit) {
  1487.                 $receipt_scale_price->setReceiptUnit($this->buildReceiptUnit($sales_unit$receipt$receipt_unit_repository$entity_manager));
  1488.             }
  1489.             $entity_manager->persist($receipt_scale_price);
  1490. //            $entity_manager->flush();
  1491.         }
  1492.         return $receipt_scale_price;
  1493.     }
  1494.     /**
  1495.      * @param Cashbox $cashbox
  1496.      * @param Receipt $receipt
  1497.      * @param EntityManagerInterface $entity_manager
  1498.      * @return ReceiptCashbox
  1499.      */
  1500.     private function buildReceiptCashbox(Cashbox $cashboxReceipt $receiptEntityManagerInterface $entity_manager): ReceiptCashbox
  1501.     {
  1502.         $receipt_cashbox = new ReceiptCashbox();
  1503.         $receipt_cashbox
  1504.             ->addReceipt($receipt)
  1505.             ->setCashbox($cashbox)
  1506.             ->setComment($cashbox->getComment())
  1507.             ->setLocked($cashbox->getLocked())
  1508.             ->setName($cashbox->getName())
  1509.             ->setSerialNumber($cashbox->getSerialNumber())
  1510.             ->setSnapDate(new \DateTime('now'));
  1511.         $entity_manager->persist($receipt_cashbox);
  1512. //        $entity_manager->flush();
  1513.         return $receipt_cashbox;
  1514.     }
  1515.     private function buildReceiptCustomer(Customer $customerReceipt $receiptReceiptCustomerRepository $receiptCustomerRepositoryReceiptCustomerGroupRepository $receiptCustomerGroupRepositoryReceiptDiscountRepository $receiptDiscountRepositoryReceiptPriceGroupRepository $receiptPriceGroupRepositoryEntityManagerInterface $entityManager): ?ReceiptCustomer
  1516.     {
  1517.         $receiptCustomer $receiptCustomerRepository->findOneBy(['receipt' => $receipt->getId(), 'customer' => $customer->getId()]);
  1518.         if (!$receiptCustomer) {
  1519.             $receiptCustomer = new ReceiptCustomer();
  1520.             $receiptCustomer->setCreateDate($customer->getCreateDate())
  1521.                 ->setCustomer($customer)
  1522.                 ->setEmail($customer->getEmail())
  1523.                 ->setFamilyName($customer->getFamilyName())
  1524.                 ->setGivenName($customer->getGivenName())
  1525.                 ->setReceipt($receipt)
  1526.                 ->setVat($customer->getVat())
  1527.                 ->setB2b($customer->getB2b())
  1528.                 ->setUuid($customer->getUuid());
  1529.             $customerGroup $customer->getCustomerGroup();
  1530.             if ($customerGroup) {
  1531.                 $receiptCustomer->setReceiptCustomerGroup($this->buildReceiptCustomerGroup($customerGroup$receipt$receiptCustomerGroupRepository$receiptDiscountRepository$receiptPriceGroupRepository$entityManager));
  1532.             }
  1533.             $discount $customer->getDiscount();
  1534.             if ($discount) {
  1535.                 $receiptCustomer->setReceiptDiscount($this->buildReceiptDiscount($discount$receipt$receiptDiscountRepository$entityManager));
  1536.             }
  1537.             $priceGroup $customer->getPriceGroup();
  1538.             if ($priceGroup) {
  1539.                 $receiptCustomer->setReceiptPriceGroup($this->buildReceiptPriceGroup($priceGroup$receipt$receiptPriceGroupRepository$entityManager));
  1540.             }
  1541. //            $receiptCustomer->addReceiptCustomerAddress();
  1542. //            $receiptCustomer->addReceiptPrice();
  1543. //            $receiptCustomer->addReceiptScalePrice();
  1544.             $entityManager->persist($receiptCustomer);
  1545. //            $entityManager->flush();
  1546.         }
  1547.         return $receiptCustomer;
  1548.     }
  1549.     /**
  1550.      * @param Customer $customer
  1551.      * @param Receipt $receipt
  1552.      * @param ReceiptCustomerRepository $receipt_customer_repository
  1553.      * @param ReceiptCustomerGroupRepository $receipt_customer_group_repository
  1554.      * @param ReceiptDiscountRepository $receipt_discount_repository
  1555.      * @param ReceiptPriceGroupRepository $receipt_price_group_repository
  1556.      * @param ReceiptCustomerAddressRepository $receipt_customer_address_repository
  1557.      * @param ReceiptPriceRepository $receipt_price_repository
  1558.      * @param ReceiptUnitRepository $receipt_unit_repository
  1559.      * @param ReceiptScalePriceRepository $receipt_scale_price_repository
  1560.      * @param EntityManagerInterface $entity_manager
  1561.      * @return ReceiptCustomer|null
  1562.      */
  1563.     private function buildFullReceiptCustomer(Customer $customerReceipt $receiptReceiptCustomerRepository $receipt_customer_repositoryReceiptCustomerGroupRepository $receipt_customer_group_repositoryReceiptDiscountRepository $receipt_discount_repositoryReceiptPriceGroupRepository $receipt_price_group_repositoryReceiptCustomerAddressRepository $receipt_customer_address_repositoryReceiptPriceRepository $receipt_price_repositoryReceiptUnitRepository $receipt_unit_repositoryReceiptScalePriceRepository $receipt_scale_price_repositoryEntityManagerInterface $entity_manager): ?ReceiptCustomer
  1564.     {
  1565.         $receipt_customer $receipt_customer_repository->findOneBy(['receipt' => $receipt->getId(), 'customer' => $customer->getId()]);
  1566.         if (!$receipt_customer) {
  1567.             $receipt_customer = new ReceiptCustomer();
  1568.             $receipt_customer->setCreateDate($customer->getCreateDate())
  1569.                 ->setCustomer($customer)
  1570.                 ->setEmail($customer->getEmail())
  1571.                 ->setFamilyName($customer->getFamilyName())
  1572.                 ->setGivenName($customer->getGivenName())
  1573.                 ->setReceipt($receipt)
  1574.                 ->setVat($customer->getVat())
  1575.                 ->setB2b($customer->getB2b())
  1576.                 ->setUuid($customer->getUuid());
  1577.             $entity_manager->persist($receipt_customer);
  1578.             $entity_manager->flush();
  1579.             $customer_group $customer->getCustomerGroup();
  1580.             if ($customer_group) {
  1581.                 $receipt_customer->setReceiptCustomerGroup($this->buildReceiptCustomerGroup($customer_group$receipt$receipt_customer_group_repository$receipt_discount_repository$receipt_price_group_repository$entity_manager));
  1582.             }
  1583.             $discount $customer->getDiscount();
  1584.             if ($discount) {
  1585.                 $receipt_customer->setReceiptDiscount($this->buildReceiptDiscount($discount$receipt$receipt_discount_repository$entity_manager));
  1586.             }
  1587.             $price_group $customer->getPriceGroup();
  1588.             if ($price_group) {
  1589.                 $receipt_customer->setReceiptPriceGroup($this->buildReceiptPriceGroup($price_group$receipt$receipt_price_group_repository$entity_manager));
  1590.             }
  1591.             $entity_manager->persist($receipt_customer);
  1592.             $entity_manager->flush();
  1593.         }
  1594.         foreach ($customer->getCustomerAddresses() as $customer_address) {
  1595.             $receipt_customer->addReceiptCustomerAddress($this->buildReceiptCustomerAddress($customer_address$receipt$receipt_customer_address_repository$entity_manager));
  1596.         }
  1597.         foreach ($customer->getPrices() as $price) {
  1598.             $receipt_customer->addReceiptPrice($this->buildReceiptPrice($price$receipt$receipt_price_repository$receipt_customer_repository$receipt_customer_group_repository$receipt_discount_repository$receipt_price_group_repository$receipt_unit_repository$entity_manager));
  1599.         }
  1600.         foreach ($customer->getScalePrices() as $scale_price) {
  1601.             $receipt_customer->addReceiptScalePrice($this->buildReceiptScalePrice($scale_price$receipt$receipt_scale_price_repository$receipt_customer_repository$receipt_customer_group_repository$receipt_discount_repository$receipt_price_group_repository$receipt_unit_repository$entity_manager));
  1602.         }
  1603.         $entity_manager->persist($receipt_customer);
  1604.         $entity_manager->flush();
  1605.         return $receipt_customer;
  1606.     }
  1607.     private function buildReceiptCustomerAddress(CustomerAddress $customerAddressReceipt $receiptReceiptCustomerAddressRepository $receiptCustomerAddressRepositoryEntityManagerInterface $entityManager): ?ReceiptCustomerAddress
  1608.     {
  1609.         $receiptCustomerAddress $receiptCustomerAddressRepository->findOneBy(['receipt' => $receipt->getId(), 'customerAddress' => $customerAddress->getId()]);
  1610.         if (!$receiptCustomerAddress) {
  1611.             $receiptCustomerAddress = new ReceiptCustomerAddress();
  1612.             $receiptCustomerAddress
  1613.                 ->setAddressAddition($customerAddress->getAddressAddition())
  1614.                 ->setAddressCountry($customerAddress->getAddressCountry())
  1615.                 ->setAddressLocality($customerAddress->getAddressLocality())
  1616.                 ->setAddressSuburb($customerAddress->getAddressSuburb())
  1617.                 ->setCompany($customerAddress->getCompany())
  1618.                 ->setCompanyDepartment($customerAddress->getCompanyDepartment())
  1619.                 ->setCreateDate(new \DateTime('now'))
  1620.                 ->setCustomerAddress($customerAddress)
  1621.                 ->setDateOfBirth($customerAddress->getDateOfBirth())
  1622.                 ->setExternalIdentifier($customerAddress->getExternalIdentifier())
  1623.                 ->setFamilyName($customerAddress->getFamilyName())
  1624.                 ->setFaxNumber($customerAddress->getFaxNumber())
  1625.                 ->setGender($customerAddress->getGender())
  1626.                 ->setGivenName($customerAddress->getGivenName())
  1627.                 ->setMobilephone($customerAddress->getMobilephone())
  1628.                 ->setPostalCode($customerAddress->getPostalCode())
  1629.                 ->setReceipt($receipt)
  1630.                 ->setStreetAddress($customerAddress->getStreetAddress())
  1631.                 ->setTelephone($customerAddress->getTelephone())
  1632.                 ->setTitle($customerAddress->getTitle())
  1633.                 ->setType($customerAddress->getType());
  1634.             $entityManager->persist($receiptCustomerAddress);
  1635. //            $entityManager->flush();
  1636.         }
  1637.         return $receiptCustomerAddress;
  1638.     }
  1639.     private function buildReceiptPriceGroup(PriceGroup $priceGroupReceipt $receiptReceiptPriceGroupRepository $receiptPriceGroupRepositoryEntityManagerInterface $entityManager): ?ReceiptPriceGroup
  1640.     {
  1641.         $receiptPriceGroup $receiptPriceGroupRepository->findOneBy(['receipt' => $receipt->getId(), 'priceGroup' => $priceGroup->getId()]);
  1642.         if (!$receiptPriceGroup) {
  1643.             $receiptPriceGroup = new ReceiptPriceGroup();
  1644.             $receiptPriceGroup->setCreateDate(new \DateTime('now'))
  1645.                 ->setName($priceGroup->getName())
  1646.                 ->setPriceGroup($priceGroup)
  1647.                 ->setReceipt($receipt);
  1648.             $entityManager->persist($receiptPriceGroup);
  1649. //            $entityManager->flush();
  1650.         }
  1651.         return $receiptPriceGroup;
  1652.     }
  1653.     private function buildReceiptCustomerGroup(CustomerGroup $customerGroupReceipt $receiptReceiptCustomerGroupRepository $receiptCustomerGroupRepositoryReceiptDiscountRepository $receiptDiscountRepositoryReceiptPriceGroupRepository $receiptPriceGroupRepositoryEntityManagerInterface $entityManager): ?ReceiptCustomerGroup
  1654.     {
  1655.         $receiptCustomerGroup $receiptCustomerGroupRepository->findOneBy(['receipt' => $receipt->getId(), 'customerGroup' => $customerGroup->getId()]);
  1656.         if (!$receiptCustomerGroup) {
  1657.             $receiptCustomerGroup = new ReceiptCustomerGroup();
  1658.             $receiptCustomerGroup->setCustomerGroup($customerGroup)
  1659.                 ->setName($customerGroup->getName())
  1660.                 ->setReceipt($receipt);
  1661.             $discount $customerGroup->getDiscount();
  1662.             if ($discount) {
  1663.                 $receiptCustomerGroup->setReceiptDiscount($this->buildReceiptDiscount($discount$receipt$receiptDiscountRepository$entityManager));
  1664.             }
  1665.             $priceGroup $customerGroup->getPriceGroup();
  1666.             if ($priceGroup) {
  1667.                 $receiptCustomerGroup->setReceiptPriceGroup($this->buildReceiptPriceGroup($priceGroup$receipt$receiptPriceGroupRepository$entityManager));
  1668.             }
  1669.             $entityManager->persist($receiptCustomerGroup);
  1670. //            $entityManager->flush();
  1671.         }
  1672.         return $receiptCustomerGroup;
  1673.     }
  1674.     private function buildReceiptDiscount(Discount $discountReceipt $receiptReceiptDiscountRepository $receiptDiscountRepositoryEntityManagerInterface $entityManager): ?ReceiptDiscount
  1675.     {
  1676.         $receiptDiscount $receiptDiscountRepository->findOneBy(['receipt' => $receipt'discount' => $discount->getId()]);
  1677.         if (!$receiptDiscount) {
  1678.             $receiptDiscount = new ReceiptDiscount();
  1679.             $receiptDiscount->setDiscount($discount)
  1680.                 ->setName($discount->getName())
  1681.                 ->setReceipt($receipt)
  1682.                 ->setType($discount->getType())
  1683.                 ->setValue($discount->getValue());
  1684.             $entityManager->persist($receiptDiscount);
  1685. //            $entityManager->flush();
  1686.         }
  1687.         return $receiptDiscount;
  1688.     }
  1689.     private function updateCartProduct(CartProduct $cartProduct, array $cart$amountstring $cartProductHandleCart $persistedCartCartProductToCartRepository $cartProductToCartRepositoryEntityManagerInterface $entityManager)
  1690.     {
  1691.         $cartProduct
  1692.             ->setBasePrice($cart['products'][$cartProductHandle]['base_price'])
  1693.             ->setBasePriceFixed($cart['products'][$cartProductHandle]['base_price_fixed'])
  1694.             ->setBasePriceOtax($cart['products'][$cartProductHandle]['base_price_otax'])
  1695.             ->setBasePriceOtaxFixed($cart['products'][$cartProductHandle]['base_price_otax_fixed'])
  1696.             ->setBaseTotal($cart['products'][$cartProductHandle]['base_total'])
  1697.             ->setBaseTotalFixed($cart['products'][$cartProductHandle]['base_total_fixed'])
  1698.             ->setBaseTotalOtax($cart['products'][$cartProductHandle]['base_total_otax'])
  1699.             ->setBaseTotalOtaxFixed($cart['products'][$cartProductHandle]['base_total_otax_fixed'])
  1700.             ->setHasDiscount($cart['products'][$cartProductHandle]['has_discount'])
  1701.             ->setPrice($cart['products'][$cartProductHandle]['price'])
  1702.             ->setPriceFixed($cart['products'][$cartProductHandle]['price_fixed'])
  1703.             ->setPriceOtax($cart['products'][$cartProductHandle]['price_otax'])
  1704.             ->setPriceOtaxFixed($cart['products'][$cartProductHandle]['price_otax_fixed'])
  1705.             ->setTotal($cart['products'][$cartProductHandle]['total'])
  1706.             ->setTotalFixed($cart['products'][$cartProductHandle]['total_fixed'])
  1707.             ->setTotalOtax($cart['products'][$cartProductHandle]['total_otax'])
  1708.             ->setTotalOtaxFixed($cart['products'][$cartProductHandle]['total_otax_fixed']);
  1709.         if (isset($cart['products'][$cartProductHandle]['product']['override_price'])) {
  1710.             $cartProduct->setPriceOverride($cart['products'][$cartProductHandle]['product']['override_price']);
  1711.         } else {
  1712.             $cartProduct->setPriceOverride(null);
  1713.         }
  1714.         $entityManager->persist($cartProduct);
  1715.         $entityManager->flush();
  1716.         // Liegt es schon im Cart?
  1717.         $cartProductToCart $cartProductToCartRepository->findOneBy(['cart' => $persistedCart->getId(), 'cartProduct' => $cartProduct->getId()]);
  1718.         if (!$cartProductToCart) {
  1719.             $cartProductToCart = new CartProductToCart();
  1720.             $cartProductToCart->setCart($persistedCart)
  1721.                 ->setCartProduct($cartProduct);
  1722.         }
  1723.         $cartProductToCart->setAmount($amount['value'])
  1724.             ->setAmountLocked($amount['locked']);
  1725.         $entityManager->persist($cartProductToCart);
  1726.         $entityManager->flush();
  1727.     }
  1728.     private function createCartProduct(Product $productCart $persistedCart, array $cart$amountstring $cartProductHandle$discountValue$discountTypebool $useComponentbool $depositRefundEntityManagerInterface $entityManager): CartProduct
  1729.     {
  1730.         $_cartProduct = new CartProduct();
  1731.         $_cartProduct
  1732.             ->setProduct($product)
  1733.             ->setAddDate(new \DateTime('now'))
  1734.             ->setCart($persistedCart)
  1735.             ->setDiscountValue($discountValue)
  1736.             ->setDiscountType($discountType)
  1737.             ->setCartProductHandle($cartProductHandle)
  1738.             ->setBasePrice($cart['products'][$cartProductHandle]['base_price'])
  1739.             ->setBasePriceFixed($cart['products'][$cartProductHandle]['base_price_fixed'])
  1740.             ->setBasePriceOtax($cart['products'][$cartProductHandle]['base_price_otax'])
  1741.             ->setBasePriceOtaxFixed($cart['products'][$cartProductHandle]['base_price_otax_fixed'])
  1742.             ->setBaseTotal($cart['products'][$cartProductHandle]['base_total'])
  1743.             ->setBaseTotalFixed($cart['products'][$cartProductHandle]['base_total_fixed'])
  1744.             ->setBaseTotalOtax($cart['products'][$cartProductHandle]['base_total_otax'])
  1745.             ->setBaseTotalOtaxFixed($cart['products'][$cartProductHandle]['base_total_otax_fixed'])
  1746.             ->setHasDiscount($cart['products'][$cartProductHandle]['has_discount'])
  1747.             ->setPrice($cart['products'][$cartProductHandle]['price'])
  1748.             ->setPriceFixed($cart['products'][$cartProductHandle]['price_fixed'])
  1749.             ->setPriceOtax($cart['products'][$cartProductHandle]['price_otax'])
  1750.             ->setPriceOtaxFixed($cart['products'][$cartProductHandle]['price_otax_fixed'])
  1751.             ->setTotal($cart['products'][$cartProductHandle]['total'])
  1752.             ->setTotalFixed($cart['products'][$cartProductHandle]['total_fixed'])
  1753.             ->setTotalOtax($cart['products'][$cartProductHandle]['total_otax'])
  1754.             ->setTotalOtaxFixed($cart['products'][$cartProductHandle]['total_otax_fixed'])
  1755.             ->setUseComponent($useComponent)
  1756.             ->setDepositRefund($depositRefund);
  1757.         if (isset($cart['products'][$cartProductHandle]['product']['override_price'])) {
  1758.             $_cartProduct->setPriceOverride($cart['products'][$cartProductHandle]['product']['override_price']);
  1759.         } else {
  1760.             $_cartProduct->setPriceOverride(null);
  1761.         }
  1762.         $entityManager->persist($_cartProduct);
  1763.         $entityManager->flush();
  1764.         $cartProductToCart = new CartProductToCart();
  1765.         $cartProductToCart->setCart($persistedCart)
  1766.             ->setCartProduct($_cartProduct)
  1767.             ->setAmount($amount['value'])
  1768.             ->setAmountLocked($amount['locked']);
  1769.         $entityManager->persist($cartProductToCart);
  1770.         $entityManager->flush();
  1771.         return $_cartProduct;
  1772.     }
  1773.     /**
  1774.      * @param Receipt $receipt
  1775.      * @param EntityManagerInterface $entity_manager
  1776.      * @return void
  1777.      */
  1778.     private function createReceiptDocument(Receipt $receiptEntityManagerInterface $entity_manager)
  1779.     {
  1780.         $receipt_cart_product_to_receipt_document_position = [];
  1781.         $receipt_document = new ReceiptDocument();
  1782.         $receipt_cart_products $receipt->getReceiptCartProducts();
  1783.         foreach ($receipt_cart_products as $receipt_cart_product) {
  1784.             /*
  1785.             $has_connection = false;
  1786.             $is_connected = false;
  1787.             $r___ = $receipt_cart_product->getConnectedReceiptCartProducts();
  1788.             if ($r___ !== null) {
  1789.                 $has_connection = true;
  1790.             }
  1791.             $r___ = $receipt_cart_product->getReceiptCartProducts();
  1792.             if ($r___ !== null) {
  1793.                 $is_connected = true;
  1794.             }
  1795.             */
  1796.             $receipt_product $receipt_cart_product->getReceiptProduct();
  1797.             $receipt_document_position = new ReceiptDocumentPosition();
  1798.             $receipt_document_position
  1799.                 ->setAmount($receipt_cart_product->getAmount())
  1800.                 ->setDepositRefund($receipt_cart_product->getDepositRefund())
  1801.                 ->setDiscountType($receipt_cart_product->getDiscountType())
  1802.                 ->setDiscountValue($receipt_cart_product->getDiscountValue())
  1803.                 ->setHasDiscount($receipt_cart_product->getHasDiscount())
  1804.                 ->setPrice($receipt_cart_product->getPrice())
  1805.                 ->setPriceFixed($receipt_cart_product->getPriceFixed())
  1806.                 ->setPriceOtax($receipt_cart_product->getPriceOtax())
  1807.                 ->setPriceOtaxFixed($receipt_cart_product->getPriceOtaxFixed())
  1808.                 ->setProduct($receipt_cart_product->getReceiptProduct()->getProduct())
  1809.                 ->setTotal($receipt_cart_product->getTotal())
  1810.                 ->setTotalFixed($receipt_cart_product->getTotalFixed())
  1811.                 ->setTotalOtax($receipt_cart_product->getTotalOtax())
  1812.                 ->setTotalOtaxFixed($receipt_cart_product->getTotalOtaxFixed())
  1813.                 ->setUseComponent($receipt_cart_product->getUseComponent())
  1814.                 ->setDeposit($receipt_product->getDeposit())
  1815.                 ->setHasFollowUp($receipt_cart_product->getHasFollowUp())
  1816.                 ->setIsFollowUp($receipt_cart_product->getIsFollowUp());
  1817.             $entity_manager->persist($receipt_document_position);
  1818.             $receipt_document->addReceiptDocumentPosition($receipt_document_position);
  1819.             $receipt_cart_product_to_receipt_document_position[$receipt_cart_product->getId()] = compact('receipt_cart_product''receipt_document_position');
  1820.         }
  1821.         foreach ($receipt_cart_product_to_receipt_document_position as $key => $item) {
  1822.             /**
  1823.              * @var ReceiptCartProduct $receipt_cart_product_
  1824.              */
  1825.             $receipt_cart_product_ $item['receipt_cart_product'];
  1826.             /**
  1827.              * @var ReceiptDocumentPosition $receipt_document_position_
  1828.              */
  1829.             $receipt_document_position_ $item['receipt_document_position'];
  1830.             $connected_receipt_cart_products $receipt_cart_product_->getConnectedReceiptCartProducts();
  1831.             foreach ($connected_receipt_cart_products as $connected_receipt_cart_product) {
  1832.                 $receipt_document_position_->addConnectedReceiptDocumentPosition($receipt_cart_product_to_receipt_document_position[$connected_receipt_cart_product->getId()]['receipt_document_position']);
  1833.             }
  1834.         }
  1835.         $customer $receipt->getCustomer();
  1836.         $customer_address $receipt->getCustomerAddress();
  1837.         if ($customer === null && $customer_address !== null) {
  1838.             $customer $customer_address->getCustomer();
  1839.         }
  1840.         if ($customer !== null) {
  1841.             $receipt_document_customer = new ReceiptDocumentCustomer();
  1842.             $receipt_document_customer
  1843.                 ->setCreateDate(new \DateTime('now'))
  1844.                 ->setCustomer($customer)
  1845.                 ->setEmail($customer->getEmail())
  1846.                 ->setFamilyName($customer->getFamilyName())
  1847.                 ->setGivenName($customer->getGivenName())
  1848.                 ->setVat($customer->getVat())
  1849.                 ->setB2b($customer->getB2b());
  1850.             $entity_manager->persist($receipt_document_customer);
  1851.             $receipt_document->addReceiptDocumentCustomer($receipt_document_customer);
  1852.         }
  1853.         if ($customer_address !== null) {
  1854.             $receipt_document_customer_address = new ReceiptDocumentCustomerAddress();
  1855.             $receipt_document_customer_address
  1856.                 ->setAddressAddition($customer_address->getAddressAddition())
  1857.                 ->setAddressCountry($customer_address->getAddressCountry())
  1858.                 ->setAddressLocality($customer_address->getAddressLocality())
  1859.                 ->setAddressSuburb($customer_address->getAddressSuburb())
  1860.                 ->setCompany($customer_address->getCompany())
  1861.                 ->setCompanyDepartment($customer_address->getCompanyDepartment())
  1862.                 ->setCreateDate($customer_address->getCreateDate())
  1863.                 ->setDateOfBirth($customer_address->getDateOfBirth())
  1864.                 ->setExternalIdentifier($customer_address->getExternalIdentifier())
  1865.                 ->setFamilyName($customer_address->getFamilyName())
  1866.                 ->setFaxNumber($customer_address->getFaxNumber())
  1867.                 ->setGender($customer_address->getGender())
  1868.                 ->setMobilephone($customer_address->getMobilephone())
  1869.                 ->setPostalCode($customer_address->getPostalCode())
  1870.                 ->setStreetAddress($customer_address->getStreetAddress())
  1871.                 ->setTelephone($customer_address->getTelephone())
  1872.                 ->setTitle($customer_address->getTitle())
  1873.                 ->setType($customer_address->getType());
  1874.             if ($customer !== null && isset($receipt_document_customer)) {
  1875.                 $receipt_document_customer_address->setReceiptDocumentCustomer($receipt_document_customer);
  1876.             }
  1877.             $entity_manager->persist($receipt_document_customer_address);
  1878.         }
  1879.         $receipt_document
  1880.             ->setComment($receipt->getComment())
  1881.             ->setCreateDate($receipt->getCreateDate())
  1882.             ->setDiscount($receipt->getDiscount())
  1883.             ->setDiscountType($receipt->getDiscountType())
  1884.             ->setReceipt($receipt)
  1885.             ->setTotal($receipt->getTotal())
  1886.             ->setTotalFixed($receipt->getTotalFixed())
  1887.             ->setTotalOtax($receipt->getTotalOtax())
  1888.             ->setTotalOtaxFixed($receipt->getTotalOtaxFixed())
  1889.             ->setTotalTax($receipt->getTotalTax())
  1890.             ->setTotalTaxFixed($receipt->getTotalTaxFixed());
  1891.         $entity_manager->persist($receipt_document);
  1892.         $entity_manager->flush();
  1893.     }
  1894.     private function hasFollowUp(Product $product): bool
  1895.     {
  1896.         $follow_up_products $product->getFollowUpProducts();
  1897.         return $follow_up_products->isEmpty() === false;
  1898.     }
  1899.     private function isFollowUp(Product $product): bool
  1900.     {
  1901.         $follow_up_products $product->getFollowUpProductFrom();
  1902.         return $follow_up_products->isEmpty() === false;
  1903.     }
  1904.     private function buildReceiptTransaction(Transaction $transactionReceipt $receiptEntityManagerInterface $entity_manager): ReceiptTransaction
  1905.     {
  1906.         $receipt_transaction = new ReceiptTransaction();
  1907.         $receipt_transaction
  1908.             ->setReceipt($receipt)
  1909.             ->setReceiptPaymentMethod($this->buildReceiptPaymentMethod($transaction->getPaymentMethod(), $receipt$entity_manager))
  1910.             ->setToPay($transaction->getToPay())
  1911.             ->setGivenCash($transaction->getGivenCash())
  1912.             ->setChangeCash($transaction->getChangeCash())
  1913.             ->setTransactionDate($transaction->getTransactionDate())
  1914.             ->setTransaction($transaction);
  1915.         $entity_manager->persist($receipt_transaction);
  1916. //        $entity_manager->flush();
  1917.         return $receipt_transaction;
  1918.     }
  1919.     private function buildReceiptPaymentMethod(PaymentMethod $payment_methodReceipt $receiptEntityManagerInterface $entity_manager): ReceiptPaymentMethod
  1920.     {
  1921.         $receipt_payment_method = new ReceiptPaymentMethod();
  1922.         $receipt_payment_method
  1923.             ->setName($payment_method->getName())
  1924.             ->setCash($payment_method->getCash())
  1925.             ->setUuid($payment_method->getUuid())
  1926.             ->setPaymentMethod($payment_method);
  1927.         $entity_manager->persist($receipt_payment_method);
  1928. //        $entity_manager->flush();
  1929.         return $receipt_payment_method;
  1930.     }
  1931. }