src/Service/UserService.php line 99

Open in your IDE?
  1. <?php
  2. //src/Service/UserService.php
  3. namespace App\Service;
  4. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\DependencyInjection\ContainerInterface;
  7. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  8. use Symfony\Component\HttpFoundation\Session\Session;
  9. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  10. use Symfony\Component\Form\Forms;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\Security\Core\Security;
  14. use Doctrine\Common\Collections\ArrayCollection;
  15. use App\Entity\Product;
  16. use App\Entity\Cart;
  17. use App\Entity\User;
  18. use App\Entity\UserSearch;
  19. use App\Entity\UserViewedProduct;
  20. use App\Entity\UserFavorite;
  21. use App\Entity\Notification;
  22. use App\Entity\RecurringOrder;
  23. use App\Entity\EmailSent;
  24. use App\Entity\UserVariables;
  25. use App\Entity\CompanyAssociation;
  26. use App\Form\ProductType;
  27. use App\Repository\ProductRepository;
  28. use App\Repository\UserRepository;
  29. use Swift_Attachment;
  30. class UserService
  31. {
  32.     private $entityInter;
  33.     private $em;
  34.     private $containerInter;
  35.     private $userRepo;
  36.     private $mailer;
  37.     private $security;
  38.     private $session;
  39.     private $currentAssociation='none';
  40.     public function __construct(EntityManagerInterface $emContainerInterface $containerUserRepository $userSecurity $securitySessionInterface $session){
  41.         //@Legacy
  42.         $this->entityInter $em;
  43.         $this->em $em;
  44.         $this->containerInter $container;
  45.         $this->userRepo $user;
  46.         $this->security $security;
  47.         $this->session $session;
  48.     }
  49.     /*
  50.      * Return the association the user is currently browing in
  51.      */
  52.     public function getAssociationUserIsBrowsing()
  53.     {
  54.         if($this->currentAssociation != 'none')
  55.             return $this->currentAssociation;
  56.         $var$this->getVariable('showThisAssociationIdOnly''customBrowsing');
  57.         if($var){
  58.             $this->currentAssociation $this->em->getRepository(CompanyAssociation::class)->findOneBy(['id' => $var]);
  59.             return $this->currentAssociation;
  60.         }
  61.         return false;
  62.     }
  63.     public function setAssociationUserIsBrowsing($associationId$user=false){
  64.         $this->setVariable('showThisAssociationIdOnly'$associationId'customBrowsing'false$user);
  65.     }
  66.     /*
  67.      * Get a variable for the user
  68.      */
  69.     public function getVariable($name$category$user=false$returnVariable=false)
  70.     {
  71.         if(!$user)
  72.             $user $this->getUser();
  73.         if($user){
  74.             $test $this->em->getRepository(UserVariables::class)->findOneBy(
  75.                 [
  76.                     'user' => $user,
  77.                     'name' => $name,
  78.                     'category' => $category
  79.                 ]
  80.             );
  81.         }else{
  82.             if(empty($this->session))
  83.                 $this->session = new Session();
  84.             $test $this->session->get($name.'-'.$category);
  85.             if($test)
  86.                 return $test;
  87.             else
  88.                 return false;
  89.         }
  90.         if(empty($test) || $test->isExpired())
  91.             return false;
  92.         else{
  93.             if($returnVariable)
  94.                 return $test;
  95.             else
  96.                 return $test->getValue();
  97.         }
  98.     }
  99.     /*
  100.      * Remove a variable for the user
  101.      */
  102.     public function delVariable($name$category$user=false){
  103.         if(!$user)
  104.             $user $this->getUser();
  105.         if($user){
  106.             $var $this->getVariable($name$category$usertrue);
  107.             if($var){
  108.                 $this->em->remove($var);
  109.                 $this->em->flush();
  110.             }
  111.         }else{
  112.             if(empty($this->session))
  113.                 $this->session = new Session();
  114.             $test $this->session->remove($name.'-'.$category);
  115.         }
  116.     }
  117.     /*
  118.      * Set a variable for the user
  119.      */
  120.     public function setVariable($name$value$category$expirationInSeconds=false$user=false){
  121.         if(!$user)
  122.             $user $this->getUser();
  123.         if($user){
  124.             $test $this->em->getRepository(UserVariables::class)->findOneBy(
  125.                 [
  126.                     'user' => $user,
  127.                     'name' => $name,
  128.                     'category' => $category
  129.                 ]
  130.             );
  131.             if($test){
  132.                 //Let's renew
  133.                 if($test->isExpired()){
  134.                     $test->setDateCreated(new \DateTime());
  135.                 }
  136.                 $test->setValue($value);
  137.                 if($expirationInSeconds)
  138.                     $test->setDelayInSecondsBeforeExpiration($expirationInSeconds);
  139.                 $this->em->persist($test);
  140.             }else{
  141.                 $var = new UserVariables();
  142.                 $var->setName($name);
  143.                 $var->setValue($value);
  144.                 $var->setUser($user);
  145.                 $var->setCategory($category);
  146.                 if($expirationInSeconds)
  147.                     $var->setDelayInSecondsBeforeExpiration($expirationInSeconds);
  148.                 $this->em->persist($var);
  149.             }
  150.             $this->em->flush();
  151.         }else{
  152.             if(empty($this->session))
  153.                 $this->session = new Session();
  154.             $this->session->set($name.'-'.$category$value);
  155.         }
  156.         return true;
  157.     }
  158.     /*
  159.      * Add Notification to a user
  160.      * @TODO move to Notification Service
  161.      */
  162.     public function addNotification($type$title$message=''$user=false){
  163.         $notif = new Notification();
  164.         $notif->setTitle($title);
  165.         $notif->setText($message);
  166.         if(!$user)
  167.             $notif->setUser($this->getUser());
  168.         else
  169.             $notif->setUser($user);
  170.         switch($type){
  171.         case 'info':
  172.             $notif->setIconColor('bg-info');
  173.             $notif->setIcon('icon-info');
  174.             break;
  175.         case 'success':
  176.             $notif->setIconColor('bg-success');
  177.             $notif->setIcon('icon-like');
  178.             break;
  179.         case 'warning':
  180.             $notif->setIconColor('bg-warning');
  181.             $notif->setIcon('icon-star');
  182.             break;
  183.         case 'error':
  184.             $notif->setIconColor('bg-danger');
  185.             $notif->setIcon('icon-dislike');
  186.             break;
  187.         }
  188.         $this->entityInter->persist($notif);
  189.         $this->entityInter->flush();
  190.     }
  191.     /*
  192.      * Add a Flash message to the user
  193.      */
  194.     public function addFlash($type$message){
  195.         $this->session->getFlashBag()->add($type$message);
  196.     }
  197.     /*
  198.      * Save the search user just did
  199.      * Type are either:
  200.      *      a: All
  201.      *      p: Product
  202.      *      c: Company(Store)
  203.      */
  204.     public function saveSearch($string$amount=0$type='a'$token=''$filters=''){
  205.         $user $this->getUser();
  206.         if($user){
  207.             $search = new UserSearch();
  208.             $search->setUser($user);
  209.             $search->setType($type);
  210.             $search->setSearch($string);
  211.             $search->setAmountResults($amount);
  212.             if($type == 'adv'){
  213.                 $search->setToken($token);
  214.                 $search->setRawFilters($filters);
  215.             }
  216.             $this->entityInter->persist($search);
  217.             $this->entityInter->flush();
  218.             return true;
  219.         }else if($type == 'adv'){
  220.             $search = new UserSearch();
  221.             $search->setType($type);
  222.             $search->setSearch($string);
  223.             $search->setAmountResults($amount);
  224.             if($type == 'adv'){
  225.                 $search->setToken($token);
  226.                 $search->setRawFilters($filters);
  227.             }
  228.             $this->entityInter->persist($search);
  229.             $this->entityInter->flush();
  230.             return true;
  231.         }
  232.         return false;
  233.     }
  234.     /*
  235.      * Add the product as viewed
  236.      */
  237.     public function addViewedProduct(Product $product){
  238.         $user $this->getUser();
  239.         if($user){
  240.             $view = new UserViewedProduct();
  241.             $view->setUser($user);
  242.             $view->setProduct($product);
  243.             $this->entityInter->persist($view);
  244.             $this->entityInter->flush();
  245.             return true;
  246.         }
  247.         return false;
  248.     }
  249.     /*
  250.      * Send a email to the user
  251.      */
  252.     public function sendEmail($subject$viewHTML=false$viewTXT=false$to false$from=null$withCC=false$replyTo=false){
  253.         if ($from==null){
  254.             $from 'reply-message@maturin.ca';
  255.         }
  256.         try {
  257.           //Let's record the email right away in our archive
  258.           $log = new EmailSent();
  259.           $log->setSentTo($to);
  260.           $log->setSentFrom($from);
  261.           $log->setSubject($subject);
  262.           $tUser $this->entityInter->getRepository(User::class)->findOneBy(['email' => $to]);
  263.           if($tUser)
  264.               $log->setUser($tUser);
  265.           if($viewHTML)
  266.               $log->setBodyHtml($viewHTML);
  267.           if($viewTXT)
  268.               $log->setBodyText($viewTXT);
  269.           $this->em->persist($log);
  270.           $this->em->flush();
  271.         } catch (\Exception $e) {
  272.           // do nothing...
  273.         }
  274.         if(empty($to)){
  275.             $user $this->getUser();
  276.             $to $user->getEmail();
  277.         }
  278.         
  279.         // if ($_ENV['APP_ENV'] != 'prod'){
  280.         //     $to = $_ENV['DEV_TO_MAIL_ADDRESS'];
  281.         // }
  282.            
  283.         $message = (new \Swift_Message($subject))
  284.             ->setFrom($from)
  285.             ->setTo($to);
  286.         if ($withCC && $_ENV['APP_ENV'] == 'prod')
  287.             $message->addCc('info@maturin.ca');
  288.         if ($replyTo){
  289.             $message->setReplyTo($replyTo);
  290.         }
  291.         if(!empty($viewHTML)){
  292.             $message->setBody($viewHTML'text/html');
  293.         }
  294.         if(!empty($viewTXT)){
  295.             $message->setBody($viewTXT'text/plain');
  296.         }
  297.         try {
  298.           return MailService::send($message);
  299.         } catch (\Throwable $e) {
  300.           return false;
  301.         } catch (\Exception $e) {
  302.           return false;
  303.         }
  304.     }
  305.     public function sendEmailWithAttachement($subject$viewHTML=false$viewTXT=false$to false$from=null$withCC=false$replyTo=false,$attachment,$invoiceNo){
  306.         if ($from==null){
  307.             $from 'reply-message@maturin.ca';
  308.         }
  309.         //Let's record the email right away in our archive
  310.         $log = new EmailSent();
  311.         $log->setSentTo($to);
  312.         $log->setSentFrom($from);
  313.         $log->setSubject($subject);
  314.         $tUser $this->entityInter->getRepository(User::class)->findOneBy(['email' => $to]);
  315.         if($tUser)
  316.             $log->setUser($tUser);
  317.         if($viewHTML)
  318.             $log->setBodyHtml($viewHTML);
  319.         if($viewTXT)
  320.             $log->setBodyText($viewTXT);
  321.         $this->em->persist($log);
  322.         $this->em->flush();
  323.         if(empty($to)){
  324.             $user $this->getUser();
  325.             $to $user->getEmail();
  326.         }
  327.         if ($_ENV['APP_ENV'] != 'prod')
  328.             $to $_ENV['DEV_TO_MAIL_ADDRESS'];
  329.         $filename sprintf('Facture-%s.pdf'$invoiceNo);
  330.         $data = new Swift_Attachment($attachment$filename'application/pdf');
  331.         $message = (new \Swift_Message($subject))
  332.             ->setFrom($from)
  333.             ->setTo($to)
  334.             ->attach($data);
  335.         if ($withCC && $_ENV['APP_ENV'] == 'prod')
  336.             $message->addCc('info@maturin.ca');
  337.         if ($replyTo){
  338.             $message->setReplyTo($replyTo);
  339.         }
  340.         if(!empty($viewHTML)){
  341.             $message->setBody($viewHTML'text/html');
  342.         }
  343.         if(!empty($viewTXT)){
  344.             $message->setBody($viewTXT'text/plain');
  345.         }
  346.         try {
  347.           return MailService::send($message);
  348.         } catch (\Throwable $e) {
  349.           return false;
  350.         } catch (\Exception $e) {
  351.           return false;
  352.         }
  353.     }
  354.     /*
  355.      * Return the user ID
  356.      */
  357.     public function getId(){
  358.         $user $this->getUser();
  359.         if(is_object($user))
  360.             return $user->getId();
  361.         else
  362.             return false;
  363.         //throw new \LogicException('No UserID found while being requested in UserService.php #72.');
  364.     }
  365.     /*
  366.      * Return the user Entity
  367.      */
  368.     public function getUser($userId false){
  369.         $user false;
  370.         if(!$userId){
  371.             $user $this->security->getUser();
  372.         }else{
  373.             if(is_numeric($userId))
  374.                 $user $this->entityInter->getRepository(User::class)->find($userId);
  375.             elseif(is_string($userId))
  376.                 $user $this->entityInter->getRepository(User::class)->findOneByEmail($userId);
  377.             else
  378.                 $user $userId;
  379.         }
  380.         return $user;
  381.     }
  382.     /*
  383.      * Return the user FromUserName
  384.      */
  385.     public function getUserFromUserName($userName){
  386.         $user $this->entityInter->getRepository(User::class)->findOneBy(
  387.             ['username' => trim($userName)]
  388.         );
  389.         return $user;
  390.     }
  391.     /*
  392.      * Return the User Private Contact List
  393.      * @TODO right now we return ALL, need to filter this better
  394.      */
  395.     public function getContactList($userId false){
  396.         if(!$userId)
  397.             $userId $this->getId();
  398.         $users $this->entityInter->getRepository(User::class)->getRelatedContacts($this->getUser($userId));
  399.         return $users;
  400.     }
  401.     /*
  402.      * Promote a user to rank
  403.      */
  404.     public function promote($roleUser $user null){
  405.         $userManager $this->containerInter->get('fos_user.user_manager');
  406.         $user->addRole($role);
  407.         return $userManager->updateUser($user);
  408.     }
  409.     /*
  410.      * demote a user to rank
  411.      */
  412.     public function demote($roleUser $user null){
  413.         $userManager $this->containerInter->get('fos_user.user_manager');
  414.         $user->removeRole($role);
  415.         return $userManager->updateUser($user);
  416.     }
  417.     /*
  418.      * Return the cart
  419.      * It store the cart in the cookie for Anonymous users
  420.      * Allowing the cart to be transfered to the user once logged in
  421.      * This is why cart is called from here and not from Entity
  422.      */
  423.     public function getCart(){
  424.         if($user $this->getUser()){
  425.             $cart $this->getUser()->getCart();
  426.         }else{
  427.             $this->session = new Session();
  428.             //Let's build a temporary cart for the user
  429.             $cartId $this->session->get('cartId');
  430.             if(!empty($cartId)){
  431.                 $cart $this->entityInter->getRepository(Cart::class)->find($cartId);
  432.             }else{
  433.                 $cart = new Cart();
  434.                 $this->entityInter->persist($cart);
  435.                 $this->entityInter->flush();
  436.                 $this->session->set('cartId'$cart->getId());
  437.             }
  438.         }
  439.         return $cart;
  440.     }
  441.     /*
  442.      * Return the cart
  443.      * It store the cart in the cookie for Anonymous users
  444.      * Allowing the cart to be transfered to the user once logged in
  445.      * This is why cart is called from here and not from Entity
  446.      */
  447.     public function getFavorites(){
  448.         $this->session = new Session();
  449.         if($user $this->getUser()){
  450.             //Merge from previous anonymous
  451.             /*
  452.             if(!empty($this->session->get('favorites'))){
  453.                 foreach($this->session->get('favorites') as $f){
  454.                     $product = $this->em->getRepository(Product::class)->findOneBy(['id'=>$f]);
  455.                     if(!$user->hasFavorite($product)){
  456.                         $favorite = new UserFavorite();
  457.                         $favorite->setUser($user);
  458.                         $favorite->setProduct($product);
  459.                         $this->em->persist($favorite);
  460.                     }
  461.                 }
  462.                 $this->em->flush();
  463.                 $this->session->remove('favorites');
  464.             }
  465.              */
  466.             $favs $this->getUser()->getFavorites();
  467.         }else{
  468.             //Let's build a temporary cart for the user
  469.             $fav $this->session->get('favorites');
  470.             $favs = new ArrayCollection();
  471.             if(!empty($fav)){
  472.                 foreach($fav as $f){
  473.                     $t $this->em->getRepository(Product::class)->findOneBy(['id'=>$f]);
  474.                     if($t){
  475.                         $tf = new UserFavorite();
  476.                         $tf->setProduct($t);
  477.                         $favs[]=$tf;
  478.                     }
  479.                 }
  480.             }else{
  481.                 $this->session->set('favorites', new ArrayCollection());
  482.             }
  483.         }
  484.         return $favs;
  485.     }
  486.     /*
  487.      * Call when a user is login in successfully
  488.      * We use this to transfer data from anonymous session to logged one
  489.      */
  490.     public function transferSession(User $user){
  491.         //Got a cart from when it was not logged yet
  492.         //Transfering to right user
  493.             $cartId $this->session->get('cartId');
  494.         if(!empty($cartId) && $user){
  495.             $cart $this->entityInter->getRepository(Cart::class)->find($cartId);
  496.             if($cart){
  497.                 //We transfer products to carts
  498.                 if(!empty($user->getCart())) {
  499.                     $cartUser $user->getCart();
  500.                     foreach($cart->getProducts() as $p) {
  501.                       $product_isAlreadyInCart false;
  502.                       $current_productId $p->getProduct()->getId();
  503.                       foreach($cartUser->getProducts() as $up) {
  504.                         $productId $up->getProduct()->getId();
  505.                         if ($productId == $current_productId) {
  506.                           $product_isAlreadyInCart true;
  507.                           $up->setQuantity$up->getQuantity() + $p->getQuantity() );
  508.                           $this->entityInter->persist($up);
  509.                         }
  510.                       }
  511.                       if (!$product_isAlreadyInCart) {
  512.                         $p->setCart($cartUser);
  513.                       }
  514.                         $this->entityInter->persist($p);
  515.                     }
  516.                     $this->entityInter->persist($cartUser);
  517.                     //$this->entityInter->remove($cart);
  518.                 } else {
  519.                     $user->addCart($cart);
  520.                     $this->entityInter->persist($user);
  521.                     $this->entityInter->persist($cart);
  522.                 }
  523.                    //$user->removeCart($cartUser);
  524.                 $this->entityInter->flush();
  525.             }
  526.             $this->session->remove('cartId');
  527.         }
  528.         //We transfer the favorites from a anonymous session
  529.         $favs $this->session->get('favorites');
  530.         if(!empty($favs) && $user){
  531.             foreach($favs as $fav){
  532.                 $product $this->em->getRepository(Product::class)->findOneBy(['id'=>$fav]);
  533.                 if($product){
  534.                     $favorite = new UserFavorite();
  535.                     $favorite->setUser($user);
  536.                     $favorite->setProduct($product);
  537.                     $this->em->persist($favorite);
  538.                 }
  539.             }
  540.             $this->em->flush();
  541.             $this->session->remove('favorites');
  542.         }
  543.         // transfer browsed association
  544.         if (($associationId $this->session->get('showThisAssociationIdOnly-customBrowsing')) != null){
  545.             $this->setAssociationUserIsBrowsing($associationId$user);
  546.         }
  547.     }
  548.     /*
  549.      * Tell if user can build bundles
  550.      */
  551.     public function isAllowedToMakeBundles(){
  552.         if($this->isGod())
  553.             return true;
  554.         $user $this->getUser();
  555.         if(!$user)
  556.             return false;
  557.         if($user->isGranted('ROLE_ADMIN_PRODUCT') || $user->isGranted('ROLE_ADMIN_MATURIN'))
  558.             return true;
  559.         return false;
  560.     }
  561.     /*
  562.      * Tell if the user is a god or not
  563.      */
  564.     public function isGod(){
  565.         $user $this->getUser();
  566.         if(!$user)
  567.             return false;
  568.         if($user->isGranted('ROLE_SUPER_ADMIN') || $user->isGranted('ROLE_ADMIN_SYSTEM'))
  569.             return true;
  570.         else
  571.             return false;
  572.     }
  573.     /*
  574.      * Return the actif reccuring orders
  575.      */
  576.     public function getActiveRecurringOrders(){
  577.         return $this->em->getRepository(RecurringOrder::class)->findActiveOrdersOfUser();
  578.     }
  579.     /*
  580.      * Return products to Suggests
  581.      */
  582.     public function findProductsToSuggest($cart=false){
  583.         if(!$cart)
  584.             $cart $this->getCart();
  585.         $suggestions = array();
  586.         $finalProducts = array();
  587.         foreach($cart->getProducts() as $p){
  588.             $suggestions array_merge($suggestions$p->getProduct()->getComplementedByGroups()->toArray());
  589.         }
  590.         foreach($suggestions as $s){
  591.             $finalProducts array_merge($finalProducts$s->getComplementaryProducts()->toArray());
  592.         }
  593.         //Let's remove the beverage for now
  594.         $exist = array();
  595.         foreach($finalProducts as $k => $p){
  596.             if(($p->getUnitDisplay() == 'ml' && $p->getUnitAmount() > 250)|| !$p->isSalable() || isset($exist[$p->getId()])){
  597.                 unset($finalProducts[$k]);
  598.             } elseif (!$this->getAssociationUserIsBrowsing()){
  599.                 if ($p->getIsDisplayedInAssociationOnly())
  600.                     unset($finalProducts[$k]);
  601.             } elseif (count($p->getPricings()) == 0){
  602.                 unset($finalProducts[$k]);
  603.             } else {
  604.                 if (!in_array($this->getAssociationUserIsBrowsing()->getId(), $p->getSearchAssociations()))
  605.                     unset($finalProducts[$k]);
  606.             }
  607.             $exist[$p->getId()] = true;
  608.         }
  609.         shuffle($finalProducts);
  610.         if(count($finalProducts) > 15){
  611.                 return array_slice($finalProducts015);
  612.         }
  613.         if(count($finalProducts) < 10){
  614.             $extras $this->em->getRepository(Product::class)->getProductsForUser($this->getUser());
  615.             foreach($extras as $key => $p){
  616.                 if(($p->getUnitDisplay() == 'ml' && $p->getUnitAmount() > 250)|| !$p->isSalable() || isset($exist[$p->getId()])){
  617.                     unset($extras[$key]);
  618.                 }
  619.             }
  620.             return array_merge($finalProducts$extras);
  621.         }
  622.         return $finalProducts;
  623.     }
  624. }