<?php
namespace App\Controller\CashBox;
use App\Entity\Cart;
use App\Entity\CartHistory;
use App\Entity\CartLog;
use App\Entity\CartProduct;
use App\Entity\CartProductToCart;
use App\Entity\Cashbox;
use App\Entity\Customer;
use App\Entity\CustomerAddress;
use App\Entity\CustomerGroup;
use App\Entity\DevLog;
use App\Entity\Discount;
use App\Entity\Employee;
use App\Entity\EmployeeGroup;
use App\Entity\FiskalyTransaction;
use App\Entity\Location;
use App\Entity\PaymentMethod;
use App\Entity\Price;
use App\Entity\PriceGroup;
use App\Entity\Product;
use App\Entity\Receipt;
use App\Entity\ReceiptCashbox;
use App\Entity\ReceiptCustomer;
use App\Entity\ReceiptCustomerAddress;
use App\Entity\ReceiptCustomerGroup;
use App\Entity\ReceiptDiscount;
use App\Entity\ReceiptDocument;
use App\Entity\ReceiptDocumentCustomer;
use App\Entity\ReceiptDocumentCustomerAddress;
use App\Entity\ReceiptDocumentPosition;
use App\Entity\ReceiptEmployee;
use App\Entity\ReceiptEmployeeGroup;
use App\Entity\ReceiptLocation;
use App\Entity\ReceiptPaymentMethod;
use App\Entity\ReceiptPrice;
use App\Entity\ReceiptPriceGroup;
use App\Entity\ReceiptProduct;
use App\Entity\ReceiptCartProduct;
use App\Entity\ReceiptScalePrice;
use App\Entity\ReceiptTax;
use App\Entity\ReceiptTransaction;
use App\Entity\ReceiptUnit;
use App\Entity\ReceiptUser;
use App\Entity\ScalePrice;
use App\Entity\Tax;
use App\Entity\Transaction;
use App\Entity\Unit;
use App\Repository\CartProductRepository;
use App\Repository\CartProductToCartRepository;
use App\Repository\CartRepository;
use App\Repository\CashboxRepository;
use App\Repository\ConfigurationRepository;
use App\Repository\CustomerAddressRepository;
use App\Repository\CustomerRepository;
use App\Repository\FiskalyTransactionRepository;
use App\Repository\LocationRepository;
use App\Repository\ReceiptCustomerAddressRepository;
use App\Repository\ReceiptCustomerGroupRepository;
use App\Repository\ReceiptCustomerRepository;
use App\Repository\ReceiptDiscountRepository;
use App\Repository\ReceiptEmployeeGroupRepository;
use App\Repository\ReceiptEmployeeRepository;
use App\Repository\ReceiptLocationRepository;
use App\Repository\ReceiptPriceGroupRepository;
use App\Repository\ReceiptPriceRepository;
use App\Repository\ReceiptProductRepository;
use App\Repository\ReceiptCartProductRepository;
use App\Repository\ReceiptRepository;
use App\Repository\ReceiptScalePriceRepository;
use App\Repository\ReceiptTaxRepository;
use App\Repository\ReceiptUnitRepository;
use App\Repository\ReceiptUserRepository;
use App\Repository\UserRepository;
use App\Service\CashBox\CartActionService;
use App\Service\CashBox\CashboxService;
use App\Service\CashBox\ProductService;
use App\Service\Fiskaly\KassenSichVApiService;
use Doctrine\ORM\EntityManagerInterface;
use Endroid\QrCode\Builder\BuilderInterface;
use Endroid\QrCode\Writer\SvgWriter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\SerializerInterface;
use App\Serializer\Normalizer\ReactCartNormalizer;
use App\Service\CashBox\PriceService;
use function is_array;
/**
* @Route("/cart")
*/
class CartController extends AbstractController
{
/**
* @var SessionInterface
*/
private SessionInterface $session;
private PriceService $priceService;
/**
* CartController constructor.
* @param SessionInterface $session
*/
public function __construct(SessionInterface $session)
{
$this->session = $session;
$this->priceService = new PriceService();
}
/**
* @Route("/", name="cart_index")
* @return Response
*/
public function index(): Response
{
return new Response('');
}
/**
* @Route("/create", name="cart_create", methods={"POST"})
* @param EntityManagerInterface $entity_manager
* @param LocationRepository $location_repository
* @param CashboxRepository $cashbox_repository
* @return JsonResponse
*/
public function createCart(Request $request, EntityManagerInterface $entity_manager, LocationRepository $location_repository, CashboxRepository $cashbox_repository, CustomerAddressRepository $customer_address_repository): JsonResponse
{
$customer_address = null;
$customer = null;
$request_data = json_decode($request->getContent(), true);
if (isset($request_data['customer'], $request_data['customer']['cId']) && !empty($request_data['customer']) && !empty($request_data['customer']['cId'])) {
$customer_address = $customer_address_repository->findOneBy(['id' => $request_data['customer']['cId']]);
if ($customer_address !== null) {
$customer = $customer_address->getCustomer();
}
}
$response = ['id' => null, '_success' => false, '_error' => 'Please choose a cashbox!'];
if ($this->session->has('cashbox')) {
/**
* @var Cashbox $cashbox
*/
$cashbox = $this->session->get('cashbox');
$location = null;
$location_ = $cashbox->getLocation();
if ($location_ !== null) {
$location = $location_repository->findOneBy(['id' => $location_->getId()]);
}
$entity_manager->createQueryBuilder()
->update('App:Cart', 'c')
->set('c.status', 0)
->getQuery()
->execute();
try {
$cart = new Cart();
$cart->setCreateDate(new \DateTime('now'))
->setLocation($location)
->setEmployee($this->getUser()->getEmployees())
->setCashbox($cashbox_repository->findOneBy(['id' => $cashbox->getId()]))
->setParked(false)
->setFinished(false)
->setStatus('open')
->setSaved(false)
->setClosed(false);
if ($customer !== null) {
$cart->setCustomer($customer);
}
if ($customer_address !== null) {
$cart->setCustomerAddress($customer_address);
}
$entity_manager->persist($cart);
$entity_manager->flush();
$response = ['id' => $cart->getId(), '_success' => true, '_error' => null];
} catch (\Exception $exception) {
// TODO: Error Handling
// dump($exception->getMessage());
$response = ['id' => null, '_success' => false, '_error' => $exception->getMessage()];
}
}
return new JsonResponse($response);
}
/**
* @Route("/update", name="cart_update", methods={"POST"})
* @param Request $request
* @param CartActionService $cart_action_service
* @param EntityManagerInterface $entity_manager
* @return Response
* @throws \JsonException
*/
public function updateCart(Request $request, CartActionService $cart_action_service, EntityManagerInterface $entity_manager, CartProductRepository $cart_product_repository, CartProductToCartRepository $cart_product_to_cart_repository): Response
{
$dev_log = new DevLog();
$dev_log->setAction('LOG')
->setType(__CLASS__)
->setFile(__FILE__)
->setLine(__LINE__)
->setInfo(__METHOD__)
->setData(json_decode(($request->getContent() && !empty($request->getContent())) ? $request->getContent() : [], true, 512, JSON_THROW_ON_ERROR))
->setMessage(__METHOD__)
->setAddDate(new \DateTime('now'));
$entity_manager->persist($dev_log);
$entity_manager->flush();
$cart_action_service->setCartActionData($request->getContent());
$cart_action = $cart_action_service->getCartAction();
/**
* @var Cart $persisted_cart
*/
$persisted_cart = $cart_action_service->getPersistedCart();
// dump($cartActionService->getCartActionData());
switch ($cart_action) {
case 'add':
$this->addToCart($request, $cart_action_service, $entity_manager, $cart_product_repository, $cart_product_to_cart_repository);
break;
case 'amount':
$this->updateAmount($request, $cart_action_service, $entity_manager, $cart_product_repository, $cart_product_to_cart_repository);
break;
case 'remove':
$this->removeFromCart($request, $cart_action_service, $entity_manager, $cart_product_to_cart_repository);
break;
}
if ($persisted_cart) {
$cart = $cart_action_service->getCart();
$cart_history = new CartHistory();
$cart_history->setCart($persisted_cart)
->setCreateDate(new \DateTime('now'))
->setCartData($cart);
$entity_manager->persist($cart_history);
$entity_manager->flush();
$persisted_cart
->setTotal($cart['total'])
->setTotalFixed($cart['total_fixed'])
->setTotalOtax($cart['total_otax'])
->setTotalOtaxFixed($cart['total_otax_fixed'])
->setTotalTax($cart['total_tax'])
->setTotalTaxFixed($cart['total_tax_fixed']);
$entity_manager->persist($persisted_cart);
$entity_manager->flush();
$cart_product_ = null;
if ($cart_action_service->getPersistedCartProduct($cart_action_service->getCartProductHandle())) {
$cart_product_ = $cart_action_service->getPersistedCartProduct($cart_action_service->getCartProductHandle());
}
$cart_log = new CartLog();
$cart_log->setCreateDate(new \DateTime('now'))
->setCart($persisted_cart)
->setAmount((int)$cart_action_service->getAmount()['value'])
->setCartProduct($cart_product_)
->setCartAction($cart_action_service->getCartAction())
->setTotal($cart['total'])
->setTotalFixed($cart['total_fixed'])
->setTotalOtax($cart['total_otax'])
->setTotalOtaxFixed($cart['total_otax_fixed'])
->setTotalTax($cart['total_tax'])
->setTotalTaxFixed($cart['total_tax_fixed']);
$entity_manager->persist($cart_log);
$entity_manager->flush();
}
// dump($request->getContent());
// dump(json_decode($request->getContent(), true));
// dump(json_decode($request->getContent()));
return new Response('');
}
/**
* @Route("/add", name="cart_add", methods={"POST"})
* @param Request $request
* @param CartActionService $cart_action_service
* @param EntityManagerInterface $entity_manager
*/
public function addToCart(Request $request, CartActionService $cart_action_service, EntityManagerInterface $entity_manager, CartProductRepository $cart_product_repository, CartProductToCartRepository $cart_product_to_cart_repository): void
{
$cart_action_service->setCartActionData($request->getContent());
/* Daten prüfen */
/**
* @var Cart $persisted_cart
*/
$persisted_cart = $cart_action_service->getPersistedCart();
$handle_product = $cart_action_service->getHandleProduct();
$action_data = $cart_action_service->getCartActionData();
$cart = $cart_action_service->getCart();
$connections = [];
if (isset($handle_product['connections']) && is_array($handle_product['connections']) && !empty($handle_product['connections'])) {
$connections = $handle_product['connections'];
}
// Alle notwendigen Daten vorhanden?
if ($persisted_cart && $handle_product) {
// Schauen ob cartProduct schon existiert
/**
* @var CartProduct $persisted_cart_product
*/
$persisted_cart_product = $cart_action_service->getPersistedCartProduct($cart_action_service->getCartProductHandle());
if ($persisted_cart_product) {
// CartProduct muss aktualisiert werden
$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);
// Connections checken
$persisted_connections = $persisted_cart_product->getConnectedCartProducts();
// Gibt es schon Connections?
if (!$persisted_connections->isEmpty()) {
// Gucken ob die aus dem Frontend-Cart so mitgekommen sind?
foreach ($persisted_connections as $persisted_connection) {
if (!isset($connections[$persisted_connection->getCartProductHandle()])) {
// Noch woanders hin connected?
$more_connections = $persisted_connection->getCartProducts();
// Diese Prüfung reicht völlig aus.
if ($more_connections->count() === 1) {
// Wenn Connection nicht noch woanders connected ist, dann weg mit der Zuordnung von CartProductToCart.
$connection_cart_product_to_cart = $cart_product_to_cart_repository->findOneBy(['cart' => $persisted_cart->getId(), 'cartProduct' => $persisted_connection->getId()]);
if ($connection_cart_product_to_cart) {
$entity_manager->remove($connection_cart_product_to_cart);
}
} else {
// Connection Löschen, da im Frontend-Cart nicht mehr vorhanden
$persisted_cart_product->removeConnectedCartProduct($persisted_connection);
}
}
}
}
// gibt_es_neue_connections? wenn_nicht, aktualisieren.
foreach ($connections as $connection) {
$persisted_cart_product_c = $cart_product_repository->findOneBy(['cart_product_handle' => $connection]);
if ($persisted_cart_product_c) {
// Aktualisiere CartProduct_C
$persisted_cart_product->addConnectedCartProduct($persisted_cart_product_c);
$this->updateCartProduct($persisted_cart_product_c, $cart, $cart_action_service->getCartProductAmountInCart($connection), $connection, $persisted_cart, $cart_product_to_cart_repository, $entity_manager);
} else {
// Erstelle CartProduct_C
/**
* @var Product $product
*/
$connection_product = $cart_action_service->getCartProductFromCart($connection);
if ($connection_product !== false) {
$product_ = $cart_action_service->getProductFromConnectionProduct($connection_product);
if ($product_) {
$connected_cart_product = $this->createCartProduct($product_, $persisted_cart, $cart, $cart_action_service->getCartProductAmountInCart($connection), $connection, null, null, false, false, $entity_manager);
$persisted_cart_product->addConnectedCartProduct($connected_cart_product);
}
}
}
}
} else {
/**
* addCartLog
*/
// Erstelle cartProduct
/**
* @var Product $product
*/
$product = $cart_action_service->getProductFromHandleProduct();
if ($product) {
$use_component = false;
$deposit_refund = false;
if (isset($handle_product['useComponent'])) {
$use_component = $handle_product['useComponent'];
}
if (isset($handle_product['depositRefund'])) {
$deposit_refund = $handle_product['depositRefund'];
}
$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);
// Connections
if (isset($handle_product['connections']) && is_array($handle_product['connections']) && !empty($handle_product['connections'])) {
foreach ($handle_product['connections'] as $connection) {
$connection_product = $cart_action_service->getCartProductFromCart($connection);
if ($connection_product !== false) {
$product_ = $cart_action_service->getProductFromConnectionProduct($connection_product);
if ($product_) {
$connected_cart_product = $this->createCartProduct($product_, $persisted_cart, $cart, $cart_action_service->getCartProductAmountInCart($connection), $connection, null, null, false, false, $entity_manager);
$cart_product->addConnectedCartProduct($connected_cart_product);
}
}
}
}
}
}
} else {
// TODO: Fehlerbehandlung
}
}
/**
* @Route("/amount", name="cart_update_amount", methods={"POST"})
* @param Request $request
* @param CartActionService $cartActionService
* @param EntityManagerInterface $entityManager
*/
public function updateAmount(Request $request, CartActionService $cartActionService, EntityManagerInterface $entityManager, CartProductRepository $cartProductRepository, CartProductToCartRepository $cartProductToCartRepository)
{
$cartActionService->setCartActionData($request->getContent());
/* Daten prüfen */
/**
* @var Cart $persistedCart
*/
$persistedCart = $cartActionService->getPersistedCart();
$actionData = $cartActionService->getCartActionData();
$cart = $cartActionService->getCart();
if ($persistedCart) {
// Schauen ob cartProduct schon existiert
/**
* @var CartProduct $persistedCartProduct
*/
$persistedCartProduct = $cartActionService->getPersistedCartProduct($cartActionService->getCartProductHandle());
// dump($cartActionService->getCartProductHandle());
// dump($persistedCartProduct);
if ($persistedCartProduct) {
$this->updateCartProduct($persistedCartProduct, $cart, $cartActionService->getCartProductAmountInCart($persistedCartProduct->getCartProductHandle()), $persistedCartProduct->getCartProductHandle(), $persistedCart, $cartProductToCartRepository, $entityManager);
// Connections checken
$persistedConnections = $persistedCartProduct->getConnectedCartProducts();
// Gibt es schon Connections?
if (!$persistedConnections->isEmpty()) {
// Gucken ob die aus dem Frontend-Cart so mitgekommen sind?
foreach ($persistedConnections as $persistedConnection) {
$this->updateCartProduct($persistedConnection, $cart, $cartActionService->getCartProductAmountInCart($actionData['cart_product_handle']), $persistedConnection->getCartProductHandle(), $persistedCart, $cartProductToCartRepository, $entityManager);
/*
if (!isset($connections[$persistedConnection->getCartProductHandle()])) {
// Noch woanders hin connected?
$cc = $persistedConnection->getCartProducts();
// Diese Prüfung reicht völlig aus.
if ($cc->count() === 1) {
// Wenn Connection nicht noch woanders connected ist, dann weg mit der Zuordnung von CartProductToCart.
$connectionCartProductToCart = $cartProductToCartRepository->findOneBy(['cart' => $persistedCart->getId(), 'cartProduct' => $persistedConnection->getId()]);
if ($connectionCartProductToCart) {
$entityManager->remove($connectionCartProductToCart);
}
} else {
// Connection Löschen, da im Frontend-Cart nicht mehr vorhanden
$persistedCartProduct->removeConnectedCartProduct($persistedConnection);
}
}*/
}
}
}
}
}
/**
* @Route("/remove", name="cart_remove", methods={"POST"})
* @param Request $request
* @param CartActionService $cartActionService
* @param EntityManagerInterface $entityManager
*/
public function removeFromCart(Request $request, CartActionService $cartActionService, EntityManagerInterface $entityManager, CartProductToCartRepository $cartProductToCartRepository)
{
$cartActionService->setCartActionData($request->getContent());
/* Daten prüfen */
/**
* @var Cart $persistedCart
*/
$persistedCart = $cartActionService->getPersistedCart();
if ($persistedCart) {
/**
* @var CartProduct $persistedCartProduct
*/
$persistedCartProduct = $cartActionService->getPersistedCartProduct($cartActionService->getCartProductHandle());
// Connections checken
$persistedConnections = $persistedCartProduct->getConnectedCartProducts();
// Gibt es schon Connections?
if (!$persistedConnections->isEmpty()) {
// Gucken ob die aus dem Frontend-Cart so mitgekommen sind?
foreach ($persistedConnections as $persistedConnection) {
if (!isset($connections[$persistedConnection->getCartProductHandle()])) {
// Noch woanders hin connected?
$cc = $persistedConnection->getCartProducts();
// Diese Prüfung reicht völlig aus.
if ($cc->count() === 1) {
// Wenn Connection nicht noch woanders connected ist, dann weg mit der Zuordnung von CartProductToCart.
$connectionCartProductToCart = $cartProductToCartRepository->findOneBy(['cart' => $persistedCart->getId(), 'cartProduct' => $persistedConnection->getId()]);
if ($connectionCartProductToCart) {
$entityManager->remove($connectionCartProductToCart);
}
} else {
// Connection Löschen, da im Frontend-Cart nicht mehr vorhanden
$persistedCartProduct->removeConnectedCartProduct($persistedConnection);
}
}
}
}
if ($persistedCartProduct) {
$cartProductToCart = $cartProductToCartRepository->findOneBy(['cart' => $persistedCart->getId(), 'cartProduct' => $persistedCartProduct->getId()]);
if ($cartProductToCart) {
$entityManager->remove($cartProductToCart);
}
} else {
/**
* Bevor etwas entfernt werden kann, muss es hinzugefügt worden sein.
* Ein CartProduct wird nie aus der Tabelle entfernt, lediglich die Beziehung zum Cart wird aufgehoben.
* Wenn an dieser Stelle das CartProduct nicht existiert ist das ein Fehler.
*/
// TODO: Fehlerbehandlung
}
} else {
// TODO: Fehlerbehandlung
}
}
/**
* @Route("/load_last", name="cart_load_last", methods={"GET"})
* @param CashboxService $cashboxService
* @param SerializerInterface $serializer
* @return JsonResponse
*/
public function loadLastCart(CashboxService $cashboxService): JsonResponse
{
if ($this->session->has('cashbox')) {
/**
* @var Cashbox $cashbox
*/
$cashbox = $this->session->get('cashbox');
if ($cashboxService->hasLastCart($cashbox)) {
$cart = $cashboxService->getLastCart($cashbox);
if ($cart) {
return $this->json(['_success' => true, 'cartId' => $cart->getId()]);
}
}
}
return $this->json(['_success' => false]);
}
/**
* @Route("/load/{id}", name="cart_load", methods={"GET"})
* @param Cart $cart
*/
public function loadCart(Cart $cart, ProductService $productService, EntityManagerInterface $entity_manager, CartRepository $cart_repository): JsonResponse
{
$cartProductToCarts = $cart->getCartProductToCarts();
$cartProductContainer = [];
$toRemove = [];
$customer = $cart->getCustomer();
$customer_address = $cart->getCustomerAddress();
foreach ($cartProductToCarts as $cartProductToCart) {
$cartProduct = $cartProductToCart->getCartProduct();
$product = $cartProduct->getProduct();
$p['product'] = $productService->buildFrontendProductFromProduct($product, $cartProduct, $customer);
$p['product']['is_connected'] = false;
$p['product']['connections'] = [];
$p['amount'] = [
'value' => $cartProductToCart->getAmount(),
'locked' => $cartProductToCart->getAmountLocked(),
];
$p['discount']['discount_type'] = $cartProduct->getDiscountType();
$p['discount']['discount'] = $cartProduct->getDiscountValue();
$p['cart_product_handle'] = $cartProduct->getCartProductHandle();
$p['deposit'] = [
'deposit' => [],
'hasDeposit' => false,
'depositTotal' => 0
];
$p['followup'] = [
'followUpProductContainer' => [],
];
$connectedCartProducts = $cartProduct->getConnectedCartProducts();
if (!empty($connectedCartProducts)) {
foreach ($connectedCartProducts as $connectedCartProduct) {
$_product = $connectedCartProduct->getProduct();
$_d = $productService->buildFrontendProductFromProduct($_product, $cartProduct, $customer);
if ($_product !== null) {
if ($_product->getDeposit() === true) {
$p['deposit']['hasDeposit'] = true;
$_d['is_connected'] = false;
$_d['connections'] = [];
$p['deposit']['deposit'][] = $_d;
$p['deposit']['depositTotal'] = $p['deposit']['depositTotal'] + $_d['price'];
if ($customer === null || $customer->getB2b() === null || $customer->getB2b() === false) {
$p['deposit']['depositTotal'] = $p['deposit']['depositTotal'] + $_d['price_otax'];
}
} else {
$p['followup']['followUpProductContainer'][] = $_d;
}
$toRemove[$connectedCartProduct->getCartProductHandle()] = $connectedCartProduct->getCartProductHandle();
}
}
}
$cartProductContainer[$cartProduct->getCartProductHandle()] = $p;
}
foreach ($toRemove as $item) {
unset($cartProductContainer[$item]);
}
$cartProductContainer = array_values($cartProductContainer);
$cartComment = ((null === $cart->getComment()) ? "" : $cart->getComment());
$cartName = ((null === $cart->getName()) ? "" : $cart->getName());
$query = $entity_manager->createQueryBuilder()
->update('App:Cart', 'c')
->set('c.status', 0)
->getQuery()
->execute();
$_query = $entity_manager->createQueryBuilder()
->update('App:Cart', 'c')
->set('c.status', ':status')
->where('c.id=:cart_id')
->setParameter('status', 'open')
->setParameter('cart_id', $cart->getId())
->getQuery()
->execute();
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)]);
}
/**
* @Route("/get_comment/{id}", name="cart_get_comment", methods={"GET"})
* @param Cart $cart
*/
public function getComment(Cart $cart)
{
return $this->json(['_success' => true, 'comment' => ((null === $cart->getComment()) ? "" : $cart->getComment()), 'cartId' => $cart->getId()]);
}
/**
* @Route("/save/{id}", name="cart_save", methods={"POST"})
* @param Cart $cart
*/
public function saveCart(Cart $cart, string $name, EntityManagerInterface $entity_manager)
{
$cart->setName($name)
->setSaveDate(new \DateTime('now'))
->setSaved(true);
$entity_manager->persist($cart);
$entity_manager->flush();
$entity_manager->createQueryBuilder()
->update('App:Cart', 'c')
->set('c.status', 0)
->getQuery()
->execute();
return new JsonResponse('', 200);
}
/**
* @Route("/save", name="cart_save_react", methods={"POST"})
* @param Request $request
* @param CartActionService $cart_action_service
* @param EntityManagerInterface $entity_manager
*/
public function saveCartReact(Request $request, CartActionService $cart_action_service, EntityManagerInterface $entity_manager): JsonResponse
{
$cart_action_service->setCartActionData($request->getContent());
$cart = $cart_action_service->getPersistedCart();
$data = $cart_action_service->getCartActionData();
if (null !== $cart) {
$cart->setName($data['name'])
->setSaveDate(new \DateTime('now'))
->setSaved(true);
$entity_manager->persist($cart);
$entity_manager->flush();
$entity_manager->createQueryBuilder()
->update('App:Cart', 'c')
->set('c.status', 0)
->getQuery()
->execute();
return new JsonResponse('Erfolgreich gespeichert', 200);
}
return new JsonResponse('Interner Fehler', 500);
}
/**
* @Route("/add_comment", name="cart_add_comment", methods={"POST"})
* @param Request $request
* @param CartActionService $cartActionService
* @param EntityManagerInterface $entityManager
*/
public function addComment(Request $request, CartActionService $cartActionService, EntityManagerInterface $entityManager): JsonResponse
{
$cartActionService->setCartActionData($request->getContent());
$cart = $cartActionService->getPersistedCart();
$data = $cartActionService->getCartActionData();
if (null !== $cart) {
$cart->setComment($data['comment']);
$entityManager->persist($cart);
$entityManager->flush();
return new JsonResponse('Erfolgreich gespeichert', 200);
}
return new JsonResponse('Interner Fehler', 500);
}
/**
* @Route("/cart_list", name="cart_list", methods={"GET"})
* @return JsonResponse
*/
public function cartList(CartRepository $cartRepository): JsonResponse
{
if ($this->session->has('cashbox')) {
/**
* @var Cashbox $cashbox
*/
$cashbox = $this->session->get('cashbox');
$_cartList = $cartRepository->findBy(['saved' => true, 'location' => $cashbox->getLocation()]);
$cartList = [];
if ($_cartList) {
foreach ($_cartList as $cart) {
$cartList[] = [
'id' => $cart->getId(),
'name' => $cart->getName(),
'save_date' => $cart->getSaveDate()->format("H:i:s"),
'date' => $cart->getSaveDate()->format("d.m.Y"),
'time' => $cart->getSaveDate()->format("H:i:s"),
'y' => $cart->getSaveDate()->format("Y"),
'm' => $cart->getSaveDate()->format("m"),
'd' => $cart->getSaveDate()->format("d"),
'h' => $cart->getSaveDate()->format("H"),
'i' => $cart->getSaveDate()->format("i"),
's' => $cart->getSaveDate()->format("s"),
];
}
return new JsonResponse($cartList, 200);
}
}
return new JsonResponse([], 200);
}
/**
* @Route("/finish/{id}", name="cart_finish", methods={"GET"})
* @param Cart $cart
*/
public function finishCart(Cart $cart, UserRepository $user_repository, ReceiptCustomerAddressRepository $receipt_customer_address_repository, ReceiptCustomerGroupRepository $customer_group_repository, ReceiptCustomerRepository $receipt_customer_repository, ReceiptDiscountRepository $receipt_discount_repository, ReceiptEmployeeGroupRepository $receipt_employee_group_repository, ReceiptEmployeeRepository $receipt_employee_repository, ReceiptLocationRepository $receipt_location_repository, ReceiptPriceGroupRepository $receipt_price_group_repository, ReceiptPriceRepository $receipt_price_repository, ReceiptProductRepository $receipt_product_repository, ReceiptCartProductRepository $receipt_cart_product_repository, ReceiptRepository $receipt_repository, ReceiptScalePriceRepository $receipt_scale_price_repository, ReceiptTaxRepository $receipt_tax_repository, ReceiptUnitRepository $receipt_unit_repository, ReceiptUserRepository $receipt_user_repository, ConfigurationRepository $configuration_repository, CustomerRepository $customer_repository, KassenSichVApiService $kassen_sichv_api_service, FiskalyTransactionRepository $fiskaly_transaction_repository, EntityManagerInterface $entity_manager, BuilderInterface $builder, SvgWriter $svgWriter): JsonResponse
{
$cart->setFinished(true)
->setFinishedDate(new \DateTime('now'));
$entity_manager->persist($cart);
$entity_manager->flush();
$entity_manager->createQueryBuilder()
->update('App:Cart', 'c')
->set('c.status', 0)
->getQuery()
->execute();
$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);
/* $receipt_cart_products = $receipt->getReceiptCartProducts();
$receipt_product_container = [];
foreach ($receipt_cart_products as $receipt_cart_product) {
$receipt_product = $receipt_cart_product->getReceiptProduct();
if ($receipt_product) {
$receipt_tax = $receipt_product->getReceiptTax();
$product = $receipt_product->getProduct();
if ($product && $receipt_tax) {
$receipt_product_ = [];
$receipt_product_['id'] = $receipt_cart_product->getId();
$receipt_product_['receipt_product_id'] = $receipt_product->getId();
$receipt_product_['receipt_product_handle'] = $receipt_cart_product->getId();
$receipt_product_['amount'] = $receipt_cart_product->getAmount();
$receipt_product_['product_id'] = $product->getId();
$receipt_product_['name'] = $receipt_product->getName();
$receipt_product_['model'] = $receipt_product->getModel();
$receipt_product_['price'] = $receipt_product->getPrice() * ((100 + (int)$receipt_tax->getReceiptTax()) / 100);
$receipt_product_['price_otax'] = $receipt_product->getPrice();
$receipt_product_['discount'] = $receipt_cart_product->getDiscountValue();
$receipt_product_['discount_type'] = $receipt_cart_product->getDiscountType();
$receipt_product_['add_date'] = $product->getAddDate();
$receipt_product_['description'] = $receipt_product->getDescription();
$receipt_product_['tax'] = ['id' => $receipt_tax->getId(), 'name' => $receipt_tax->getName(), 'tax' => $receipt_tax->getReceiptTax()];
$product_tags = $product->getProductTags();
foreach ($product_tags as $product_tag) {
$receipt_product_['tags'][] = ['id' => $product_tag->getId(), 'name' => $product_tag->getName()];
}
$stock_container = $product->getProductToStocks();
foreach ($stock_container as $product_to_stock) {
$stock = $product_to_stock->getStock();
if ($stock) {
$location = $stock->getLocation();
if ($location) {
$receipt_product_['stock'][] = ['id' => $product_to_stock->getId(), 'location' => $location->getName(), 'name' => $stock->getName(), 'amount' => $product_to_stock->getAmount()];
}
}
}
$receipt_product_['deposit'] = $receipt_product->getDeposit();
$receipt_product_container[] = $receipt_product_;
}
}
}*/
$receipt_comment = (string)$receipt->getComment();
$this->createReceiptDocument($receipt, $entity_manager);
$transaction_structure = $kassen_sichv_api_service->startTransaction($cart->getCashbox(), $receipt);
if ($transaction_structure->success === true) {
$fiskaly_transaction = $fiskaly_transaction_repository->findOneBy(['transaction_id' => $transaction_structure->getId()]);
if ($fiskaly_transaction !== null) {
// $transaction_structure = $kassen_sichv_api_service->updateRawTransaction($fiskaly_transaction, $receipt);
$transaction_structure = $kassen_sichv_api_service->updateTransaction($fiskaly_transaction, $receipt);
if ($transaction_structure->success === true) {
$kassen_sichv_api_service->finishTransaction($fiskaly_transaction, $receipt);
}
}
}
$tss_data = [
'finish_date' => null,
'finish_date_format' => null,
'finished' => null,
'fiskalyClient' => null,
'fiskalyTss' => null,
'id' => null,
'start_date' => null,
'start_date_format' => null,
'started' => null,
'transaction_id' => null,
'update_date' => null,
'update_date_format' => null,
'updated' => null,
];
$fiskaly_transaction = $fiskaly_transaction_repository->findOneBy(['transaction_id' => $transaction_structure->getId()]);
$qr_code = "";
if ($fiskaly_transaction !== null) {
$tss_data = [
'finish_date' => $fiskaly_transaction->getFinishDate(),
'finish_date_total_format' => $fiskaly_transaction->getFinishDate()->format("d.m.Y H:i:s"),
'finish_date_format' => $fiskaly_transaction->getFinishDate()->format("d.m.Y"),
'finish_time_format' => $fiskaly_transaction->getFinishDate()->format("H:i:s"),
'finished' => $fiskaly_transaction->getFinished(),
'fiskalyClient' => $fiskaly_transaction->getFiskalyClient()->getClientId(),
'fiskalyTss' => $fiskaly_transaction->getFiskalyClient()->getFiskalyTss()->getTssId(),
'id' => $fiskaly_transaction->getId(),
'start_date' => $fiskaly_transaction->getStartDate(),
'start_date_total_format' => $fiskaly_transaction->getStartDate()->format("d.m.Y H:i:s"),
'start_date_format' => $fiskaly_transaction->getStartDate()->format("d.m.Y"),
'start_time_format' => $fiskaly_transaction->getStartDate()->format("H:i:s"),
'started' => $fiskaly_transaction->getStarted(),
'transaction_id' => $fiskaly_transaction->getTransactionId(),
'update_date' => $fiskaly_transaction->getUpdateDate(),
'update_date_total_format' => $fiskaly_transaction->getUpdateDate()->format("d.m.Y H:i:s"),
'update_date_format' => $fiskaly_transaction->getUpdateDate()->format("d.m.Y"),
'update_time_format' => $fiskaly_transaction->getUpdateDate()->format("H:i:s"),
'updated' => $fiskaly_transaction->getUpdated(),
];
$pixel_to_mm_factor = 25.4;
$max_paper_mm = 75; // 80mm receipt
$printer_dpi = 203; //most default Thermal-Printer dpi
$size = ($max_paper_mm / ($pixel_to_mm_factor / $printer_dpi));
$qr_code_result = $builder
->writer($svgWriter)
->size($size)
->margin(0)
->data($fiskaly_transaction->getQrCodeData())
->build();
$qr_code = $qr_code_result->getString();
}
$receipt_data = [
"cart_total" => null,
"cart_total_fixed" => null,
"cart_total_otax" => null,
"cart_total_otax_fixed" => null,
"cart_total_tax" => null,
"cart_total_tax_fixed" => null,
"comment" => null,
"create_date" => $receipt->getCreateDate(),
"create_date_total_format" => $receipt->getCreateDate()->format("d.m.Y H:i:s"),
"create_date_format" => $receipt->getCreateDate()->format("d.m.Y"),
"create_time_format" => $receipt->getCreateDate()->format("H:i:s"),
"customer" => null,
"customerAddress" => null,
"dailyFinancialStatement" => null,
"discount" => null,
"discount_type" => null,
"fiskalyReceiptTypes" => null,
"fiskalyTransactions" => null,
"id" => $receipt->getId(),
"number" => $receipt->getNumber(),
"receipt_transaction_id" => null,
"receiptCartProducts" => null,
"receiptCashbox" => null,
"receiptCustomerAddresses" => null,
"receiptCustomerGroups" => null,
"receiptCustomers" => null,
"receiptDiscounts" => null,
"receiptDocuments" => null,
"receiptEmployee" => null,
"receiptEmployeeGroups" => null,
"receiptLocation" => null,
"receiptPriceGroups" => null,
"receiptPrices" => null,
"receiptProducts" => null,
"receiptScalePrices" => null,
"receiptTaxes" => null,
"receiptUnits" => null,
"receiptUsers" => null,
"status" => null,
"total" => null,
"total_fixed" => null,
"total_otax" => null,
"total_otax_fixed" => null,
"total_tax" => null,
"total_tax_fixed" => null,
"transaction" => null,
"uuid" => null,
];
$receipt_cashbox = $receipt->getReceiptCashbox();
return $this->json([
'_success' => true,
'tss_data' => $tss_data,
'receipt_data' => $receipt_data,
'cashbox' => $receipt_cashbox->getId(),
'qr_code' => $qr_code,
]
);
}
/**
* @Route("/close/{id}", name="cart_close", methods={"GET"})
* @param Cart $cart
*/
public function closeCart(Cart $cart, EntityManagerInterface $entity_manager): void
{
$cart->setClosed(true)
->setCloseDate(new \DateTime('now'));
$entity_manager->persist($cart);
$entity_manager->flush();
$entity_manager->createQueryBuilder()
->update('App:Cart', 'c')
->set('c.status', 0)
->getQuery()
->execute();
}
/**
* @Route("/has_customer", name="cart_has_customer", methods={"POST"})
* @param Request $request
* @param CartActionService $cartActionService
*/
public function cartHasCustomer(Request $request, CartActionService $cartActionService)
{
$cartActionService->setCartActionData($request->getContent());
$cart = $cartActionService->getPersistedCart();
if ($cart !== null) {
$customer = $cart->getCustomer();
if ($customer !== null) {
return $this->json(['_success' => true, 'has_customer' => true]);
}
return $this->json(['_success' => true, 'has_customer' => false]);
}
return $this->json(['_success' => false]);
}
/**
* @param Cart $cart
* @param UserRepository $user_repository
* @param ReceiptCustomerAddressRepository $receipt_customer_address_repository
* @param ReceiptCustomerGroupRepository $receipt_customer_group_repository
* @param ReceiptCustomerRepository $receipt_customer_repository
* @param ReceiptDiscountRepository $receipt_discount_repository
* @param ReceiptPriceGroupRepository $receipt_price_group_repository
* @param ReceiptPriceRepository $receipt_price_repository
* @param ReceiptProductRepository $receipt_product_repository
* @param ReceiptCartProductRepository $receipt_cart_product_repository
* @param ReceiptScalePriceRepository $receipt_scale_price_repository
* @param ReceiptTaxRepository $receipt_tax_repository
* @param ReceiptUnitRepository $receipt_unit_repository
* @param EntityManagerInterface $entity_manager
* @return Receipt
*/
private function buildReceipt(Cart $cart, UserRepository $user_repository, ReceiptCustomerAddressRepository $receipt_customer_address_repository, ReceiptCustomerGroupRepository $receipt_customer_group_repository, ReceiptCustomerRepository $receipt_customer_repository, ReceiptDiscountRepository $receipt_discount_repository, ReceiptPriceGroupRepository $receipt_price_group_repository, ReceiptPriceRepository $receipt_price_repository, ReceiptProductRepository $receipt_product_repository, ReceiptCartProductRepository $receipt_cart_product_repository, ReceiptScalePriceRepository $receipt_scale_price_repository, ReceiptTaxRepository $receipt_tax_repository, ReceiptUnitRepository $receipt_unit_repository, ReceiptRepository $receipt_repository, ConfigurationRepository $configuration_repository, CustomerRepository $customer_repository, EntityManagerInterface $entity_manager): Receipt
{
/**
* addReceiptCartProduct
* setReceiptTransactionId
* setStatus
* setTransaction
*/
$follow_up_is_deposit = 0;
$follow_up_is_deposit_config = $configuration_repository->findOneBy(['config_key' => 'FOLLOW_UP_IS_DEPOSIT', 'config_group' => 'POS']);
if ($follow_up_is_deposit_config !== null) {
$follow_up_is_deposit = (int)$follow_up_is_deposit_config->getConfigValue();
}
$new_receipt_number = 1;
$receipt_number_start = 1;
$receipt_number_start_config = $configuration_repository->findOneBy(['config_key' => 'RECEIPT_NUMBER_START', 'config_group' => 'POS_RECEIPT']);
if ($receipt_number_start_config !== null) {
$receipt_number_start = $receipt_number_start_config->getConfigValue();
$new_receipt_number = $receipt_number_start_config->getConfigValue();
}
$last_receipt = $receipt_repository->findBy([], ['number' => 'DESC'], 1);
if (!empty($last_receipt) && $last_receipt[0]->getNumber() >= $receipt_number_start) {
$new_receipt_number = $last_receipt[0]->getNumber() + 1;
}
$receipt = new Receipt();
$receipt
->setCreateDate(new \DateTime('now'))
->setComment($cart->getComment())
->setDiscount($cart->getDiscount())
->setDiscountType($cart->getDiscountType())
->setCartTotal($cart->getTotal())
->setCartTotalFixed($cart->getTotalFixed())
->setCartTotalOtax($cart->getTotalOtax())
->setCartTotalOtaxFixed($cart->getTotalOtaxFixed())
->setCartTotalTax($cart->getTotalTax())
->setCartTotalTaxFixed($cart->getTotalTaxFixed())
->setNumber($new_receipt_number);
$entity_manager->persist($receipt);
$entity_manager->flush();
// ReceiptCashbox
$cashbox = $cart->getCashbox();
if ($cashbox) {
$receipt->setReceiptCashbox($this->buildReceiptCashbox($cashbox, $receipt, $entity_manager));
}
// ReceiptTransaction
$transaction = $cart->getTransactions()->last();
if ($transaction !== false) {
$receipt->addReceiptTransaction($this->buildReceiptTransaction($transaction, $receipt, $entity_manager));
}
// Customer?
$customer = $cart->getCustomer();
$has_customer = false;
if ($customer) {
$has_customer = true;
} else {
$default_pos_customer = $configuration_repository->findOneBy(['config_key' => 'DEFAULT_POS_CUSTOMER', 'config_group' => 'POS_CUSTOMER']);
if ($default_pos_customer !== null) {
$customer = $customer_repository->findOneBy(['id' => $default_pos_customer]);
if ($customer !== null) {
$has_customer = true;
}
}
}
if ($has_customer) {
$receipt->setCustomer($customer);
$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));
}
$employee = $cart->getEmployee();
if ($employee) {
$receipt->setReceiptEmployee($this->buildReceiptEmployee($employee, $receipt, $user_repository, $entity_manager));
}
$location = $cart->getLocation();
if ($location) {
$receipt->setReceiptLocation($this->buildReceiptLocation($location, $entity_manager));
}
$entity_manager->persist($receipt);
$entity_manager->flush();
foreach ($cart->getCartProductToCarts() as $cart_product_to_cart) {
$cart_product = $cart_product_to_cart->getCartProduct();
$has_follow_up = false;
$is_follow_up = false;
if ($cart_product) {
$product = $cart_product->getProduct();
if ($product) {
$is_follow_up = $this->isFollowUp($product);
$has_follow_up = $this->hasFollowUp($product);
$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);
if ($receipt_product) {
$pricing_structure = $this->priceService->buildProductPrice($product);
$use_pricing_structure = $pricing_structure->getPrice();
if ($has_customer === true && $pricing_structure->isHasCustomerPrices() && isset($pricing_structure->getCustomerPrice()[$customer->getId()])) {
$use_pricing_structure = $pricing_structure->getCustomerPrice()[$customer->getId()];
}
if ($pricing_structure->isHasScalePrices() && isset($pricing_structure->getScalePrice()[$cart_product_to_cart->getAmount()])) {
$scale_pricing_structure = $pricing_structure->getScalePrice()[$cart_product_to_cart->getAmount()];
$use_pricing_structure = $scale_pricing_structure;
if ($has_customer === true && $scale_pricing_structure->isHasCustomerPrices() && isset($scale_pricing_structure->getCustomerPrice()[$customer->getId()])) {
$use_pricing_structure = $scale_pricing_structure->getCustomerPrice()[$customer->getId()];
}
}
$receipt_cart_product = new ReceiptCartProduct();
$receipt_cart_product
->setReceipt($receipt)
->setReceiptProduct($receipt_product)
->setAmount($cart_product_to_cart->getAmount())
->setBasePrice($pricing_structure->getBasePrice()->getPrice())
->setBasePriceFixed($pricing_structure->getBasePrice()->getPriceFixed())
->setBasePriceOtax($pricing_structure->getBasePrice()->getPriceNoTax())
->setBasePriceOtaxFixed($pricing_structure->getBasePrice()->getPriceNoTaxFixed())
->setBaseTotal($pricing_structure->getBasePrice()->getPrice() * $cart_product_to_cart->getAmount())
->setBaseTotalFixed($this->priceService->priceFix($pricing_structure->getBasePrice()->getPrice() * $cart_product_to_cart->getAmount()))
->setBaseTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getBaseTotal(),(float)$receipt_product->getReceiptTax()->getReceiptTax()))
->setBaseTotalOtaxFixed($this->priceService->priceFix($receipt_cart_product->getBaseTotalOtax()))
->setHasDiscount($cart_product->getHasDiscount())
->setPrice($use_pricing_structure->getPrice())
->setPriceFixed($use_pricing_structure->getPriceFixed())
->setPriceOtax($use_pricing_structure->getPriceNoTax())
->setPriceOtaxFixed($use_pricing_structure->getPriceNoTaxFixed())
->setReceipt($receipt)
->setTotal($use_pricing_structure->getPrice() * $cart_product_to_cart->getAmount())
->setTotalFixed($this->priceService->priceFix($use_pricing_structure->getPrice() * $cart_product_to_cart->getAmount()))
->setTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getTotal(),(float)$receipt_product->getReceiptTax()->getReceiptTax()))
->setTotalOtaxFixed($receipt_cart_product->getTotalOtax())
->setCartBasePrice($cart_product->getBasePrice())
->setCartBasePriceFixed($cart_product->getBasePriceFixed())
->setCartBasePriceOtax($cart_product->getBasePriceOtax())
->setCartBasePriceOtaxFixed($cart_product->getBasePriceOtaxFixed())
->setCartBaseTotal($cart_product->getBaseTotal())
->setCartBaseTotalFixed($cart_product->getBaseTotalFixed())
->setCartBaseTotalOtax($cart_product->getBaseTotalOtax())
->setCartBaseTotalOtaxFixed($cart_product->getBaseTotalOtaxFixed())
->setCartHasDiscount($cart_product->getHasDiscount())
->setCartPrice($cart_product->getPrice())
->setCartPriceFixed($cart_product->getPriceFixed())
->setCartPriceOtax($cart_product->getPriceOtax())
->setCartPriceOtaxFixed($cart_product->getPriceOtaxFixed())
->setCartTotal($cart_product->getTotal())
->setCartTotalFixed($cart_product->getTotalFixed())
->setCartTotalOtax($cart_product->getTotalOtax())
->setCartTotalOtaxFixed($cart_product->getTotalOtaxFixed())
->setDiscountValue($cart_product->getDiscountValue())
->setDiscountType($cart_product->getDiscountType())
->setUseComponent($cart_product->getUseComponent())
->setDepositRefund($cart_product->getDepositRefund())
->setReceiptProductHandle($cart_product->getCartProductHandle())
->setHasFollowUp($has_follow_up)
->setIsFollowUp($is_follow_up);
if ($cart_product->getUseComponent() === true) {
$receipt_cart_product
->setPrice($use_pricing_structure->getComponentPrice())
->setPriceFixed($use_pricing_structure->getComponentPriceFixed())
->setBasePrice($pricing_structure->getBasePrice()->getComponentPrice())
->setBasePriceFixed($pricing_structure->getBasePrice()->getComponentPriceFixed())
->setTotal($receipt_cart_product->getPrice() * $cart_product_to_cart->getAmount())
->setTotalFixed($receipt_cart_product->getTotal())
->setBaseTotal($receipt_cart_product->getBasePrice() * $cart_product_to_cart->getAmount())
->setBaseTotalFixed($receipt_cart_product->getBasePriceFixed() * $cart_product_to_cart->getAmount())
->setBasePriceOtax($pricing_structure->getBasePrice()->getComponentPriceNoTax())
->setBasePriceOtaxFixed($pricing_structure->getBasePrice()->getComponentPriceNoTaxFixed())
->setPriceOtax($use_pricing_structure->getComponentPriceNoTax())
->setPriceOtaxFixed($use_pricing_structure->getComponentPriceNoTaxFixed())
->setTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getTotal(),(float)$receipt_product->getReceiptTax()->getReceiptTax()))
->setTotalOtaxFixed($receipt_cart_product->getTotalOtax())
->setBaseTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getBaseTotal(),(float)$receipt_product->getReceiptTax()->getReceiptTax()))
->setBaseTotalOtaxFixed($receipt_cart_product->getBaseTotalOtax());
}
//dump($product);
//dump($customer);
if ($product->getDeposit() === true && ($customer === null || $customer->getB2b() === null || $customer->getB2b() === false)) {
$receipt_cart_product
->setPrice($receipt_cart_product->getPriceOtax())
->setPriceFixed($receipt_cart_product->getPriceOtaxFixed())
->setBasePrice($receipt_cart_product->getBasePriceOtax())
->setBasePriceFixed($receipt_cart_product->getBasePriceOtaxFixed())
->setTotal($receipt_cart_product->getPrice() * $cart_product_to_cart->getAmount())
->setTotalFixed($receipt_cart_product->getPriceFixed() * $cart_product_to_cart->getAmount())
->setBaseTotal($receipt_cart_product->getBasePrice() * $cart_product_to_cart->getAmount())
->setBaseTotalFixed($receipt_cart_product->getBasePriceFixed() * $cart_product_to_cart->getAmount());
// dump($receipt_cart_product);
}
if ($follow_up_is_deposit === 1 && $is_follow_up === true && ($customer === null || $customer->getB2b() === null || $customer->getB2b() === false)) {
$receipt_cart_product
->setPrice($receipt_cart_product->getPriceOtax())
->setPriceFixed($receipt_cart_product->getPriceOtaxFixed())
->setBasePrice($receipt_cart_product->getBasePriceOtax())
->setBasePriceFixed($receipt_cart_product->getBasePriceOtaxFixed())
->setTotal($receipt_cart_product->getPrice() * $cart_product_to_cart->getAmount())
->setTotalFixed($receipt_cart_product->getPriceFixed() * $cart_product_to_cart->getAmount())
->setBaseTotal($receipt_cart_product->getBasePrice() * $cart_product_to_cart->getAmount())
->setBaseTotalFixed($receipt_cart_product->getBasePriceFixed() * $cart_product_to_cart->getAmount());
// dump($receipt_cart_product);
}
if ($cart_product->getDepositRefund() === true) {
$receipt_cart_product
->setPrice(0 - $receipt_cart_product->getPrice())
->setPriceFixed(0 - $receipt_cart_product->getPriceFixed())
->setBasePrice(0 - $receipt_cart_product->getBasePrice())
->setBasePriceFixed(0 - $receipt_cart_product->getBasePriceFixed())
->setTotal($receipt_cart_product->getPrice() * $cart_product_to_cart->getAmount())
->setTotalFixed($receipt_cart_product->getPriceFixed() * $cart_product_to_cart->getAmount())
->setBaseTotal($receipt_cart_product->getBasePrice() * $cart_product_to_cart->getAmount())
->setBaseTotalFixed($receipt_cart_product->getBasePriceFixed() * $cart_product_to_cart->getAmount())
->setPriceOtax(0 - $receipt_cart_product->getPriceOtax())
->setPriceOtaxFixed(0 - $receipt_cart_product->getPriceOtaxFixed())
->setTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getTotal(),(float)$receipt_product->getReceiptTax()->getReceiptTax()))
->setTotalOtaxFixed($receipt_cart_product->getTotalOtax())
->setBasePriceOtax(0 - $receipt_cart_product->getBasePriceOtax())
->setBasePriceOtaxFixed(0 - $receipt_cart_product->getBasePriceOtaxFixed())
->setBaseTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getBaseTotal(),(float)$receipt_product->getReceiptTax()->getReceiptTax()))
->setBaseTotalOtaxFixed($receipt_cart_product->getBaseTotalOtax());
}
$receipt_cart_product->setBaseTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getBaseTotal(), (float)$receipt_product->getReceiptTax()->getReceiptTax()));
$receipt_cart_product->setBaseTotalOtaxFixed($this->priceService->priceFix($receipt_cart_product->getBaseTotalOtax()));
$receipt_cart_product->setTotalOtax($this->priceService->removeTax((float)$receipt_cart_product->getTotal(), (float)$receipt_product->getReceiptTax()->getReceiptTax()));
$receipt_cart_product->setTotalOtaxFixed($this->priceService->priceFix($receipt_cart_product->getTotalOtax()));
$entity_manager->persist($receipt_cart_product);
$receipt->addReceiptCartProduct($receipt_cart_product);
$receipt_product->addReceiptCartProduct($receipt_cart_product);
}
}
}
}
$entity_manager->flush();
//Connections
foreach ($cart->getCartProductToCarts() as $cart_product_to_cart) {
$cart_product = $cart_product_to_cart->getCartProduct();
/** Das ist eine Wirklich blöde Stelle. Denn wir müssen uns jetzt das
* ReceiptCartProduct auf Basis des CartProduct holen.
*/
$receipt_cart_product = $receipt_cart_product_repository->findOneBy(['receipt_product_handle' => $cart_product->getCartProductHandle()]);
$connected_cart_products = $cart_product->getConnectedCartProducts();
if (!$connected_cart_products->isEmpty()) {
foreach ($connected_cart_products as $connected_cart_product) {
/** Das ist eine Wirklich blöde Stelle. Denn wir müssen uns jetzt das
* ReceiptCartProduct auf Basis des CartProduct holen.
*/
$connected_receipt_cart_product = $receipt_cart_product_repository->findOneBy(['receipt_product_handle' => $connected_cart_product->getCartProductHandle()]);
if ($connected_receipt_cart_product) {
$receipt_cart_product->addConnectedReceiptCartProduct($connected_receipt_cart_product);
$entity_manager->persist($receipt_cart_product);
}
}
}
}
$entity_manager->flush();
$total = 0;
$total_fixed = 0;
$total_otax = 0;
$total_otax_fixed = 0;
$taxes = ['taxes' => [], 'positions' => [], 'total_otax' => [], 'total' => [], 'total_tax' => []];
foreach ($receipt->getReceiptCartProducts() as $receipt_cart_product) {
$taxes['taxes'][$receipt_cart_product->getReceiptProduct()->getReceiptTax()->getId()] = $receipt_cart_product->getReceiptProduct()->getReceiptTax()->getReceiptTax();
$taxes['positions'][$receipt_cart_product->getReceiptProduct()->getReceiptTax()->getId()][] = $receipt_cart_product->getTotal();
// $total += $receipt_cart_product->getTotal();
// $total_fixed += $receipt_cart_product->getTotalOtaxFixed();
// $total_otax += $receipt_cart_product->getTotalOtax();
// $total_otax_fixed += $receipt_cart_product->getTotalOtaxFixed();
}
// $total_fixed = $this->priceService->priceFix($total);
foreach ($taxes['taxes'] as $mtax_key => $mtax_item) {
$taxes['total'][$mtax_key] = array_sum($taxes['positions'][$mtax_key]);
$taxes['total_otax'][$mtax_key] = $taxes['total'][$mtax_key] / ((100 + $taxes['taxes'][$mtax_key]) / 100);
$taxes['total_otax'][$mtax_key] = $this->priceService->removeTax((float)$taxes['total'][$mtax_key], (float)$taxes['taxes'][$mtax_key]);
$taxes['total_otax'][$mtax_key] = $this->priceService->priceFix($taxes['total_otax'][$mtax_key]);
$taxes['total_tax'][$mtax_key] = $taxes['total'][$mtax_key] - $taxes['total_otax'][$mtax_key];
}
$total = array_sum($taxes['total']);
$total_fixed = $this->priceService->priceFix($total);
$total_otax = array_sum($taxes['total_otax']);
$total_otax_fixed = $this->priceService->priceFix($total_otax);
$total_tax = array_sum($taxes['total_tax']);
$total_tax_fixed = $this->priceService->priceFix($total_tax);
$receipt
->setTotal($total)
->setTotalFixed($total_fixed)
->setTotalOtax($total_otax)
->setTotalOtaxFixed($total_otax_fixed)
->setTotalTax($total_tax)
->setTotalTaxFixed($total_tax_fixed);
$entity_manager->persist($receipt);
$entity_manager->flush();
return $receipt;
}
/**
* @param Employee $employee
* @param Receipt $receipt
* @param UserRepository $user_repository
* @param EntityManagerInterface $entity_manager
* @return ReceiptEmployee
*/
private function buildReceiptEmployee(Employee $employee, Receipt $receipt, UserRepository $user_repository, EntityManagerInterface $entity_manager): ReceiptEmployee
{
$receipt_employee = new ReceiptEmployee();
$receipt_employee->setEmployee($employee)
->setExternalIdentifier($employee->getExternalIdentifier())
->setFamilyName($employee->getFamilyName())
->setFromApi($employee->getFromApi())
->setGivenName($employee->getGivenName())
->setLockPin($employee->getLockPin())
->setStatus($employee->getStatus())
->setTelephone($employee->getTelephone());
$employee_group = $employee->getEmployeeGroup();
if ($employee_group) {
$receipt_employee->setReceiptEmployeeGroup($this->buildReceiptEmployeeGroup($employee->getEmployeeGroup(), $receipt, $entity_manager));
}
$user = $this->getUser();
if ($user) {
$receipt_employee->setReceiptUser($this->buildReceiptUser($user, $receipt, $user_repository, $entity_manager));
}
$entity_manager->persist($receipt_employee);
$entity_manager->flush();
return $receipt_employee;
}
private function buildReceiptEmployeeGroup(EmployeeGroup $employeeGroup, Receipt $receipt, EntityManagerInterface $entityManager): ReceiptEmployeeGroup
{
$receiptEmployeeGroup = new ReceiptEmployeeGroup();
$receiptEmployeeGroup->setComment($employeeGroup->getComment())
->setEmployeeGroup($employeeGroup)
->setName($employeeGroup->getName())
->setReceipt($receipt)
->setStatus($employeeGroup->getStatus());
$entityManager->persist($receiptEmployeeGroup);
$entityManager->flush();
return $receiptEmployeeGroup;
}
private function buildReceiptUser(UserInterface $user, Receipt $receipt, UserRepository $userRepository, EntityManagerInterface $entityManager): ReceiptUser
{
$receiptUser = new ReceiptUser();
$_user = $userRepository->findOneBy(['id' => $user->getId()]);
$receiptUser->setAccountId($user->getAccountId())
->setEmail($user->getEmail())
->setPassword($user->getPassword())
->setRoles($user->getRoles())
// ->setReceipt($receipt)
->setUser($_user);
$entityManager->persist($receiptUser);
$entityManager->flush();
return $receiptUser;
}
/**
* @param Location $location
* @param EntityManagerInterface $entity_manager
* @return ReceiptLocation
*/
private function buildReceiptLocation(Location $location, EntityManagerInterface $entity_manager): ReceiptLocation
{
$receipt_location = new ReceiptLocation();
$receipt_location->setAddressAddition($location->getAddressAddition())
->setAddressCountry($location->getAddressCountry())
->setAddressLocality($location->getAddressLocality())
->setEmail($location->getEmail())
->setFaxNumber($location->getFaxNumber())
->setLocation($location)
->setLogo($location->getLogo())
->setName($location->getName())
->setPostalCode($location->getPostalCode())
->setShowAddressOnReceipt($location->getShowAddressOnReceipt())
->setShowContactOnReceipt($location->getShowContactOnReceipt())
->setStreetAddress($location->getStreetAddress())
->setTelephone($location->getTelephone())
->setWebsite($location->getWebsite());
$entity_manager->persist($receipt_location);
$entity_manager->flush();
return $receipt_location;
}
/**
* @param CartProduct $cart_product
* @param Receipt $receipt
* @param ReceiptCustomerGroupRepository $receipt_customer_group_repository
* @param ReceiptCustomerRepository $receipt_customer_repository
* @param ReceiptDiscountRepository $receipt_discount_repository
* @param ReceiptPriceGroupRepository $receipt_price_group_repository
* @param ReceiptPriceRepository $receipt_price_repository
* @param ReceiptProductRepository $receipt_product_repository
* @param ReceiptScalePriceRepository $receipt_scale_price_repository
* @param ReceiptTaxRepository $receipt_tax_repository
* @param ReceiptUnitRepository $receipt_unit_repository
* @param EntityManagerInterface $entity_manager
* @return ReceiptProduct|null
*/
private function buildReceiptProduct(CartProduct $cart_product, Receipt $receipt, ReceiptCustomerGroupRepository $receipt_customer_group_repository, ReceiptCustomerRepository $receipt_customer_repository, ReceiptDiscountRepository $receipt_discount_repository, ReceiptPriceGroupRepository $receipt_price_group_repository, ReceiptPriceRepository $receipt_price_repository, ReceiptProductRepository $receipt_product_repository, ReceiptScalePriceRepository $receipt_scale_price_repository, ReceiptTaxRepository $receipt_tax_repository, ReceiptUnitRepository $receipt_unit_repository, EntityManagerInterface $entity_manager): ?ReceiptProduct
{
$product = $cart_product->getProduct();
$has_follow_up = false;
$is_follow_up = false;
if ($product) {
$is_follow_up = $this->isFollowUp($product);
$has_follow_up = $this->hasFollowUp($product);
$receipt_product = $receipt_product_repository->findOneBy(['receipt' => $receipt->getId(), 'product' => $product->getId()]);
if (!$receipt_product) {
$receipt_product = new ReceiptProduct();
$receipt_product->setAddDate(new \DateTime('now'))
->setComponentPrice($product->getComponentPrice())
->setContainer($product->getContainer())
->setContainerSize($product->getContainerSize())
->setDeposit($product->getDeposit())
->setDescription($product->getDescription())
->setHandle($product->getHandle())
->setImage($product->getImage())
->setModel($product->getModel())
->setName($product->getName())
->setPrice($product->getPrice())
->setPurchasingPrice($product->getPurchasingPrice())
->setProduct($product)
->setReceipt($receipt)
->setSalesUnitFactor($product->getSalesUnitFactor())
->setStatus($product->getStatus())
->setStorageUnitContainerSize($product->getStorageUnitContainerSize())
->setStorageUnitHeight($product->getStorageUnitHeight())
->setStorageUnitLength($product->getStorageUnitLength())
->setStorageUnitPalletSize($product->getStorageUnitPalletSize())
->setStorageUnitTotalLiters($product->getStorageUnitTotalLiters())
->setStorageUnitVolume($product->getStorageUnitVolume())
->setStorageUnitWeight($product->getStorageUnitWeight())
->setStorageUnitWidth($product->getStorageUnitWidth())
->setHasFollowUp($has_follow_up)
->setIsFollowUp($is_follow_up);
if ($cart_product->getPriceOverride() !== null && $cart_product->getPriceOverride() > 0) {
$receipt_product->setPrice($cart_product->getPriceOverride());
}
$entity_manager->persist($receipt_product);
$entity_manager->flush();
$tax = $product->getTax();
if ($tax) {
$receipt_product->setReceiptTax($this->buildReceiptTax($tax, $receipt, $receipt_tax_repository, $entity_manager));
}
$sales_unit = $product->getSalesUnit();
if ($sales_unit) {
$receipt_product->setReceiptUnit($this->buildReceiptUnit($sales_unit, $receipt, $receipt_unit_repository, $entity_manager));
}
foreach ($product->getPrices() as $price) {
$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));
}
foreach ($product->getScalePrices() as $scale_price) {
$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));
}
$entity_manager->persist($receipt_product);
$entity_manager->flush();
}
return $receipt_product;
}
return null;
}
/**
* @param Tax $tax
* @param Receipt $receipt
* @param ReceiptTaxRepository $receipt_tax_repository
* @param EntityManagerInterface $entity_manager
* @return ReceiptTax
*/
private function buildReceiptTax(Tax $tax, Receipt $receipt, ReceiptTaxRepository $receipt_tax_repository, EntityManagerInterface $entity_manager): ReceiptTax
{
$receipt_tax = $receipt_tax_repository->findOneBy(['receipt' => $receipt->getId(), 'tax' => $tax->getId()]);
if (!$receipt_tax) {
$receipt_tax = new ReceiptTax();
$receipt_tax->setName($tax->getName())
->setReceipt($receipt)
->setReceiptTax($tax->getTax())
->setTax($tax);
$entity_manager->persist($receipt_tax);
$entity_manager->flush();
return $receipt_tax;
}
return $receipt_tax;
}
/**
* @param Unit $unit
* @param Receipt $receipt
* @param ReceiptUnitRepository $receipt_unit_repository
* @param EntityManagerInterface $entity_manager
* @return ReceiptUnit
*/
private function buildReceiptUnit(Unit $unit, Receipt $receipt, ReceiptUnitRepository $receipt_unit_repository, EntityManagerInterface $entity_manager): ReceiptUnit
{
$receipt_unit = $receipt_unit_repository->findOneBy(['receipt' => $receipt->getId(), 'unit' => $unit->getId()]);
if (!$receipt_unit) {
$receipt_unit = new ReceiptUnit();
$receipt_unit->setName($unit->getName())
->setReceipt($receipt)
->setUnit($unit);
$entity_manager->persist($receipt_unit);
$entity_manager->flush();
return $receipt_unit;
}
return $receipt_unit;
}
/**
* @param Price $price
* @param Receipt $receipt
* @param ReceiptPriceRepository $receipt_price_repository
* @param ReceiptCustomerRepository $receipt_customer_repository
* @param ReceiptCustomerGroupRepository $receipt_customer_group_repository
* @param ReceiptDiscountRepository $receipt_discount_repository
* @param ReceiptPriceGroupRepository $receipt_price_group_repository
* @param ReceiptUnitRepository $receipt_unit_repository
* @param EntityManagerInterface $entity_manager
* @return ReceiptPrice|null
*/
private function buildReceiptPrice(Price $price, Receipt $receipt, ReceiptPriceRepository $receipt_price_repository, ReceiptCustomerRepository $receipt_customer_repository, ReceiptCustomerGroupRepository $receipt_customer_group_repository, ReceiptDiscountRepository $receipt_discount_repository, ReceiptPriceGroupRepository $receipt_price_group_repository, ReceiptUnitRepository $receipt_unit_repository, EntityManagerInterface $entity_manager): ?ReceiptPrice
{
$receipt_price = $receipt_price_repository->findOneBy(['receipt' => $receipt->getId(), 'sourcePrice' => $price->getId()]);
if (!$receipt_price) {
$receipt_price = new ReceiptPrice();
$receipt_price->setComponentPrice($price->getComponentPrice())
->setPrice($price->getPrice())
->setReceipt($receipt)
->setSalesUnitFactor($price->getSalesUnitFactor())
->setSourcePrice($price)
->setValidFrom($price->getValidFrom())
->setValidTo($price->getValidTo());
$customer = $price->getCustomer();
if ($customer) {
$receipt_price->setReceiptCustomer($this->buildReceiptCustomer($customer, $receipt, $receipt_customer_repository, $receipt_customer_group_repository, $receipt_discount_repository, $receipt_price_group_repository, $entity_manager));
}
$price_group = $price->getPriceGroup();
if ($price_group) {
$receipt_price->setReceiptPriceGroup($this->buildReceiptPriceGroup($price_group, $receipt, $receipt_price_group_repository, $entity_manager));
}
$sales_unit = $price->getSalesUnit();
if ($sales_unit) {
$receipt_price->setReceiptUnit($this->buildReceiptUnit($sales_unit, $receipt, $receipt_unit_repository, $entity_manager));
}
$entity_manager->persist($receipt_price);
// $entity_manager->flush();
}
return $receipt_price;
}
/**
* @param ScalePrice $scale_price
* @param Receipt $receipt
* @param ReceiptScalePriceRepository $receipt_scale_price_repository
* @param ReceiptCustomerRepository $receipt_customer_repository
* @param ReceiptCustomerGroupRepository $receipt_customer_group_repository
* @param ReceiptDiscountRepository $receipt_discount_repository
* @param ReceiptPriceGroupRepository $receipt_price_group_repository
* @param ReceiptUnitRepository $receipt_unit_repository
* @param EntityManagerInterface $entity_manager
* @return ReceiptScalePrice|null
*/
private function buildReceiptScalePrice(ScalePrice $scale_price, Receipt $receipt, ReceiptScalePriceRepository $receipt_scale_price_repository, ReceiptCustomerRepository $receipt_customer_repository, ReceiptCustomerGroupRepository $receipt_customer_group_repository, ReceiptDiscountRepository $receipt_discount_repository, ReceiptPriceGroupRepository $receipt_price_group_repository, ReceiptUnitRepository $receipt_unit_repository, EntityManagerInterface $entity_manager): ?ReceiptScalePrice
{
$receipt_scale_price = $receipt_scale_price_repository->findOneBy(['receipt' => $receipt->getId(), 'scalePrice' => $scale_price->getId()]);
if (!$receipt_scale_price) {
$receipt_scale_price = new ReceiptScalePrice();
$receipt_scale_price->setComponentPrice($scale_price->getComponentPrice())
->setPrice($scale_price->getPrice())
->setReceipt($receipt)
->setSalesUnitFactor($scale_price->getSalesUnitFactor())
->setScalePrice($scale_price)
->setValidFrom($scale_price->getValidFrom())
->setValidTo($scale_price->getValidTo())
->setQuantity($scale_price->getQuantity());
$customer = $scale_price->getCustomer();
if ($customer) {
$receipt_scale_price->setReceiptCustomer($this->buildReceiptCustomer($customer, $receipt, $receipt_customer_repository, $receipt_customer_group_repository, $receipt_discount_repository, $receipt_price_group_repository, $entity_manager));
}
$price_group = $scale_price->getPriceGroup();
if ($price_group) {
$receipt_scale_price->setReceiptPriceGroup($this->buildReceiptPriceGroup($price_group, $receipt, $receipt_price_group_repository, $entity_manager));
}
$sales_unit = $scale_price->getSalesUnit();
if ($sales_unit) {
$receipt_scale_price->setReceiptUnit($this->buildReceiptUnit($sales_unit, $receipt, $receipt_unit_repository, $entity_manager));
}
$entity_manager->persist($receipt_scale_price);
// $entity_manager->flush();
}
return $receipt_scale_price;
}
/**
* @param Cashbox $cashbox
* @param Receipt $receipt
* @param EntityManagerInterface $entity_manager
* @return ReceiptCashbox
*/
private function buildReceiptCashbox(Cashbox $cashbox, Receipt $receipt, EntityManagerInterface $entity_manager): ReceiptCashbox
{
$receipt_cashbox = new ReceiptCashbox();
$receipt_cashbox
->addReceipt($receipt)
->setCashbox($cashbox)
->setComment($cashbox->getComment())
->setLocked($cashbox->getLocked())
->setName($cashbox->getName())
->setSerialNumber($cashbox->getSerialNumber())
->setSnapDate(new \DateTime('now'));
$entity_manager->persist($receipt_cashbox);
// $entity_manager->flush();
return $receipt_cashbox;
}
private function buildReceiptCustomer(Customer $customer, Receipt $receipt, ReceiptCustomerRepository $receiptCustomerRepository, ReceiptCustomerGroupRepository $receiptCustomerGroupRepository, ReceiptDiscountRepository $receiptDiscountRepository, ReceiptPriceGroupRepository $receiptPriceGroupRepository, EntityManagerInterface $entityManager): ?ReceiptCustomer
{
$receiptCustomer = $receiptCustomerRepository->findOneBy(['receipt' => $receipt->getId(), 'customer' => $customer->getId()]);
if (!$receiptCustomer) {
$receiptCustomer = new ReceiptCustomer();
$receiptCustomer->setCreateDate($customer->getCreateDate())
->setCustomer($customer)
->setEmail($customer->getEmail())
->setFamilyName($customer->getFamilyName())
->setGivenName($customer->getGivenName())
->setReceipt($receipt)
->setVat($customer->getVat())
->setB2b($customer->getB2b())
->setUuid($customer->getUuid());
$customerGroup = $customer->getCustomerGroup();
if ($customerGroup) {
$receiptCustomer->setReceiptCustomerGroup($this->buildReceiptCustomerGroup($customerGroup, $receipt, $receiptCustomerGroupRepository, $receiptDiscountRepository, $receiptPriceGroupRepository, $entityManager));
}
$discount = $customer->getDiscount();
if ($discount) {
$receiptCustomer->setReceiptDiscount($this->buildReceiptDiscount($discount, $receipt, $receiptDiscountRepository, $entityManager));
}
$priceGroup = $customer->getPriceGroup();
if ($priceGroup) {
$receiptCustomer->setReceiptPriceGroup($this->buildReceiptPriceGroup($priceGroup, $receipt, $receiptPriceGroupRepository, $entityManager));
}
// $receiptCustomer->addReceiptCustomerAddress();
// $receiptCustomer->addReceiptPrice();
// $receiptCustomer->addReceiptScalePrice();
$entityManager->persist($receiptCustomer);
// $entityManager->flush();
}
return $receiptCustomer;
}
/**
* @param Customer $customer
* @param Receipt $receipt
* @param ReceiptCustomerRepository $receipt_customer_repository
* @param ReceiptCustomerGroupRepository $receipt_customer_group_repository
* @param ReceiptDiscountRepository $receipt_discount_repository
* @param ReceiptPriceGroupRepository $receipt_price_group_repository
* @param ReceiptCustomerAddressRepository $receipt_customer_address_repository
* @param ReceiptPriceRepository $receipt_price_repository
* @param ReceiptUnitRepository $receipt_unit_repository
* @param ReceiptScalePriceRepository $receipt_scale_price_repository
* @param EntityManagerInterface $entity_manager
* @return ReceiptCustomer|null
*/
private function buildFullReceiptCustomer(Customer $customer, Receipt $receipt, ReceiptCustomerRepository $receipt_customer_repository, ReceiptCustomerGroupRepository $receipt_customer_group_repository, ReceiptDiscountRepository $receipt_discount_repository, ReceiptPriceGroupRepository $receipt_price_group_repository, ReceiptCustomerAddressRepository $receipt_customer_address_repository, ReceiptPriceRepository $receipt_price_repository, ReceiptUnitRepository $receipt_unit_repository, ReceiptScalePriceRepository $receipt_scale_price_repository, EntityManagerInterface $entity_manager): ?ReceiptCustomer
{
$receipt_customer = $receipt_customer_repository->findOneBy(['receipt' => $receipt->getId(), 'customer' => $customer->getId()]);
if (!$receipt_customer) {
$receipt_customer = new ReceiptCustomer();
$receipt_customer->setCreateDate($customer->getCreateDate())
->setCustomer($customer)
->setEmail($customer->getEmail())
->setFamilyName($customer->getFamilyName())
->setGivenName($customer->getGivenName())
->setReceipt($receipt)
->setVat($customer->getVat())
->setB2b($customer->getB2b())
->setUuid($customer->getUuid());
$entity_manager->persist($receipt_customer);
$entity_manager->flush();
$customer_group = $customer->getCustomerGroup();
if ($customer_group) {
$receipt_customer->setReceiptCustomerGroup($this->buildReceiptCustomerGroup($customer_group, $receipt, $receipt_customer_group_repository, $receipt_discount_repository, $receipt_price_group_repository, $entity_manager));
}
$discount = $customer->getDiscount();
if ($discount) {
$receipt_customer->setReceiptDiscount($this->buildReceiptDiscount($discount, $receipt, $receipt_discount_repository, $entity_manager));
}
$price_group = $customer->getPriceGroup();
if ($price_group) {
$receipt_customer->setReceiptPriceGroup($this->buildReceiptPriceGroup($price_group, $receipt, $receipt_price_group_repository, $entity_manager));
}
$entity_manager->persist($receipt_customer);
$entity_manager->flush();
}
foreach ($customer->getCustomerAddresses() as $customer_address) {
$receipt_customer->addReceiptCustomerAddress($this->buildReceiptCustomerAddress($customer_address, $receipt, $receipt_customer_address_repository, $entity_manager));
}
foreach ($customer->getPrices() as $price) {
$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));
}
foreach ($customer->getScalePrices() as $scale_price) {
$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));
}
$entity_manager->persist($receipt_customer);
$entity_manager->flush();
return $receipt_customer;
}
private function buildReceiptCustomerAddress(CustomerAddress $customerAddress, Receipt $receipt, ReceiptCustomerAddressRepository $receiptCustomerAddressRepository, EntityManagerInterface $entityManager): ?ReceiptCustomerAddress
{
$receiptCustomerAddress = $receiptCustomerAddressRepository->findOneBy(['receipt' => $receipt->getId(), 'customerAddress' => $customerAddress->getId()]);
if (!$receiptCustomerAddress) {
$receiptCustomerAddress = new ReceiptCustomerAddress();
$receiptCustomerAddress
->setAddressAddition($customerAddress->getAddressAddition())
->setAddressCountry($customerAddress->getAddressCountry())
->setAddressLocality($customerAddress->getAddressLocality())
->setAddressSuburb($customerAddress->getAddressSuburb())
->setCompany($customerAddress->getCompany())
->setCompanyDepartment($customerAddress->getCompanyDepartment())
->setCreateDate(new \DateTime('now'))
->setCustomerAddress($customerAddress)
->setDateOfBirth($customerAddress->getDateOfBirth())
->setExternalIdentifier($customerAddress->getExternalIdentifier())
->setFamilyName($customerAddress->getFamilyName())
->setFaxNumber($customerAddress->getFaxNumber())
->setGender($customerAddress->getGender())
->setGivenName($customerAddress->getGivenName())
->setMobilephone($customerAddress->getMobilephone())
->setPostalCode($customerAddress->getPostalCode())
->setReceipt($receipt)
->setStreetAddress($customerAddress->getStreetAddress())
->setTelephone($customerAddress->getTelephone())
->setTitle($customerAddress->getTitle())
->setType($customerAddress->getType());
$entityManager->persist($receiptCustomerAddress);
// $entityManager->flush();
}
return $receiptCustomerAddress;
}
private function buildReceiptPriceGroup(PriceGroup $priceGroup, Receipt $receipt, ReceiptPriceGroupRepository $receiptPriceGroupRepository, EntityManagerInterface $entityManager): ?ReceiptPriceGroup
{
$receiptPriceGroup = $receiptPriceGroupRepository->findOneBy(['receipt' => $receipt->getId(), 'priceGroup' => $priceGroup->getId()]);
if (!$receiptPriceGroup) {
$receiptPriceGroup = new ReceiptPriceGroup();
$receiptPriceGroup->setCreateDate(new \DateTime('now'))
->setName($priceGroup->getName())
->setPriceGroup($priceGroup)
->setReceipt($receipt);
$entityManager->persist($receiptPriceGroup);
// $entityManager->flush();
}
return $receiptPriceGroup;
}
private function buildReceiptCustomerGroup(CustomerGroup $customerGroup, Receipt $receipt, ReceiptCustomerGroupRepository $receiptCustomerGroupRepository, ReceiptDiscountRepository $receiptDiscountRepository, ReceiptPriceGroupRepository $receiptPriceGroupRepository, EntityManagerInterface $entityManager): ?ReceiptCustomerGroup
{
$receiptCustomerGroup = $receiptCustomerGroupRepository->findOneBy(['receipt' => $receipt->getId(), 'customerGroup' => $customerGroup->getId()]);
if (!$receiptCustomerGroup) {
$receiptCustomerGroup = new ReceiptCustomerGroup();
$receiptCustomerGroup->setCustomerGroup($customerGroup)
->setName($customerGroup->getName())
->setReceipt($receipt);
$discount = $customerGroup->getDiscount();
if ($discount) {
$receiptCustomerGroup->setReceiptDiscount($this->buildReceiptDiscount($discount, $receipt, $receiptDiscountRepository, $entityManager));
}
$priceGroup = $customerGroup->getPriceGroup();
if ($priceGroup) {
$receiptCustomerGroup->setReceiptPriceGroup($this->buildReceiptPriceGroup($priceGroup, $receipt, $receiptPriceGroupRepository, $entityManager));
}
$entityManager->persist($receiptCustomerGroup);
// $entityManager->flush();
}
return $receiptCustomerGroup;
}
private function buildReceiptDiscount(Discount $discount, Receipt $receipt, ReceiptDiscountRepository $receiptDiscountRepository, EntityManagerInterface $entityManager): ?ReceiptDiscount
{
$receiptDiscount = $receiptDiscountRepository->findOneBy(['receipt' => $receipt, 'discount' => $discount->getId()]);
if (!$receiptDiscount) {
$receiptDiscount = new ReceiptDiscount();
$receiptDiscount->setDiscount($discount)
->setName($discount->getName())
->setReceipt($receipt)
->setType($discount->getType())
->setValue($discount->getValue());
$entityManager->persist($receiptDiscount);
// $entityManager->flush();
}
return $receiptDiscount;
}
private function updateCartProduct(CartProduct $cartProduct, array $cart, $amount, string $cartProductHandle, Cart $persistedCart, CartProductToCartRepository $cartProductToCartRepository, EntityManagerInterface $entityManager)
{
$cartProduct
->setBasePrice($cart['products'][$cartProductHandle]['base_price'])
->setBasePriceFixed($cart['products'][$cartProductHandle]['base_price_fixed'])
->setBasePriceOtax($cart['products'][$cartProductHandle]['base_price_otax'])
->setBasePriceOtaxFixed($cart['products'][$cartProductHandle]['base_price_otax_fixed'])
->setBaseTotal($cart['products'][$cartProductHandle]['base_total'])
->setBaseTotalFixed($cart['products'][$cartProductHandle]['base_total_fixed'])
->setBaseTotalOtax($cart['products'][$cartProductHandle]['base_total_otax'])
->setBaseTotalOtaxFixed($cart['products'][$cartProductHandle]['base_total_otax_fixed'])
->setHasDiscount($cart['products'][$cartProductHandle]['has_discount'])
->setPrice($cart['products'][$cartProductHandle]['price'])
->setPriceFixed($cart['products'][$cartProductHandle]['price_fixed'])
->setPriceOtax($cart['products'][$cartProductHandle]['price_otax'])
->setPriceOtaxFixed($cart['products'][$cartProductHandle]['price_otax_fixed'])
->setTotal($cart['products'][$cartProductHandle]['total'])
->setTotalFixed($cart['products'][$cartProductHandle]['total_fixed'])
->setTotalOtax($cart['products'][$cartProductHandle]['total_otax'])
->setTotalOtaxFixed($cart['products'][$cartProductHandle]['total_otax_fixed']);
if (isset($cart['products'][$cartProductHandle]['product']['override_price'])) {
$cartProduct->setPriceOverride($cart['products'][$cartProductHandle]['product']['override_price']);
} else {
$cartProduct->setPriceOverride(null);
}
$entityManager->persist($cartProduct);
$entityManager->flush();
// Liegt es schon im Cart?
$cartProductToCart = $cartProductToCartRepository->findOneBy(['cart' => $persistedCart->getId(), 'cartProduct' => $cartProduct->getId()]);
if (!$cartProductToCart) {
$cartProductToCart = new CartProductToCart();
$cartProductToCart->setCart($persistedCart)
->setCartProduct($cartProduct);
}
$cartProductToCart->setAmount($amount['value'])
->setAmountLocked($amount['locked']);
$entityManager->persist($cartProductToCart);
$entityManager->flush();
}
private function createCartProduct(Product $product, Cart $persistedCart, array $cart, $amount, string $cartProductHandle, $discountValue, $discountType, bool $useComponent, bool $depositRefund, EntityManagerInterface $entityManager): CartProduct
{
$_cartProduct = new CartProduct();
$_cartProduct
->setProduct($product)
->setAddDate(new \DateTime('now'))
->setCart($persistedCart)
->setDiscountValue($discountValue)
->setDiscountType($discountType)
->setCartProductHandle($cartProductHandle)
->setBasePrice($cart['products'][$cartProductHandle]['base_price'])
->setBasePriceFixed($cart['products'][$cartProductHandle]['base_price_fixed'])
->setBasePriceOtax($cart['products'][$cartProductHandle]['base_price_otax'])
->setBasePriceOtaxFixed($cart['products'][$cartProductHandle]['base_price_otax_fixed'])
->setBaseTotal($cart['products'][$cartProductHandle]['base_total'])
->setBaseTotalFixed($cart['products'][$cartProductHandle]['base_total_fixed'])
->setBaseTotalOtax($cart['products'][$cartProductHandle]['base_total_otax'])
->setBaseTotalOtaxFixed($cart['products'][$cartProductHandle]['base_total_otax_fixed'])
->setHasDiscount($cart['products'][$cartProductHandle]['has_discount'])
->setPrice($cart['products'][$cartProductHandle]['price'])
->setPriceFixed($cart['products'][$cartProductHandle]['price_fixed'])
->setPriceOtax($cart['products'][$cartProductHandle]['price_otax'])
->setPriceOtaxFixed($cart['products'][$cartProductHandle]['price_otax_fixed'])
->setTotal($cart['products'][$cartProductHandle]['total'])
->setTotalFixed($cart['products'][$cartProductHandle]['total_fixed'])
->setTotalOtax($cart['products'][$cartProductHandle]['total_otax'])
->setTotalOtaxFixed($cart['products'][$cartProductHandle]['total_otax_fixed'])
->setUseComponent($useComponent)
->setDepositRefund($depositRefund);
if (isset($cart['products'][$cartProductHandle]['product']['override_price'])) {
$_cartProduct->setPriceOverride($cart['products'][$cartProductHandle]['product']['override_price']);
} else {
$_cartProduct->setPriceOverride(null);
}
$entityManager->persist($_cartProduct);
$entityManager->flush();
$cartProductToCart = new CartProductToCart();
$cartProductToCart->setCart($persistedCart)
->setCartProduct($_cartProduct)
->setAmount($amount['value'])
->setAmountLocked($amount['locked']);
$entityManager->persist($cartProductToCart);
$entityManager->flush();
return $_cartProduct;
}
/**
* @param Receipt $receipt
* @param EntityManagerInterface $entity_manager
* @return void
*/
private function createReceiptDocument(Receipt $receipt, EntityManagerInterface $entity_manager)
{
$receipt_cart_product_to_receipt_document_position = [];
$receipt_document = new ReceiptDocument();
$receipt_cart_products = $receipt->getReceiptCartProducts();
foreach ($receipt_cart_products as $receipt_cart_product) {
/*
$has_connection = false;
$is_connected = false;
$r___ = $receipt_cart_product->getConnectedReceiptCartProducts();
if ($r___ !== null) {
$has_connection = true;
}
$r___ = $receipt_cart_product->getReceiptCartProducts();
if ($r___ !== null) {
$is_connected = true;
}
*/
$receipt_product = $receipt_cart_product->getReceiptProduct();
$receipt_document_position = new ReceiptDocumentPosition();
$receipt_document_position
->setAmount($receipt_cart_product->getAmount())
->setDepositRefund($receipt_cart_product->getDepositRefund())
->setDiscountType($receipt_cart_product->getDiscountType())
->setDiscountValue($receipt_cart_product->getDiscountValue())
->setHasDiscount($receipt_cart_product->getHasDiscount())
->setPrice($receipt_cart_product->getPrice())
->setPriceFixed($receipt_cart_product->getPriceFixed())
->setPriceOtax($receipt_cart_product->getPriceOtax())
->setPriceOtaxFixed($receipt_cart_product->getPriceOtaxFixed())
->setProduct($receipt_cart_product->getReceiptProduct()->getProduct())
->setTotal($receipt_cart_product->getTotal())
->setTotalFixed($receipt_cart_product->getTotalFixed())
->setTotalOtax($receipt_cart_product->getTotalOtax())
->setTotalOtaxFixed($receipt_cart_product->getTotalOtaxFixed())
->setUseComponent($receipt_cart_product->getUseComponent())
->setDeposit($receipt_product->getDeposit())
->setHasFollowUp($receipt_cart_product->getHasFollowUp())
->setIsFollowUp($receipt_cart_product->getIsFollowUp());
$entity_manager->persist($receipt_document_position);
$receipt_document->addReceiptDocumentPosition($receipt_document_position);
$receipt_cart_product_to_receipt_document_position[$receipt_cart_product->getId()] = compact('receipt_cart_product', 'receipt_document_position');
}
foreach ($receipt_cart_product_to_receipt_document_position as $key => $item) {
/**
* @var ReceiptCartProduct $receipt_cart_product_
*/
$receipt_cart_product_ = $item['receipt_cart_product'];
/**
* @var ReceiptDocumentPosition $receipt_document_position_
*/
$receipt_document_position_ = $item['receipt_document_position'];
$connected_receipt_cart_products = $receipt_cart_product_->getConnectedReceiptCartProducts();
foreach ($connected_receipt_cart_products as $connected_receipt_cart_product) {
$receipt_document_position_->addConnectedReceiptDocumentPosition($receipt_cart_product_to_receipt_document_position[$connected_receipt_cart_product->getId()]['receipt_document_position']);
}
}
$customer = $receipt->getCustomer();
$customer_address = $receipt->getCustomerAddress();
if ($customer === null && $customer_address !== null) {
$customer = $customer_address->getCustomer();
}
if ($customer !== null) {
$receipt_document_customer = new ReceiptDocumentCustomer();
$receipt_document_customer
->setCreateDate(new \DateTime('now'))
->setCustomer($customer)
->setEmail($customer->getEmail())
->setFamilyName($customer->getFamilyName())
->setGivenName($customer->getGivenName())
->setVat($customer->getVat())
->setB2b($customer->getB2b());
$entity_manager->persist($receipt_document_customer);
$receipt_document->addReceiptDocumentCustomer($receipt_document_customer);
}
if ($customer_address !== null) {
$receipt_document_customer_address = new ReceiptDocumentCustomerAddress();
$receipt_document_customer_address
->setAddressAddition($customer_address->getAddressAddition())
->setAddressCountry($customer_address->getAddressCountry())
->setAddressLocality($customer_address->getAddressLocality())
->setAddressSuburb($customer_address->getAddressSuburb())
->setCompany($customer_address->getCompany())
->setCompanyDepartment($customer_address->getCompanyDepartment())
->setCreateDate($customer_address->getCreateDate())
->setDateOfBirth($customer_address->getDateOfBirth())
->setExternalIdentifier($customer_address->getExternalIdentifier())
->setFamilyName($customer_address->getFamilyName())
->setFaxNumber($customer_address->getFaxNumber())
->setGender($customer_address->getGender())
->setMobilephone($customer_address->getMobilephone())
->setPostalCode($customer_address->getPostalCode())
->setStreetAddress($customer_address->getStreetAddress())
->setTelephone($customer_address->getTelephone())
->setTitle($customer_address->getTitle())
->setType($customer_address->getType());
if ($customer !== null && isset($receipt_document_customer)) {
$receipt_document_customer_address->setReceiptDocumentCustomer($receipt_document_customer);
}
$entity_manager->persist($receipt_document_customer_address);
}
$receipt_document
->setComment($receipt->getComment())
->setCreateDate($receipt->getCreateDate())
->setDiscount($receipt->getDiscount())
->setDiscountType($receipt->getDiscountType())
->setReceipt($receipt)
->setTotal($receipt->getTotal())
->setTotalFixed($receipt->getTotalFixed())
->setTotalOtax($receipt->getTotalOtax())
->setTotalOtaxFixed($receipt->getTotalOtaxFixed())
->setTotalTax($receipt->getTotalTax())
->setTotalTaxFixed($receipt->getTotalTaxFixed());
$entity_manager->persist($receipt_document);
$entity_manager->flush();
}
private function hasFollowUp(Product $product): bool
{
$follow_up_products = $product->getFollowUpProducts();
return $follow_up_products->isEmpty() === false;
}
private function isFollowUp(Product $product): bool
{
$follow_up_products = $product->getFollowUpProductFrom();
return $follow_up_products->isEmpty() === false;
}
private function buildReceiptTransaction(Transaction $transaction, Receipt $receipt, EntityManagerInterface $entity_manager): ReceiptTransaction
{
$receipt_transaction = new ReceiptTransaction();
$receipt_transaction
->setReceipt($receipt)
->setReceiptPaymentMethod($this->buildReceiptPaymentMethod($transaction->getPaymentMethod(), $receipt, $entity_manager))
->setToPay($transaction->getToPay())
->setGivenCash($transaction->getGivenCash())
->setChangeCash($transaction->getChangeCash())
->setTransactionDate($transaction->getTransactionDate())
->setTransaction($transaction);
$entity_manager->persist($receipt_transaction);
// $entity_manager->flush();
return $receipt_transaction;
}
private function buildReceiptPaymentMethod(PaymentMethod $payment_method, Receipt $receipt, EntityManagerInterface $entity_manager): ReceiptPaymentMethod
{
$receipt_payment_method = new ReceiptPaymentMethod();
$receipt_payment_method
->setName($payment_method->getName())
->setCash($payment_method->getCash())
->setUuid($payment_method->getUuid())
->setPaymentMethod($payment_method);
$entity_manager->persist($receipt_payment_method);
// $entity_manager->flush();
return $receipt_payment_method;
}
}