src/Controller/CashBox/CartController.php line 135

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