src/StartPlatz/Bundle/MemberBundle/Entity/ProductRepository.php line 354

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace App\StartPlatz\Bundle\MemberBundle\Entity;
  3. use App\StartPlatz\Bundle\LogBundle\Entity\Errorlog;
  4. use App\StartPlatz\Bundle\MonsumBundle\Entity\Customer;
  5. use App\StartPlatz\Bundle\SettingBundle\Entity\Space;
  6. use DateTime;
  7. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  8. use App\StartPlatz\Bundle\FibuBundle\Entity\Product as FibuProduct;
  9. use App\StartPlatz\Bundle\FibuBundle\Entity\Position;
  10. use App\StartPlatz\Bundle\MonsumBundle\Entity\Article;
  11. use Doctrine\ORM\QueryBuilder;
  12. use Doctrine\Persistence\ManagerRegistry;
  13. /**
  14.  * ProductRepository
  15.  *
  16.  * This class was generated by the Doctrine ORM. Add your own custom
  17.  * repository methods below.
  18.  */
  19. class ProductRepository extends ServiceEntityRepository
  20. {
  21.     public function __construct(ManagerRegistry $managerRegistry)
  22.     {
  23.         parent::__construct($managerRegistryProduct::class /*Product Member*/);
  24.     }
  25.     public function isPurchaseTemplateSet(Product $product)
  26.     {
  27.         $em $this->getEntityManager();
  28.         if (!$product->getPurchaseTemplate()) {
  29.             $template = [
  30.                 'stepOneTitle'    => "Produkt prüfen",
  31.                 'backgroundImage' => "https://res.cloudinary.com/startplatz/image/upload/v1588517648/header/STARTPLATZ_MEDIAPARK.jpg",
  32.                 'stepTwoTitle'    => "Checkout",
  33.                 'receiptTitle'    => "Quittung / Receipt",
  34.                 'receiptText'     => "Ihr Einkauf war erfolgreich. // Your purchase was successful",
  35.             ];
  36.             $product->setPurchaseTemplate(json_encode($template));
  37.             $em->persist($product);
  38.             $em->flush();
  39.         }
  40.         return $product;
  41.     }
  42.     public function findPaginated($criteria = [], $order = [], $page 1$limit 5)
  43.     {
  44.         $qb $this->getEntityManager()->createQueryBuilder();
  45.         $qb
  46.             ->select('p')
  47.             ->from(Product::class /*Product Member*/'p')
  48.             ->setFirstResult($limit * ($page 1)) // Offset
  49.             ->setMaxResults($limit// Limit
  50.         ;
  51.         $qb $this->setCriteria($qb$criteria);
  52.         if ($order) {
  53.             foreach ($order as $key => $value) {
  54.                 $qb->orderBy('p.' $key$value);
  55.             }
  56.         } else {
  57.             $qb->addOrderBy('p.lastModified''DESC');
  58.         }
  59.         $query $qb->getQuery();
  60.         $results $query->getResult();
  61.         return $results;
  62.     }
  63.     private function setCriteria(QueryBuilder $qb$criteria)
  64.     {
  65.         foreach($criteria as $field =>$value) {
  66.             switch ($field) {
  67.                 case "partners":
  68.                     $qb->andWhere("p.type IN (:types) ");
  69.                     $qb->setParameter(':types'$value);
  70.                     break;
  71.                 case "accounts":
  72.                     $qb->andWhere("p.account IN (:array) ");
  73.                     $qb->setParameter(':array'$value);
  74.                     break;
  75.                 case "tags":
  76.                     $qb->andWhere('p.'$field ' LIKE :' $field);
  77.                     $qb->setParameter($field"%{$value}%");
  78.                     break;
  79.                 default:
  80.                     $qb->andWhere('p.'$field ' = :' $field);
  81.                     $qb->setParameter($field$value);
  82.                     break;
  83.             }
  84.         }
  85.         return $qb;
  86.     }
  87.     public function countByCriteria($criteria = [])
  88.     {
  89.         $qb $this->getEntityManager()->createQueryBuilder();
  90.         $qb
  91.             ->select('COUNT(p)')
  92.             ->from(Product::class /*Product Member*/'p')
  93.         ;
  94.         $qb $this->setCriteria($qb$criteria);
  95.         return $qb->getQuery()->getSingleScalarResult();
  96.     }
  97.     public function deleteProduct(Product $product)
  98.     {
  99.         $em $this->getEntityManager();
  100.         // if used in entity space set to null
  101.         $em->getRepository(Space::class)->setProductIdToNullIfUsed($product->getId());
  102.         $em->remove($product);
  103.         $em->flush();
  104.         return "Product deleted";
  105.     }
  106.     public function setField($field$action$id)
  107.     {
  108.         $em $this->getEntityManager();
  109.         $field = (in_array($field, ['status']) ? $field 'status');
  110.         if (!$entity $this->findOneBy(['id' => $id])) {
  111.             return 'ERROR: entity not found';
  112.         }
  113.         $method 'set' . ($field);
  114.         $entity->$method($action);
  115.         $entity->setLastModified(new DateTime());
  116.         $em->persist($entity);
  117.         $em->flush();
  118.         return 'field ' $field ' set to ' $action;
  119.     }
  120.     public function updateRelations(Product $product)
  121.     {
  122.         $connection $this->getEntityManager()->getConnection();
  123.         $sql ="UPDATE aaa_sp_services p
  124.               SET p.productType = :type,
  125.                   p.productName = :name
  126.               WHERE p.productId = :productId" ;
  127.         $connection->executeQuery($sql, ['type' => $product->getType(), 'name' => $product->getName(), 'productId' => $product->getId()]);
  128.         $sql ="UPDATE sp_fibu_easybill_positions p
  129.               SET p.allmedaProductType = :type,
  130.                   p.allmedaProductId = :productId
  131.               WHERE p.positionId = :easybillPositionId" ;
  132.         $connection->executeQuery($sql, ['type' => $product->getType(), 'name' => $product->getName(), 'productId' => $product->getId(), 'easybillPositionId' => $product->getEasybillPositionId()]);
  133.         $sql ="UPDATE sp_monsum_items p
  134.               SET p.allmedaProductType = :type
  135.               WHERE p.allmedaProductId = :productId" ;
  136.         $connection->executeQuery($sql, ['type' => $product->getType(), 'name' => $product->getName(), 'productId' => $product->getId(), 'easybillPositionId' => $product->getEasybillPositionId()]);
  137.         return "Services and Easybill positions updated for product {$product->getName()}, Monsum Items updated for allmedaProductId";
  138.     }
  139.     public function setDefaultValues(Product $product)
  140.     {
  141.         $now = new DateTime();
  142.         $product->setStatus('active');
  143.         $product->setBookingAccount('44010');
  144.         $product->setNoticeDays(0);
  145.         return $product;
  146.     }
  147.     public function getSettingsDefault(Product $product)
  148.     {
  149.         return [
  150.             "special-offer" => [
  151.                 "price"         => "",
  152.                 "description"   => "",
  153.                 "name"          => "",
  154.             ],
  155.         ];
  156.     }
  157.     public function setMonsumArticleId(Product $productArticle $article$adminEmail)
  158.     {
  159.         $em $this->getEntityManager();
  160.         $now = new DateTime();
  161.         $product->setMonsumArticleId($article->getArticleId());
  162.         $product->setLastModified($now);
  163.         $product->setLastChangeUser($adminEmail);
  164.         $em->persist($product);
  165.         $em->flush();
  166.         return $product;
  167.     }
  168.     public function createOrUpdateProductByMonsumArticle(Article $article$adminEmail)
  169.     {
  170.         $em $this->getEntityManager();
  171.         $now = new DateTime();
  172.         if (!$product $this->findOneBy(['monsumArticleId' => $article->getArticleId()])) {
  173.             if (!$product $this->findOneBy(['account' => $article->getAccount(),'agent'=>'monsum''productNumber' => $article->getArticleNumber() ])) {
  174.                 $product = new Product();
  175.                 $product->setMonsumArticleId($article->getArticleId());
  176.                 $product->setAccount($article->getAccount());
  177.                 $product->setAgent('monsum');
  178.                 $product->setType('Other');
  179.                 $product->setBookingAccount('44010');
  180.                 $product->setStatus('active');
  181.                 $product->setLocation($em->getRepository(Customer::class)->getLocationByAccount($article->getAccount()));
  182.             } else {
  183.                 // product has been cloned
  184.                 $product->setMonsumArticleId($article->getArticleId());
  185.             }
  186.         }
  187.         $product->setMonsumArticleNumber($article->getArticleNumber());
  188.         $product->setName($article->getTitle());
  189.         $product->setProductNumber($article->getArticleNumber());
  190.         $product->setIsAddon($article->getIsAddon());
  191.         $product->setMonsumSettings(json_encode($em->getRepository(Article::class /*Monsum Article*/)->getMonsumSettingsByArticle($article)));
  192.         $product->setPrice($article->getUnitPrice());
  193.         $product->setDescription($article->getDescription());
  194.         $product->setLastModified($now);
  195.         $product->setLastChangeUser($adminEmail);
  196.         $logText "createOrUpdateProductByMonsumArticle";
  197.         $product->setHistory($this->writeHistory($product$logText$adminEmail));
  198.         $em->persist($product);
  199.         $em->flush();
  200.         return $product;
  201.     }
  202.     private function writeHistory(Product $product$logText$adminEmail){
  203.         $product->setHistory('==== ' date("Y-m-d") . ' by ' $product->getLastChangeUser() . ' ===' PHP_EOL $logText PHP_EOL $product->getHistory());
  204.         return $product;
  205.     }
  206.     public function createOrUpdateProductExceptionByMonsum($settings)
  207.     {
  208.         $em $this->getEntityManager();
  209.         $now = new DateTime();
  210.         $account $settings['account'];
  211.         $articleNumber '99999';
  212.         if (!$product $this->findOneBy(['monsumArticleNumber' => $articleNumber'account' => $account])) {
  213.             $product = new Product();
  214.             $product->setAccount($settings['account']);
  215.             $product->setAgent('monsum');
  216.         }
  217.         $product->setMonsumArticleNumber($articleNumber);
  218.         $product->setName("Exception");
  219.         $product->setProductNumber($product->getMonsumArticleNumber());
  220.         $product->setType('Exception');
  221.         $product->setStatus('active');
  222.         $product->setBookingAccount('44010');
  223.         $product->setDescription("Exception");
  224.         $product->setLastModified($now);
  225.         $product->setLastChangeUser($settings['adminEmail']);
  226.         $em->persist($product);
  227.         $em->flush();
  228.         return $product;
  229.     }
  230.     public function createOrUpdateProductByMonsumSubscriptionPlan($plan$settings)
  231.     {
  232.         $em $this->getEntityManager();
  233.         $now = new DateTime();
  234.         $articleId $plan->ARTICLE_ID;
  235.         if (!$product $this->findOneBy(['monsumArticleId' => $articleId])) {
  236.             $product = new Product();
  237.             $product->setMonsumArticleId($articleId);
  238.             $product->setAccount($settings['account']);
  239.             $product->setAgent('monsum');
  240.             $product->setType('Other');
  241.         }
  242.         $product->setMonsumArticleNumber($plan->ARTICLE_NUMBER);
  243.         $product->setName($plan->TITLE);
  244.         $product->setProductNumber($product->getMonsumArticleNumber());
  245.         $product->setStatus('active');
  246.         $product->setBookingAccount('44010');
  247.         $product->setPrice($plan->UNIT_PRICE);
  248.         $product->setDescription($plan->DESCRIPTION);
  249.         $product->setLastModified($now);
  250.         $product->setLastChangeUser($settings['adminEmail']);
  251.         $logText "from subscription {$plan->ARTICLE_NUMBER} by createOrUpdateProductByMonsumSubscriptionPlan";
  252.         $product->setHistory($this->writeHistory($product$logText$settings['adminEmail']));
  253.         $em->persist($product);
  254.         $em->flush();
  255.         return $product;
  256.     }
  257.     public function createOrUpdateProductByMonsumInvoiceItem($item$settings)
  258.     {
  259.         $em $this->getEntityManager();
  260.         $now = new DateTime();
  261.         if (!$product $this->findOneBy(['monsumArticleNumber' => $item->ARTICLE_NUMBER'account'=>$settings['account']])) {
  262.             $product = new Product();
  263.             $product->setMonsumArticleNumber($item->ARTICLE_NUMBER);
  264.             $product->setAccount($settings['account']);
  265.             $product->setAgent('monsum');
  266.             $product->setType('Other');
  267.         }
  268.         $product->setName($item->DESCRIPTION);
  269.         $product->setProductNumber($product->getMonsumArticleNumber());
  270.         $product->setStatus('active');
  271.         $product->setBookingAccount('44010');
  272.         $product->setPrice($item->UNIT_PRICE);
  273.         $product->setDescription($item->DESCRIPTION);
  274.         $product->setLastModified($now);
  275.         $product->setLastChangeUser($settings['adminEmail']);
  276.         $logText "modified from invoiceItem {$item->INVOICE_ITEM_ID} by createOrUpdateProductByMonsumInvoiceItem";
  277.         $product->setHistory($this->writeHistory($product$logText$settings['adminEmail']));
  278.         $em->persist($product);
  279.         $em->flush();
  280.         return $product;
  281.     }
  282.     /******** easybill create or update starts here ***/
  283.     public function findExistingProduct$positionIdstring $account, ?string $productNumber null): ?Product
  284.     {
  285.         // Immer erst nach PositionId UND Account suchen
  286.         $product $this->findOneBy([
  287.             'easybillPositionId' => $positionId,
  288.             'account' => $account
  289.         ]);
  290.         // Fallback-Suche nach Produktnummer UND Account
  291.         if (!$product && $productNumber) {
  292.             $product $this->findOneBy([
  293.                 'productNumber' => $productNumber,
  294.                 'account' => $account
  295.             ]);
  296.         }
  297.         return $product;
  298.     }
  299.     public function initializeNewProduct(
  300.         string $positionId,
  301.         string $account,
  302.         ?string $productNumber null,
  303.         string $adminEmail
  304.     ): array {
  305.         $product = new Product();
  306.         $product->setEasybillPositionId($positionId);
  307.         $product->setAccount($account);
  308.         $location = match($account) {
  309.             'AI-Hub' => 'AI-Hub',
  310.             'SP-DUS' => 'DUS',
  311.             default => 'CGN'
  312.         };
  313.         $product->setLocation($location);
  314.         $product->setAgent('easybill');
  315.         $product->setType('Other');
  316.         if ($productNumber) {
  317.             $product->setProductNumber($productNumber);
  318.             $product->setPrevNumber($productNumber);
  319.         }
  320.         // Logging und Response
  321.         $activity "SUCCESS: Allmeda Product created {$product->getName()} with type = 'Other' and easybillPositionId={$positionId}";
  322.         $this->getEntityManager()->getRepository(Errorlog::class)->logError(
  323.             $activity,
  324.             "createOrUpdateProductByEasybillProduct",
  325.             $adminEmail,
  326.             "allmedaProduct",
  327.             $product->getId()
  328.         );
  329.         return [
  330.             'product' => $product,
  331.             'response' => $activity
  332.         ];
  333.     }
  334.     public function createOrUpdateProductByEasybillPosition(Position $position$adminEmail)
  335.     {
  336.         $em $this->getEntityManager();
  337.         $now = new DateTime();
  338.         if (!$product $this->findOneBy(['easybillPositionId' => $position->getPositionId()])) {
  339.             $product = new Product();
  340.             $product->setEasybillPositionId($position->getPositionId());
  341.             $product->setAccount($position->getAccount());
  342.             $product->setLocation(($position->getAccount() == 'SP-DUS' 'DUS' 'CGN'));
  343.             $product->setAgent('easybill');
  344.         }
  345.         $product->setStatus('active');
  346.         $product->setBookingAccount($position->getBookingAccount());
  347.         $description mb_substr(preg_replace('/[\x00-\x1F\x80-\xFF]/'''$position->getDescription()), 0255);
  348.         $product->setName($description);
  349.         $product->setPrice($position->getSinglePriceNet());
  350.         $product->setDescription($description);
  351.         $product->setLastModified($now);
  352.         $product->setLastChangeUser($adminEmail);
  353.         $em->persist($product);
  354.         $em->flush();
  355.         return $product;
  356.     }
  357.     /**
  358.      * Aktualisiert ein bestehendes Produkt mit Daten aus einem FibuProduct
  359.      *
  360.      * @param Product $allmedaProduct Das zu aktualisierende Produkt
  361.      * @param FibuProduct $fibuProduct Das Quellprodukt mit den neuen Daten
  362.      * @param string $adminEmail E-Mail für Logging-Zwecke
  363.      * @return array Ergebnis der Aktualisierung
  364.      */
  365.     public function updateExistingProduct(
  366.         Product $allmedaProduct,
  367.         FibuProduct $fibuProduct,
  368.         string $adminEmail
  369.     ): array {
  370.         // Aktualisiere relevante Felder basierend auf $fibuProduct
  371.         // Hier müssen die konkreten Felder ergänzt werden, die aktualisiert werden sollen
  372.         // Beispiel:
  373.         // $allmedaProduct->setName($fibuProduct->getName());
  374.         // $allmedaProduct->setDescription($fibuProduct->getDescription());
  375.         $now = new DateTime();
  376.         $allmedaProduct->setStatus('active');
  377.         $allmedaProduct->setBookingAccount($fibuProduct->getBookingAccount());
  378.         $description mb_substr(preg_replace('/[\x00-\x1F\x80-\xFF]/'''$fibuProduct->getDescription()), 0255);
  379.         $allmedaProduct->setName($description);
  380.         $allmedaProduct->setPrice($fibuProduct->getPrice());
  381.         $allmedaProduct->setVatPercent($fibuProduct->getVatPercent());
  382.         $allmedaProduct->setDescription($description);
  383.         $allmedaProduct->setLastModified($now);
  384.         $allmedaProduct->setLastChangeUser($adminEmail);
  385.         $this->getEntityManager()->persist($allmedaProduct);
  386.         $this->getEntityManager()->flush();
  387.         // Logging
  388.         $activity "Allmeda Product updated: {$allmedaProduct->getName()} with ID={$allmedaProduct->getId()}";
  389.         $this->getEntityManager()->getRepository(Errorlog::class)->logError(
  390.             $activity,
  391.             "updateExistingProduct",
  392.             $adminEmail,
  393.             "allmedaProduct",
  394.             $allmedaProduct->getId()
  395.         );
  396.         return [
  397.             'product' => $allmedaProduct,
  398.             'response' => $activity
  399.         ];
  400.     }
  401.     public function createOrUpdateProductByEasybillApiPosition($item$account$adminEmail)
  402.     {
  403.         $em $this->getEntityManager();
  404.         $now = new DateTime();
  405.         $response '';
  406.         $apiData    $this->getApiData($item);
  407.         $positionId $item->id;
  408.         $price      $item->sale_price /100;  // otherwise we get an input error with numbers > 999
  409.         if (!$product $this->findOneBy(['easybillPositionId' => $positionId'account'=>$account])) {
  410.             if (!$product $this->findOneBy(['productNumber' => $item->number'account'=>$account])) {
  411.                 $product = new Product();
  412.                 $product->setAccount($account);
  413.                 // Determine the location using a switch statement
  414.                 switch ($product->getAccount()) {
  415.                     case 'AI-Hub':
  416.                         $location 'AI-Hub';
  417.                         break;
  418.                     case 'SP-DUS':
  419.                         $location 'DUS';
  420.                         break;
  421.                     default:
  422.                         $location 'CGN'// Default value
  423.                         break;
  424.                 }
  425.                 // Set the location
  426.                 $product->setLocation($location);
  427.                 $product->setAgent('easybill');
  428.                 $product->setType('Other');
  429.                 $product->setName($apiData['name']);
  430.                 $product->setProductNumber($apiData['productNumber']);
  431.                 $product->setPrevNumber($apiData['productNumber']);
  432.                 $product->setEasybillPositionId($positionId);
  433.                 $activity "SUCCESS: created {$product->getName()}, with type = 'Other' and easybillPositionId={$product->getEasybillPositionId()}";
  434.             } else {
  435.                 $product->setEasybillPositionId($positionId);
  436.                 $activity "SUCCESS: updated {$product->getName()}, with easybillPositionId={$product->getEasybillPositionId()}";
  437.             }
  438.             //$em->getRepository(Errorlog::class)->logError($activity, "createOrUpdateProductByEasybillProduct", $adminEmail, "allmedaProduct", $product->getId());
  439.             $response $activity;
  440.         }
  441.         $allmedaData $this->getAllmedaData($product);
  442.         $changes array_diff_assoc($allmedaData$apiData);
  443.         if ($changes) {
  444.             $product->setStatus('active');
  445.             $product->setBookingAccount($apiData['bookingAccount']);
  446.             $product->setPrice($price);
  447.             $product->setDescription($apiData['description']);
  448.             $product->setEasybillGroupId($apiData['groupId']);
  449.             $product->setName($apiData['name']);
  450.             if ($product->getProductNumber() < '99000' and $product->getProductNumber() != $apiData['productNumber']) {
  451.                 // check if the combination of account, agent and productNumber is already in use
  452.                 if ($this->countByCriteria(['account' => $product->getAccount(), 'agent' => $product->getAgent(), 'productNumber' => $apiData['productNumber']])) {
  453.                     $newProductNumber $this->findNextExceptionProductNumber();
  454.                     $product->setProductNumber($newProductNumber);
  455.                     $activity "ERROR: Reset ProductNumber {$apiData['productNumber']} to {$product->getProductNumber()}";
  456.                     $em->getRepository(Errorlog::class)->logError($activity"createOrUpdateProductByEasybillProduct"$adminEmail"allmedaProduct"$product->getId());
  457.                 } else {
  458.                     $product->setProductNumber($apiData['productNumber']);
  459.                 }
  460.             } else {
  461.                 $product->setProductNumber($apiData['productNumber']);
  462.             }
  463.             $product->setLastModified($now);
  464.             $product->setLastChangeUser($adminEmail);
  465.             $em->persist($product);
  466.             $em->flush();
  467.             $jsonChanges json_encode($changes);
  468.             $apiData     json_encode($apiData);
  469.             $response .= " createOrUpdateProductByEasybillApiPosition: updated {$product->getId()} {$product->getName()} with type = {$product->getType()} and changes {$jsonChanges} and apiData {$apiData}";
  470.         } else {
  471.             $response .= " createOrUpdateProductByEasybillApiPosition: exists already and no update needed {$product->getId()} {$product->getName()} - Easybill position {$positionId}";
  472.         }
  473.         return ['meta' => $response'entity' => $product] ;
  474.     }
  475.     public function updateExistingAllmedaProductByEasybillProduct(Product $product\App\StartPlatz\Bundle\FibuBundle\Entity\Product $position,  $adminEmail)
  476.     {
  477.         $em $this->getEntityManager();
  478.         $now = new DateTime();
  479.         $response '';
  480.         $storedData $this->getStoredData($product);
  481.         $fetchedData  $this->getFetchedData($position);
  482.         $changes array_diff_assoc($fetchedData$storedData);
  483.         if ($changes) {
  484.             $product->setAccount($position->getAccount());
  485.             $location = match($position->getAccount()) {
  486.                 'AI-Hub' => 'AI-Hub',
  487.                 'SP-DUS' => 'DUS',
  488.                 default => 'CGN'
  489.             };
  490.             $product->setLocation($location);
  491.             $product->setStatus('active');
  492.             $product->setBookingAccount($position->getBookingAccount());
  493.             $description $position->getDescription();
  494.             $product->setPrice($position->getSalePrice());
  495.             $product->setName($position->getName());
  496.             $product->setDescription($description);
  497.             $product->setEasybillGroupId($position->getGroupId());
  498.             $product->setEasybillPositionId($position->getPositionId());
  499.             $product->setAgent('easybill');
  500.             $product->setProductNumber($position->getNumber());
  501.             $product->setLastModified($now);
  502.             $product->setLastChangeUser($adminEmail);
  503.             $em->persist($product);
  504.             $em->flush();
  505.             $this->updateRelations($product);
  506.             $jsonChanges json_encode($changes);
  507.             $response .= "Allmeda Product updated {$product->getId()} {$product->getName()} with type = {$product->getType()} and changes {$jsonChanges} and relations updated";
  508.         } else {
  509.             $response .= "Allmeda Product exists already and no update needed {$product->getId()} {$product->getName()} - Easybill position {$position->getPositionId()}";
  510.         }
  511.         return [
  512.             'response' => $response,
  513.             'product' => $product
  514.         ];
  515.     }
  516.     private function findNextExceptionProductNumber()
  517.     {
  518.         if ($exception $this->findOneBy(['productNumber' => '99001'])) {
  519.             $lastException $this->findOneBy([], ['productNumber' => 'DESC']);
  520.             $nextProductNumber $lastException->getProductNumber() + 1;
  521.         } else {
  522.             $nextProductNumber '99001';
  523.         }
  524.         return $nextProductNumber;
  525.     }
  526.     private function getApiData($item)
  527.     {
  528.         $description     $item->description;
  529.         $data = ['description'    => $description'name'           => trim(explode(PHP_EOL, (string) $description)[0]), 'bookingAccount' => $item->export_identifier "" $item->export_identifier '99999''groupId'        => $item->group_id'price'          => number_format((float) $item->sale_price /1002), 'productNumber'  => $item->number'vatPercent'     => $item->vat_percent];
  530.         return $data;
  531.     }
  532.     private function getAllmedaData(Product $product)
  533.     {
  534.         $data = ['description'    => $product->getDescription(), 'name'           => $product->getName(), 'bookingAccount' => $product->getBookingAccount(), 'groupId'        => $product->getEasybillGroupId(), 'price'          => number_format((float) $product->getPrice(), 2), 'productNumber'  => $product->getProductNumber(), 'vatPercent'     => $product->getVatPercent()];
  535.         return $data;
  536.     }
  537.     private function getStoredData(Product $product)
  538.     {
  539.         $data = ['positionId' => $product->getEasybillPositionId(), 'name' => $product->getName(), 'account'        => $product->getAccount(), 'productNumber'  => $product->getProductNumber(), 'BookingAccount' => $product->getBookingAccount(), 'description'    => $product->getDescription(), 'Price'          => number_format((float) $product->getPrice(), 2), 'agent'          => $product->getAgent(), 'groupId'        => $product->getEasybillGroupId()];
  540.         return $data;
  541.     }
  542.     private function getFetchedData(\App\StartPlatz\Bundle\FibuBundle\Entity\Product $position)
  543.     {
  544.         $description $position->getDescription();
  545.         $name        $position->getName();
  546.         $data = ['positionId' => $position->getPositionId() ,'name' => $position->getName(), 'account'        => $position->getAccount(), 'productNumber'  => $position->getNumber(), 'BookingAccount' => $position->getBookingAccount(), 'description'    => $description'Price'          => number_format((float) $position->getSalePrice(), 2), 'agent'          => 'easybill''groupId'        => $position->getGroupId()];
  547.         return $data;
  548.     }
  549.     public function getAggregateByGroup($group$filter)
  550.     {
  551.         $qb $this->getEntityManager()->createQueryBuilder();
  552.         $qb->select(['t.' $group'COUNT(t.id) as number']);
  553.         $qb->from(Product::class /*Product Member*/'t');
  554.         if ($filter) {
  555.             //$qb->where('t.month = :filter');
  556.             //$qb->setParameter(':filter', $filter);
  557.         }
  558.         $qb->groupBy('t.'$group);
  559.         return $qb->getQuery()->getResult();
  560.     }
  561.     public function findOneBySpaceId($spaceId)
  562.     {
  563.         $qb $this->getEntityManager()->createQueryBuilder();
  564.         $qb->select('p')
  565.             ->from(Product::class /*Product Member*/'p')
  566.             ->from(Space::class, 's')
  567.             ->where('s.productId = p.id')
  568.             ->andWhere('s.id = :spaceId')
  569.             ->setParameter('spaceId'$spaceId)
  570.         ;
  571.         return $qb->getQuery()->getOneOrNullResult();
  572.     }
  573.     public function findByQueryString($queryString$sortArray = [])
  574.     {
  575.         $qb $this->getEntityManager()->createQueryBuilder();
  576.         $qb->select(['p']);
  577.         $qb->from(Product::class /*Product Member*/'p');
  578.         $qb->where('p.name LIKE :queryString OR p.id LIKE :queryString OR p.sortName LIKE :queryString OR p.description LIKE :queryString ');
  579.         $queryString '%' $queryString '%';
  580.         $qb->setParameter(':queryString'$queryString);
  581.         if (isset($sortArray)) {
  582.             foreach($sortArray as $field => $order) {
  583.                 $qb->addOrderBy('p.'$field$order);
  584.             }
  585.         } else {
  586.             $qb->orderBy('p.name''DESC');
  587.         }
  588.         return $qb->getQuery()->getResult();
  589.     }
  590.     public function findByLocation($location)
  591.     {
  592.         $qb $this->getEntityManager()->createQueryBuilder();
  593.         $qb->select(['p']);
  594.         $qb->from(Product::class /*Product Member*/'p');
  595.         $qb->where('p.location = :location OR p.location = ' "'SP'");
  596.         $qb->setParameter(':location'$location);
  597.         $qb->orderBy('p.name''DESC');
  598.         return $qb->getQuery()->getResult();
  599.     }
  600.     //
  601.     public function countParts($field$criteria)
  602.     {
  603.         $qb $this->getEntityManager()->createQueryBuilder();
  604.         $field 'p.' $field;
  605.         $qb->select([$field'COUNT(' .$field .') as total']);
  606.         $qb->from(Product::class /*Product Member*/'p');
  607.         if ($criteria) {
  608.             foreach ($criteria as $key => $value) {
  609.                 $qb->andWhere('p.' $key ' = :param');
  610.                 $qb->setParameter(':param'$value);
  611.             }
  612.         }
  613.         $qb->groupBy($field);
  614.         return $qb->getQuery()->getResult();
  615.     }
  616.     public function findOneByAndGetArrayResult($criteria)
  617.     {
  618.         $qb $this->getEntityManager()->createQueryBuilder();
  619.         $qb->select(['p']);
  620.         $qb->from(Product::class /*Product Member*/'p');
  621.         $field key($criteria);
  622.         $qb->where('p.'$field ' = :queryString');
  623.         $queryString $criteria[$field];
  624.         $qb->setParameter(':queryString'$queryString);
  625.         return $qb->getQuery()->getOneOrNullResult(2);
  626.     }
  627.     public function findByAndGetArrayResult($criteria)
  628.     {
  629.         $qb $this->getEntityManager()->createQueryBuilder();
  630.         $qb->select(['p']);
  631.         $qb->from(Product::class /*Product Member*/'p');
  632.         $field key($criteria);
  633.         $qb->where('p.'$field ' = :queryString');
  634.         $queryString $criteria[$field];
  635.         $qb->setParameter(':queryString'$queryString);
  636.         return $qb->getQuery()->getArrayResult();
  637.     }
  638.     public function getProductData(Product $product)
  639.     {
  640.         return ['name'               => $product->getName(), 'price'              => (float) $product->getPrice(), 'type'               => $product->getType(), 'agent'              => $product->getAgent(), 'account'            => $product->getAccount(), 'description'        => $product->getDescription(), 'imageUrl'           => $product->getImageUrl(), 'faq'                => $product->getFaq(), 'isBookableByMember' => $product->getIsBookableByMember(), 'isBookableByAdmin'  => $product->getIsBookableByAdmin(), 'easybillPositionId' => $product->getEasybillPositionId()];
  641.     }
  642.     public function getProductList()
  643.     {
  644.         $products $this->findBy([], ['type'=>'ASC''productNumber' => 'ASC''account' => 'ASC']);
  645.         $productIds array_map(fn (Product $product) => $product->getId(), $products);
  646.         $productNames array_map(fn (Product $product) => "{$product->getType()} - {$product->getProductNumber()}{$product->getAccount()}-{$product->getName()}"$products);
  647.         return array_combine($productIds$productNames);
  648.     }
  649.     public function find4Search()
  650.     {
  651.         $connection $this->getEntityManager()->getConnection();
  652.         $sql ="SELECT p.id, p.name, p.status, p.location, p.price, p.type, p.easybillPositionId, p.account, p.agent, p.productNumber
  653.         FROM aaa_sp_products p
  654.         ";
  655.         return $connection->fetchAllAssociative($sql, []);
  656.     }
  657.     public function getTemplateVars($request)
  658.     {
  659.         $templateVars = ['filter'  => null'tag'     => []];
  660.         $now = new DateTime();
  661.         if ($tag $request->query->get('tag')) {
  662.             $templateVars['tag'] = trim((string) $tag);
  663.         }
  664.         if ($location $request->query->get('location')) {
  665.             $templateVars['location']   = $location;
  666.         }
  667.         if ($status $request->query->get('status')) {
  668.             $status = (!in_array($status, ['active''inactive']) ? 'active' $status);
  669.             $templateVars['status']   = $status;
  670.         }
  671.         if ($criteria $request->query->get('criteria')) {
  672.             $templateVars['criteria'] = $criteria;
  673.         } else {
  674.             $templateVars['criteria'] = [];
  675.         }
  676.         if ($dimensions $request->query->get('dimension')) {
  677.             $templateVars['dimensions'] = $dimensions;
  678.         } else {
  679.             $templateVars['dimensions'] = [];
  680.         }
  681.         if ($filter $request->query->get('filter') and !$page $request->query->get('page')) {
  682.             $templateVars['filter']   = $filter;
  683.             if (preg_match("/:/", (string) $filter)) {
  684.                 $parameters explode(':', (string) $filter);
  685.                 if (isset($templateVars['criteria']['id'])) {
  686.                     unset($templateVars['criteria']['id']);
  687.                 }
  688.                 if (isset($templateVars['criteria'][$parameters[0]]) and $templateVars['criteria'][$parameters[0]] == $parameters[1]) {
  689.                     unset($templateVars['criteria'][$parameters[0]]);
  690.                 } else {
  691.                     $templateVars['criteria'][$parameters[0]] = $parameters[1];
  692.                     $templateVars['filter']   = null;
  693.                 }
  694.             } else {
  695.                 if ($filter == 'none') {
  696.                     $templateVars['criteria'] = [];
  697.                     $templateVars['filter']   = null;
  698.                 } else {
  699.                     $templateVars['filter']   = null;
  700.                 }
  701.             }
  702.         }
  703.         if ($sort $request->query->get('sort')) {
  704.             $templateVars['sort']   = $sort;
  705.             if (preg_match("/:/", (string) $sort)) {
  706.                 $parameters explode(':', (string) $sort);
  707.                 $templateVars['dimensions'][$parameters[0]] = $parameters[1];
  708.             } else {
  709.                 $sort 'none';
  710.                 switch ($sort) {
  711.                     default:
  712.                         $templateVars['dimensions'] = [];
  713.                         $templateVars['sort']   = null;
  714.                         break;
  715.                 }
  716.             }
  717.         }
  718.         if ($fields $request->query->get('fields')) {
  719.             $templateVars['fields']   = $fields;
  720.         }
  721.         return $templateVars;
  722.     }
  723. }