src/Controller/ApiController.php line 729

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\AlgoliaReindexRequest;
  4. use App\Entity\CarteCadeau;
  5. use App\Entity\Devise;
  6. use App\Entity\Genres;
  7. use App\Entity\GiftCreditsPromoCode;
  8. use App\Entity\GiftMembership;
  9. use App\Entity\GiftProduct;
  10. use App\Entity\Produit;
  11. use App\Entity\ProduitPrix;
  12. use App\Entity\Promotion;
  13. use App\Entity\Tier;
  14. use App\Entity\Transaction;
  15. use App\Entity\User;
  16. use App\Entity\UserProduits;
  17. use App\Entity\UserPromotions;
  18. use App\Entity\UserWishlists;
  19. use App\Service\FileService;
  20. use App\Service\HookManager;
  21. use App\Service\MailService;
  22. use App\Service\StringManager;
  23. use DateTime;
  24. use Doctrine\ORM\EntityManagerInterface;
  25. use Exception;
  26. use Symfony\Component\HttpClient\HttpClient;
  27. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  28. use Symfony\Component\HttpFoundation\Request;
  29. use Symfony\Component\Routing\Annotation\Route;
  30. use Symfony\Component\HttpFoundation\JsonResponse;
  31. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  32. use Dompdf\Dompdf;
  33. use Dompdf\Options;
  34. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  35. use Symfony\Component\HttpFoundation\Response;
  36. use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
  37. use GuzzleHttp\Client as ApiClient;
  38. use Psr\Log\LoggerInterface;
  39. use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
  40. use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
  41. use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
  42. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  43. use Algolia\SearchBundle\SearchService;
  44. class ApiController extends AbstractController
  45. {
  46.   const TOKEN_VALIDITY_DURATION 12 3600;
  47.   public $domain 'https://bookdoreille.b-cdn.net/';
  48.   /**
  49.    * @var HookManager
  50.    */
  51.   private $hookManager;
  52.   private $logger;
  53.   protected $searchService;
  54.   public function __construct(
  55.     EntityManagerInterface      $em,
  56.     FileService                 $file_service,
  57.     UserPasswordHasherInterface $encoder,
  58.     MailService                 $mail_service,
  59.     ContainerBagInterface       $container,
  60.     HookManager                 $hookManager,
  61.     LoggerInterface             $logger,
  62.     SearchService               $searchService
  63.   )
  64.   {
  65.     $this->em $em;
  66.     $this->file_service $file_service;
  67.     $this->encoder $encoder;
  68.     $this->mail_service $mail_service;
  69.     $this->params = array();
  70.     $this->container $container;
  71.     $this->hookManager $hookManager;
  72.     $this->logger $logger;
  73.     $this->searchService $searchService;
  74.   }
  75.   /**
  76.    * @Route("/api/profil/update", name="api_update_profil")
  77.    */
  78.   public function update_profil(Request $request): JsonResponse
  79.   {
  80.     $token $request->headers->get('token');
  81.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  82.     if ($userToken != null && (time() - $userToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION) {
  83.       try {
  84.         $user $userToken->getUser();
  85.         $user->setNom($request->request->get('nom'))
  86.           ->setPrenom($request->request->get('prenom'))
  87.           ->setRaisonSociale($request->request->get('raison_sociale'))
  88.           ->setAdressePostale($request->request->get('adresse_postale'))
  89.           ->setCodePostal($request->request->get('code_postal'))
  90.           ->setVille($request->request->get('ville'))
  91.           ->setPays($request->request->get('pays'))
  92.           ->setOptinNouveautes($request->request->get('newsletter'));
  93.         $this->em->persist($user);
  94.         $this->em->flush();
  95.       } catch (Exception $e) {
  96.         return new JsonResponse(array("error" => "Une erreur s'est produite: " $e->getMessage()));
  97.       }
  98.       return new JsonResponse(array('success' => true));
  99.     }
  100.     return new JsonResponse(array("error" => "Une erreur s'est produite, veuillez vous relogger"));
  101.   }
  102.   /**
  103.    * @Route("/api/get_zip_token", name="api_get_zip_token")
  104.    */
  105.   public function get_zip_token(Request $request): JsonResponse
  106.   {
  107.     $token $request->headers->get('token');
  108.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  109.     if ($userToken != null && (time() - $userToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION) {
  110.     }
  111.     return new JsonResponse(array('error' => "Erreur - veuillez vous relogger"));
  112.   }
  113.   /**
  114.    * @Route("/api/register", name="api_register")
  115.    */
  116.   public function register(Request $request): JsonResponse
  117.   {
  118.     if ($request->request->get('password') != null && $request->request->get('email') != null) {
  119.       try {
  120.         $existing_user $this->em->getRepository('App:User')->findOneBy(array('email' => $request->request->get('email')));
  121.         if ($existing_user == null) {
  122.           $password $request->request->get('password');
  123.           $user = new User;
  124.           $user->setPrenom($request->request->get('prenom'))
  125.             ->setNom($request->request->get('nom'))
  126.             ->setEmail($request->request->get('email'))
  127.             ->setDateCreated(new \DateTime())
  128.             ->setUsername($user->getEmail())
  129.             ->setRole('user');
  130.           $this->em->persist($user);
  131.           $encodedPassword $this->encoder->hashPassword($user$password);
  132.           $user->setPassword($encodedPassword);
  133.           $this->em->persist($user);
  134.           $this->em->flush();
  135.           $this->validateAndAssignGiftCards($request->request->get('email'), $user);
  136.           $this->validateAndAssignGiftProducts($request->request->get('email'), $user);
  137.           if ($request->request->get('isCa') == 1) {
  138.             $bytes random_bytes(16);
  139.             $memberstack_password bin2hex($bytes);
  140.             $user->setCodeAbo($memberstack_password);
  141.             $this->em->persist($user);
  142.             if ($this->container->get('parameter_bag')->get('app.env') == "dev") {
  143.               $api_key "pk_sb_2fa87d3fadccd90794ac";
  144.             } else {
  145.               $api_key "pk_baa2568b3eae41eb6fa0";
  146.             }
  147.             $client = new ApiClient([
  148.               'headers' => ['Content-Type' => 'application/json''x-api-key' => $api_key]
  149.             ]);
  150.             try {
  151.               $response $client->post(
  152.                 'https://client.memberstack.com/auth/signup',
  153.                 ['body' => json_encode(
  154.                   [
  155.                     'email' => $user->getEmail(),
  156.                     'password' => $memberstack_password,
  157.                     'plans' => []
  158.                   ]
  159.                 )]
  160.               );
  161.             } catch (Exception $e) {
  162.               return new JsonResponse(array('success' => false'error' => 'Compte crée, mais création memberstack Ã©chouée ' $e->getMessage()));
  163.             }
  164.             $this->em->flush();
  165.           } else {
  166.             $this->hookManager->hookCreateUser($user);
  167.           }
  168.           return new JsonResponse(array('success' => true));
  169.         } else {
  170.           return new JsonResponse(array('success' => false'error' => 'Un compte avec cet email existe déjà'));
  171.         }
  172.       } catch (Exception $e) {
  173.         return new JsonResponse(array('success' => false'error' => 'Une erreur est survenue'));
  174.       }
  175.     }
  176.     return new JsonResponse(array('success' => false'error' => 'Paramètres email ou mot de passe manquant'));
  177.   }
  178.   private function validateAndAssignGiftCards($email$user): void
  179.   {
  180.     if ($email && $user) {
  181.       $giftCards $this->em->getRepository(CarteCadeau::class)->getUsersCardsNotRegistered($email);
  182.       foreach ($giftCards as $giftCard) {
  183.         $giftCard $this->em->getRepository(CarteCadeau::class)->find($giftCard["id"]);
  184.         if ($giftCard) {
  185.           $destinatairesTemp json_decode($giftCard->getDestinatairesTemp(), true);
  186.           $currentDate = new DateTime();
  187.           if (!empty($destinatairesTemp['date_reception']) && !empty($destinatairesTemp['email'])) {
  188.             $dateReception DateTime::createFromFormat('d/m/Y'$destinatairesTemp['date_reception']);
  189.             if ($dateReception $currentDate) {
  190.               $giftCard->setUtilisateurDestinataire($user);
  191.               $giftCard->setEtat("valide");
  192.               $this->em->persist($giftCard);
  193.             }
  194.           }
  195.         }
  196.       }
  197.       $this->em->flush();
  198.     }
  199.   }
  200.   private function validateAndAssignGiftProducts($email$user): void
  201.   {
  202.     if ($email && $user) {
  203.       $unassignedGiftProducts $this->em->getRepository('App:GiftProduct')->findBy(['redeemed' => false'validated' => true]);
  204.       for ($i 0$i count($unassignedGiftProducts); $i++) {
  205.         if ($unassignedGiftProducts[$i]->getRecipientEmail() === $email) {
  206.           $unassignedGiftProducts[$i]->setRecipient($user);
  207.           $this->em->persist($unassignedGiftProducts[$i]);
  208.           $this->createUserProduct($user$unassignedGiftProducts[$i]->getProduct());
  209.         }
  210.       }
  211.       $this->em->flush();
  212.     }
  213.   }
  214.   private function createUserProduct($user$product): void
  215.   {
  216.     if ($user && $product) {
  217.       $userProduct = new UserProduits();
  218.       $userProduct
  219.         ->setUser($user)
  220.         ->setProduit($product)
  221.         ->setDateActivation(new \DateTime);
  222.       $this->em->persist($userProduct);
  223.       $productsWishlist $this->em->getRepository('App:UserWishlists')->findOneBy(array('produit' => $product'user' => $user));
  224.       if ($productsWishlist != null) {
  225.         $this->em->remove($productsWishlist);
  226.       }
  227.       $this->em->flush();
  228.     }
  229.   }
  230.   /**
  231.    * @Route("/api/password_forgot", name="api_password_forgot")
  232.    */
  233.   public function api_password_forgot(Request $request): JsonResponse
  234.   {
  235.     if ($request->request->get('email') != null) {
  236.       $test $this->em->getRepository('App:User')->findOneBy(array('email' => $request->request->get('email')));
  237.       if ($test == false) {
  238.         return new JsonResponse(array('success' => false'error' => "L'email ne correspond Ã  aucun compte"));
  239.       } else {
  240.         $token uniqid() . hash('md5'$test->getEmail());
  241.         $test->setTokenReset($token);
  242.         $this->em->persist($test);
  243.         $this->em->flush();
  244.         //return new JsonResponse(array('success' => true, 'token_password' => $token));
  245.         $destinataire $test->getEmail();
  246.         $content $this->renderView(
  247.           'Mail/password_retrieve.html.twig',
  248.           array(
  249.             'token' => $token
  250.           )
  251.         );
  252.         //$content =  $this->render('Mail/validation_commande.html.twig');
  253.         $subject "Récupération de mot de passe Book d'Oreille";
  254.         try {
  255.           $tt $this->mail_service->sendTransacEmail($destinataire$content$subject);
  256.           return new JsonResponse(array('success' => true'error' => "Un email de récupération a Ã©té envoyé"));
  257.         } catch (Exception $e) {
  258.           return new JsonResponse(array('success' => false'error' => "Une erreur est survenue"));
  259.         }
  260.       }
  261.     }
  262.     return new JsonResponse(array('success' => false'error' => "Merci de préciser l'email du compte"));
  263.   }
  264.   /**
  265.    * @Route("/api/password_change", name="api_password_change")
  266.    */
  267.   public function api_password_change(Request $request): JsonResponse
  268.   {
  269.     if ($request->request->get('token_password') != null && $request->request->get('password') != null) {
  270.       $user $this->em->getRepository("App:User")->findOneBy(array('token_reset' => $request->request->get('token_password')));
  271.       $encodedPassword $this->encoder->hashPassword($user$request->request->get('password'));
  272.       $user->setTokenReset(null)
  273.         ->setPassword($encodedPassword);
  274.       $this->em->persist($user);
  275.       $this->em->flush();
  276.       return new JsonResponse(array('success' => true'error' => 'Mot de passe modifié'));
  277.     }
  278.     return new JsonResponse(array('success' => false'error' => 'Des paramètres sont manquants'));
  279.   }
  280.   /**
  281.    * @Route("/api/categories-narra", name="api_get_categories_narra")
  282.    */
  283.   public function api_get_categories_narra(Request $request): JsonResponse
  284.   {
  285.     return new JsonResponse($this->em->getRepository(Produit::class)->countCategorieNarra());
  286.   }
  287.   /**
  288.    * @Route("/api/password_token", name="api_password_token")
  289.    */
  290.   public function api_password_token(Request $request): JsonResponse
  291.   {
  292.     if ($request->request->get('email') != null) {
  293.       $test $this->em->getRepository(User::class)->findOneBy(array('email' => $request->request->get('email')));
  294.       if ($test == false) {
  295.         return new JsonResponse(array('success' => false'error' => "L'email ne correspond Ã  aucun compte"));
  296.       } else {
  297.         $token uniqid() . hash('md5'$test->getEmail());
  298.         $test->setTokenReset($token);
  299.         $this->em->persist($test);
  300.         $this->em->flush();
  301.         return new JsonResponse(array('success' => true'token' => $token));
  302.       }
  303.     }
  304.     return new JsonResponse(array('success' => false'error' => "Merci de préciser l'email du compte"));
  305.   }
  306.   /**
  307.    * @Route("/api/password_validation", name="api_password_validation")
  308.    */
  309.   public function api_password_validation(Request $request): JsonResponse
  310.   {
  311.     if ($request->request->get('token_password') != null && $request->request->get('password') != null && $request->request->get('site') == "narra") {
  312.       $user $this->em->getRepository(User::class)->findOneBy(array('token_reset' => $request->request->get('token_password')));
  313.       $encodedPassword $this->encoder->hashPassword($user$request->request->get('password'));
  314.       $user->setTokenReset(null)
  315.         ->setPassword($encodedPassword);
  316.       $this->em->persist($user);
  317.       $this->em->flush();
  318.       return new JsonResponse(array('success' => true'error' => 'Mot de passe modifié'));
  319.     }
  320.     return new JsonResponse(array('success' => false'error' => 'Des paramètres sont manquants ou erronés'));
  321.   }
  322.   /**
  323.    * @Route("/api/contenus", name="api_get_contenus")
  324.    */
  325.   public function getApiContenus(Request $request): JsonResponse
  326.   {
  327.     $results = array();
  328.     $first_date $request->query->get('first_date');
  329.     $end_date $request->query->get('end_date');
  330.     $date_debut false;
  331.     $date_fin false;
  332.     if ($first_date != null) {
  333.       $date_debut date_create_from_format('Y-m-d'$first_date);
  334.     }
  335.     if ($end_date != null) {
  336.       $date_fin date_create_from_format('Y-m-d'$end_date);
  337.     }
  338.     $prixlitteraires $this->em->getRepository('App:PrixLitteraire')->getAll($date_debut$date_fin);
  339.     $array_object = array();
  340.     foreach ($prixlitteraires as $object) {
  341.       $tmp = array(
  342.         'obj_id' => $object->getId(),
  343.         'nom_prix' => $object->getLibelleFr(),
  344.         'description' => $object->getDescriptionFr()
  345.       );
  346.       array_push($array_object$tmp);
  347.     }
  348.     $results['prixlitteraires'] = $array_object;
  349.     $categories $this->em->getRepository('App:GroupeGenres')->findAll();
  350.     $array_object = array();
  351.     foreach ($categories as $object) {
  352.       $tmp = array(
  353.         'obj_id' => $object->getId(),
  354.         'nom_genre' => $object->getLibelleFr()
  355.       );
  356.       array_push($array_object$tmp);
  357.     }
  358.     $results['categories'] = $array_object;
  359.     $genres $this->em->getRepository('App:Genres')->getAll($date_debut$date_fin);
  360.     $array_object = array();
  361.     foreach ($genres as $object) {
  362.       $tmp = array(
  363.         'obj_id' => $object->getId(),
  364.         'nom_genre' => $object->getLibelleFr(),
  365.         'description' => $object->getDescriptionFr(),
  366.         'parent' => ($object->getGroupe() != null) ? $object->getGroupe()->getId() : null
  367.       );
  368.       array_push($array_object$tmp);
  369.     }
  370.     $results['genres'] = $array_object;
  371.     $sousgenres $this->em->getRepository('App:SousGenres')->getAll($date_debut$date_fin);
  372.     $array_object = array();
  373.     foreach ($sousgenres as $object) {
  374.       $tmp = array(
  375.         'obj_id' => $object->getId(),
  376.         'id_genre' => ($object->getGenre() != null) ? $object->getGenre()->getId() : null,
  377.         'nom_genre' => $object->getLibelleFr(),
  378.         'description' => $object->getDescriptionFr()
  379.       );
  380.       array_push($array_object$tmp);
  381.     }
  382.     $results['sousgenres'] = $array_object;
  383.     $publics $this->em->getRepository('App:Publics')->getAll($date_debut$date_fin);
  384.     $array_object = array();
  385.     foreach ($publics as $object) {
  386.       $tmp = array(
  387.         'obj_id' => $object->getId(),
  388.         'nom_public' => $object->getLibelleFr(),
  389.       );
  390.       array_push($array_object$tmp);
  391.     }
  392.     $results['publics'] = $array_object;
  393.     $publics_jeunesse $this->em->getRepository('App:PublicsJeunesse')->getAll($date_debut$date_fin);
  394.     $array_object = array();
  395.     foreach ($publics_jeunesse as $object) {
  396.       $tmp = array(
  397.         'obj_id' => $object->getId(),
  398.         'nom_public_jeunesse' => $object->getLibelleFr(),
  399.       );
  400.       array_push($array_object$tmp);
  401.     }
  402.     $results['publics_jeunesse'] = $array_object;
  403.     $themes $this->em->getRepository('App:Theme')->getAll($date_debut$date_fin);
  404.     $array_object = array();
  405.     foreach ($themes as $object) {
  406.       $tmp = array(
  407.         'obj_id' => $object->getId(),
  408.         'nom_theme' => $object->getLibelleFr(),
  409.       );
  410.       array_push($array_object$tmp);
  411.     }
  412.     $results['themes'] = $array_object;
  413.     $versions $this->em->getRepository('App:Version')->getAll($date_debut$date_fin);
  414.     $array_object = array();
  415.     foreach ($versions as $object) {
  416.       $tmp = array(
  417.         'obj_id' => $object->getId(),
  418.         'nom_version' => $object->getLibelleFr(),
  419.       );
  420.       array_push($array_object$tmp);
  421.     }
  422.     $results['versions'] = $array_object;
  423.     return new JsonResponse($results);
  424.   }
  425.   /**
  426.    * @Route("/api/narrators", name="api_get_narrators")
  427.    */
  428.   public function getNarrators(Request $request): JsonResponse
  429.   {
  430.     $country $request->query->get('country');
  431.     $narrators $this->em->getRepository(Tier::class)->getNarrators($country);
  432.     $arrayNarrators = array();
  433.     foreach ($narrators as $narratorData) {
  434.       $narrator $narratorData[0];
  435.       $productCount $narratorData['productCount'];
  436.       $tmp = array(
  437.         'id' => $narrator->getId(),
  438.         'products_count' => $productCount,
  439.         'first_name' => $narrator->getPrenom(),
  440.         'last_name' => $narrator->getNom(),
  441.         'slug' => $narrator->getAlgoliaName()
  442.       );
  443.       $arrayNarrators[] = $tmp;
  444.     }
  445.     return new JsonResponse($arrayNarrators);
  446.   }
  447.   /**
  448.    * @Route("/api/tiers/{slug}", name="api_get_tier_by_slug")
  449.    */
  450.   public function getTierBySlug($slug): JsonResponse
  451.   {
  452.     $tier $this->em->getRepository(Tier::class)->findOneBy(array('algolia_name' => $slug));
  453.     $tierNormalized = array(
  454.       'id' => $tier->getId(),
  455.       'image_name' => $tier->getImageName()
  456.     );
  457.     return new JsonResponse($tierNormalized);
  458.   }
  459.   /**
  460.    * @Route("/api/authors", name="api_get_authors")
  461.    */
  462.   public function getAuthors(Request $request): JsonResponse
  463.   {
  464.     $country $request->query->get('country');
  465.     $authors $this->em->getRepository(Tier::class)->getAuthors($country);
  466.     $arrayAuthors = array();
  467.     foreach ($authors as $authorData) {
  468.       $author $authorData[0];
  469.       $productCount $authorData['productCount'];
  470.       $tmp = array(
  471.         'id' => $author->getId(),
  472.         'products_count' => $productCount,
  473.         'first_name' => $author->getPrenom(),
  474.         'last_name' => $author->getNom(),
  475.         'slug' => $author->getAlgoliaName()
  476.       );
  477.       $arrayAuthors[] = $tmp;
  478.     }
  479.     return new JsonResponse($arrayAuthors);
  480.   }
  481.   /**
  482.    * @Route("/api/tiers", name="api_get_tiers")
  483.    */
  484.   public function getApiTiers(Request $request): JsonResponse
  485.   {
  486.     $first_date $request->query->get('first_date');
  487.     $end_date $request->query->get('end_date');
  488.     $date_debut false;
  489.     $date_fin false;
  490.     if ($first_date != null) {
  491.       $date_debut date_create_from_format('Y-m-d'$first_date);
  492.     }
  493.     if ($end_date != null) {
  494.       $date_fin date_create_from_format('Y-m-d'$end_date);
  495.     }
  496.     $editeur $request->query->get('editeur');
  497.     $tiers $this->em->getRepository(Tier::class)->getTiers($date_debut$date_fin);
  498.     $array_tiers = array();
  499.     foreach ($tiers as $tier) {
  500.       if ($editeur == 1) {
  501.         if ($tier->getEditeurProduits()->count() > 0) {
  502.           $nbProductCa $tier->getEditeurProduits()->filter(function (Produit $product) {
  503.             return $product->getBoolCad() && $product->getActive();
  504.           })->count();
  505.           $tmp = array(
  506.             'obj_id' => $tier->getId(),
  507.             'date_creation' => ($tier->getDateCreation() != null) ? $tier->getDateCreation()->format('c') : null,
  508.             'date_modification' => ($tier->getDateUpdate() != null) ? $tier->getDateUpdate()->format('c') : null,
  509.             'titre' => $tier->getPrenom() . ' ' $tier->getNom(),
  510.             'description' => $tier->getDescriptionFr(),
  511.             'image' => $this->domain 'contributeurs/' $tier->getImageName(),
  512.             'credit_image' => $tier->getCopyrightImage(),
  513.             'nombre_produit' => $tier->getEditeurProduits()->count(),
  514.             'nombre_produit_ca' => $nbProductCa,
  515.             'algolia_name' => $tier->getAlgoliaName()
  516.           );
  517.           $array_tiers[] = $tmp;
  518.         }
  519.       } else {
  520.         $tmp = array(
  521.           'obj_id' => $tier->getId(),
  522.           'date_creation' => ($tier->getDateCreation() != null) ? $tier->getDateCreation()->format('c') : null,
  523.           'date_modification' => ($tier->getDateUpdate() != null) ? $tier->getDateUpdate()->format('c') : null,
  524.           'titre' => $tier->getPrenom() . ' ' $tier->getNom(),
  525.           'description' => $tier->getDescriptionFr(),
  526.           'image' => $this->domain 'contributeurs/' $tier->getImageName(),
  527.           'credit_image' => $tier->getCopyrightImage(),
  528.           'algolia_name' => $tier->getAlgoliaName()
  529.         );
  530.         $array_tiers[] = $tmp;
  531.       }
  532.     }
  533.     return new JsonResponse($array_tiers);
  534.   }
  535.   /**
  536.    * @Route("/api/tiers/{id}", name="api_get_tiers_detail")
  537.    */
  538.   public function getApiTiersDetail(Request $request$id): JsonResponse
  539.   {
  540.     $tier $this->em->getRepository('App:Tier')->find($id);
  541.     if ($tier !== null) {
  542.       //Id des titres
  543.       $titres_id = array();
  544.       foreach ($tier->getProduitsArtistes() as $produit) {
  545.         array_push($titres_id, array('id' => $produit->getId(), 'type' => 'artiste'));
  546.       }
  547.       foreach ($tier->getProduitsAuteurs() as $produit) {
  548.         array_push($titres_id, array('id' => $produit->getId(), 'type' => 'auteur'));
  549.       }
  550.       foreach ($tier->getProduitsTraducteurs() as $produit) {
  551.         array_push($titres_id, array('id' => $produit->getId(), 'type' => 'traducteur'));
  552.       }
  553.       foreach ($tier->getProduitsInterpretes() as $produit) {
  554.         array_push($titres_id, array('id' => $produit->getId(), 'type' => 'interprete'));
  555.       }
  556.       foreach ($tier->getProduitsCompositeurs() as $produit) {
  557.         array_push($titres_id, array('id' => $produit->getId(), 'type' => 'compositeur'));
  558.       }
  559.       foreach ($tier->getProduitsIllustrateurs() as $produit) {
  560.         array_push($titres_id, array('id' => $produit->getId(), 'type' => 'illustrateur'));
  561.       }
  562.       foreach ($tier->getProduitsRealisateurs() as $produit) {
  563.         array_push($titres_id, array('id' => $produit->getId(), 'type' => 'realisateur'));
  564.       }
  565.       $tmp = array(
  566.         'obj_id' => $tier->getId(),
  567.         'date_creation' => ($tier->getDateCreation() != null) ? $tier->getDateCreation()->format('c') : null,
  568.         'date_modification' => ($tier->getDateUpdate() != null) ? $tier->getDateUpdate()->format('c') : null,
  569.         'titre' => $tier->getPrenom() . ' ' $tier->getNom(),
  570.         'description' => $tier->getDescriptionFr(),
  571.         'image' => $this->domain 'contributeurs/' $tier->getImageName(),
  572.         'credit_image' => $tier->getCopyrightImage(),
  573.         'audiobooks' => $titres_id,
  574.       );
  575.       return new JsonResponse($tmp);
  576.     } else {
  577.       return new JsonResponse(array('error' => 'not found'));
  578.     }
  579.   }
  580.   /**
  581.    * @Route("/api/selections", name="api_get_selections")
  582.    */
  583.   public function getApiSelections(Request $request): JsonResponse
  584.   {
  585.     $first_date $request->query->get('first_date');
  586.     $end_date $request->query->get('end_date');
  587.     $date_debut false;
  588.     $date_fin false;
  589.     if ($first_date != null) {
  590.       $date_debut date_create_from_format('Y-m-d'$first_date);
  591.     }
  592.     if ($end_date != null) {
  593.       $date_fin date_create_from_format('Y-m-d'$end_date);
  594.     }
  595.     $selections $this->em->getRepository('App:Selection')->getApiSelections($date_debut$date_fin);
  596.     $array_selections = array();
  597.     foreach ($selections as $selection) {
  598.       $titres_id = array();
  599.       foreach ($selection->getProduits() as $p) {
  600.         array_push($titres_id$p->getId());
  601.       }
  602.       $tmp = array(
  603.         'date_creation' => ($selection->getDateCreated() != null) ? $selection->getDateCreated()->format('c') : null,
  604.         'date_modification' => ($selection->getDateUpdate() != null) ? $selection->getDateUpdate()->format('c') : null,
  605.         'titre' => $selection->getLibelleFr(),
  606.         'description' => $selection->getDescriptionFr(),
  607.         'parent' => ($selection->getParent() != null) ? $selection->getParent()->getLibelleFr() : null,
  608.         'audiobooks' => $titres_id,
  609.       );
  610.       array_push($array_selections$tmp);
  611.     }
  612.     return new JsonResponse($array_selections);
  613.   }
  614.   /**
  615.    * @Route("/api/genres", name="api_get_genres")
  616.    */
  617.   public function apiGenres(Request $request): JsonResponse
  618.   {
  619.     $country $request->query->get('country');
  620.     $results $this->em->getRepository(Genres::class)->getAllGenresWithProductCount('fr'$country);
  621.     return new JsonResponse($results);
  622.   }
  623.   /**
  624.    * @Route("/api/audiobooks", name="api_get_audiobooks")
  625.    */
  626.   public function apiAudiobooks(Request $request): JsonResponse
  627.   {
  628.     $first_date $request->query->get('first_date');
  629.     $end_date $request->query->get('end_date');
  630.     $type $request->query->get('type');
  631.     $orderBy $request->query->get('orderBy');
  632.     $country $request->query->get('country');
  633.     $limit $request->query->get('limit');
  634.     $ids $request->query->get('ids', []);
  635.     $genres $request->query->get('genres', []);
  636.     $publisher $request->query->get('publisher');
  637.     $decodedGenres array_map('urldecode', (array)$genres);
  638.     $contributorSlug $request->query->get('contributorSlug');
  639.     $authorSlug $request->query->get('authorSlug');
  640.     $narratorSlug $request->query->get('narratorSlug');
  641.     $date_debut false;
  642.     $date_fin false;
  643.     if ($first_date != null) {
  644.       $date_debut date_create_from_format('Y-m-d'$first_date);
  645.     }
  646.     if ($end_date != null) {
  647.       $date_fin date_create_from_format('Y-m-d'$end_date);
  648.     }
  649.     if ($type !== null) {
  650.       $produits $this->em->getRepository(Produit::class)->getProducts(
  651.         'fr',
  652.         $limit,
  653.         0,
  654.         $orderBy,
  655.         $country,
  656.         $type,
  657.         $ids,
  658.         $decodedGenres,
  659.         $publisher,
  660.         $contributorSlug,
  661.         $authorSlug,
  662.         $narratorSlug
  663.       );
  664.     } else {
  665.       $produits $this->em->getRepository(Produit::class)->getApiAll($date_debut$date_fin);
  666.     }
  667.     $results $this->processProducts($produits$type$country);
  668.     return new JsonResponse($results);
  669.   }
  670.   /**
  671.    * @Route("/api/audiobooks-urls", name="api_get_audiobooks_urls")
  672.    */
  673.   public function apiAudiobooksUrls(Request $request): JsonResponse
  674.   {
  675.     $country $request->query->get('country');
  676.     $limit $request->query->get('limit');
  677.     $produits $this->em->getRepository(Produit::class)->getProductsUrls($country$limit);
  678.     $results = [];
  679.     foreach ($produits as $p) {
  680.       $tmp = array(
  681.         'obj_id' => $p['id'],
  682.         'alias_url' => $p['alias_url'],
  683.       );
  684.       $results[] = $tmp;
  685.     }
  686.     return new JsonResponse($results);
  687.   }
  688.   /**
  689.    * @Route("/api/audiobook/{slug}", name="api_get_audiobook_by_slug")
  690.    */
  691.   public function apiAudiobookBySlug($slug): JsonResponse
  692.   {
  693.     $audiobook $this->em->getRepository(Produit::class)->findOneBy(array(
  694.       'alias_url' => $slug
  695.     ));
  696.     $results $this->processProducts([$audiobook], '''');
  697.     if (count($results) > 0) {
  698.       return new JsonResponse(array('success' => true'audiobook' => $results[0]));
  699.     } else {
  700.       return new JsonResponse(array('error' => true));
  701.     }
  702.   }
  703.   /**
  704.    * @Route("/api/audiobooks/{id}", name="api_get_audiobooks_detail")
  705.    */
  706.   public function apiAudiobookDetail($id): JsonResponse
  707.   {
  708.     $book $this->em->getRepository(Produit::class)->find($id);
  709.     if ($book != null) {
  710.       $categories = array();
  711.       $categories_id = array();
  712.       $genres = array();
  713.       if ($book->getGenre1() != null) {
  714.         if ($book->getGenre1()->getGroupe() != null) {
  715.           array_push($categories_id$book->getGenre1()->getGroupe()->getId());
  716.         }
  717.         array_push($genres$book->getGenre1()->getId());
  718.       }
  719.       if ($book->getGenre2() != null) {
  720.         if ($book->getGenre2()->getGroupe() != null) {
  721.           array_push($categories_id$book->getGenre2()->getGroupe()->getId());
  722.         }
  723.         array_push($genres$book->getGenre2()->getId());
  724.       }
  725.       $categories_id array_unique($categories_id);
  726.       foreach ($categories_id as $id) {
  727.         $groupegenre $this->em->getRepository('App:GroupeGenres')->find($id);
  728.         array_push($categories, array('id' => $groupegenre->getId()));
  729.       }
  730.       $sousgenres = array();
  731.       if ($book->getSousgenre1() != null) {
  732.         array_push($sousgenres$book->getSousgenre1()->getId());
  733.       }
  734.       if ($book->getSousgenre2() != null) {
  735.         array_push($sousgenres$book->getSousgenre2()->getId());
  736.       }
  737.       $themes = array();
  738.       foreach ($book->getThemes() as $theme) {
  739.         array_push($themes$theme->getId());
  740.       }
  741.       $jeunesse = array();
  742.       if ($book->getPublics() != null && $book->getPublics()->getId() == 3) {
  743.         $jeunesse = array(
  744.           'detail_jeunesse' => ($book->getPublicsJeunesse() != null) ? $book->getPublicsJeunesse()->getLibelleFr() : null,
  745.           'age_min' => $book->getJeunesseAgeMin(),
  746.           'age_max' => $book->getJeunesseAgeMin()
  747.         );
  748.       }
  749.       $auteurs = array();
  750.       foreach ($book->getAuteurs() as $tier) {
  751.         //if($tier->getActive() == true){
  752.         array_push($auteurs$tier->getId());
  753.         //}
  754.       }
  755.       $interpretes = array();
  756.       foreach ($book->getInterpretes() as $tier) {
  757.         //if($tier->getActive() == true){
  758.         array_push($interpretes$tier->getId());
  759.         //}
  760.       }
  761.       $traducteurs = array();
  762.       foreach ($book->getTraducteurs() as $tier) {
  763.         //if($tier->getActive() == true){
  764.         array_push($traducteurs$tier->getId());
  765.         //}
  766.       }
  767.       $illustrateurs = array();
  768.       foreach ($book->getIllustrateurs() as $tier) {
  769.         //if($tier->getActive() == true){
  770.         array_push($illustrateurs$tier->getId());
  771.         //}
  772.       }
  773.       $compositeurs = array();
  774.       foreach ($book->getCompositeurs() as $tier) {
  775.         //if($tier->getActive() == true){
  776.         array_push($compositeurs$tier->getId());
  777.         //}
  778.       }
  779.       $bookrixlitteraires = array();
  780.       foreach ($book->getPrixLitteraires() as $tier) {
  781.         array_push($bookrixlitteraires$tier->getId());
  782.       }
  783.       $arr_prix_vente $this->em->getRepository(ProduitPrix::class)->getProductPrice($book->getId());
  784.       $bookrix_vente null;
  785.       $date_fin_precommande null;
  786.       if ($arr_prix_vente != null) {
  787.         $bookrix_vente $arr_prix_vente['prix_ttc'];
  788.         if ($arr_prix_vente['precommande']) {
  789.           $date_fin_precommande = ($arr_prix_vente['date_fin'] != null) ? $arr_prix_vente['date_fin']->format('c') : null;
  790.         }
  791.       }
  792.       $arr_prix_vente_ca $this->em->getRepository(ProduitPrix::class)->getProductPrice($book->getId(), 'CAD');
  793.       $bookrix_vente_ca null;
  794.       if ($arr_prix_vente_ca != null) {
  795.         $bookrix_vente_ca $arr_prix_vente_ca['prix_ttc'];
  796.       }
  797.       $tmp = array(
  798.         'obj_id' => $book->getId(),
  799.         'active' => $book->getActive(),
  800.         'id_pipe_drive' => $book->getIdCrm(),
  801.         'image_hd' => $this->domain 'produit/hd/' $book->getImageHdName(),
  802.         'alt_image' => $book->getCopyrightImage(),
  803.         'titre_fr' => $book->getTitreFr(),
  804.         'sous_titre_fr' => $book->getSousTitreFr(),
  805.         'titre_original' => $book->getTitreOriginal(),
  806.         'serie' => array(
  807.           'serie_id' => ($book->getSerie() != null) ? $book->getSerie()->getId() : null,
  808.           'serie_titre' => ($book->getSerie() != null) ? $book->getSerie()->getTitre() : null,
  809.           'tome' => $book->getNumeroTome(),
  810.           'categories' => $categories,
  811.           'genres' => $genres,
  812.           'sousgenres' => $sousgenres
  813.         ),
  814.         'themes' => $themes,
  815.         'public' => ($book->getPublics() != null) ? $book->getPublics()->getLibelleFr() : null,
  816.         'jeunesse' => $jeunesse,
  817.         'auteurs' => $auteurs,
  818.         'interpretes' => $interpretes,
  819.         'traducteurs' => $traducteurs,
  820.         'illustrateurs' => $illustrateurs,
  821.         'compositeurs' => $compositeurs,
  822.         'prix_litteraires' => $bookrixlitteraires,
  823.         'editeur' => ($book->getEditor() != null) ? $book->getEditor()->getId() : null,
  824.         'fournisseur' => ($book->getFournisseur() != null) ? $book->getFournisseur()->getId() : null,
  825.         'version' => ($book->getVersion() != null) ? $book->getVersion()->getLibelleFr() : null,
  826.         'duree' => $book->getDureeMin(),
  827.         'collection' => ($book->getCollection() != null) ? $book->getCollection()->getLibelleFr() : null,
  828.         'type_realisation' => ($book->getTypeRealisation() != null) ? $book->getTypeRealisation()->getLibelleFr() : null,
  829.         'ean_telechargement' => $book->getEanTelechargement(),
  830.         'ean_cd' => $book->getEanCd(),
  831.         'resume' => $book->getResumeFr(),
  832.         'url_presentation_origine' => $book->getUrlOriginePresentationFr(),
  833.         'tracklist' => $book->getEnrichissementsFr(),
  834.         'coup_de_coeur_libraire' => $book->getCoupDeCoeurLibraire(),
  835.         'video_html' => $book->getVideo(),
  836.         'url_extrait' => $this->file_service->getUrlExtrait($book->getId()),
  837.         'annee_production' => $book->getAnneeProduction(),
  838.         'annee_edition' => $book->getAnneeEdition(),
  839.         'copyright' => $book->getCopyright(),
  840.         'has_chapitre_gratuit' => $book->getBoolChapitreGratuit(),
  841.         'langue_audio' => $book->getLangueSources(),
  842.         'langue_originale' => $book->getLangueOriginale(),
  843.         'prix_reference' => $book->getPrixReference(),
  844.         'prix_reference_ca' => $book->getPrixReferenceCa(),
  845.         'prix_vente' => $bookrix_vente,
  846.         'prix_vente_ca' => $bookrix_vente_ca,
  847.         'date_fin_precommande' => $date_fin_precommande,
  848.         'is_new' => $book->getTitreALaUne(),
  849.         'is_bestseller' => $book->getBestSeller(),
  850.         'is_bestseller_ca' => $book->getBestSellerCa(),
  851.         'is_exclu_numerique' => $book->getProduitAppel(),
  852.         'date_creation' => ($book->getDateCreation() != null) ? $book->getDateCreation()->format('c') : null,
  853.         'date_modification' => ($book->getDateUpdate() != null) ? $book->getDateUpdate()->format('c') : null
  854.       );
  855.       return new JsonResponse($tmp);
  856.     } else {
  857.       return new JsonResponse(array('error' => 'not found'));
  858.     }
  859.   }
  860.   /**
  861.    * @Route("/api/mybooks", name="api_my_books")
  862.    */
  863.   public function getMyApiBooks(Request $request): JsonResponse
  864.   {
  865.     $token $request->headers->get('token');
  866.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  867.     if ($userToken != null && (time() - $userToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION) {
  868.       //Ok lister livres du user
  869.       $get $request->query;
  870.       $order $get->get('order');
  871.       $order_sort $get->get('order_sort');
  872.       $offset = ($get->get('page') - 1) * $get->get('rows');
  873.       $user_id $userToken->getUser()->getId();
  874.       $results_final = array();
  875.       if ($get->get('type') == 'freechapters') {
  876.         $results_final $this->em->getRepository('App:UserChapitreGratuit')->getUserProduits($user_id$offset$get->get('rows'), $order$order_sort);
  877.       } else if ($get->get('type') == 'wishlist') {
  878.         $results_final $this->em->getRepository('App:UserWishlists')->getUserProduits($user_id$offset$get->get('rows'), $order$order_sort);
  879.       } else {
  880.         $results_final $this->em->getRepository('App:UserProduits')->getApiUserProduits($user_id$offset$get->get('rows'), $order$order_sort);
  881.       }
  882.       return new JsonResponse($results_final);
  883.     }
  884.     return new JsonResponse(array("error" => "Une erreur s'est produite, veuillez vous relogger"));
  885.   }
  886.   /**
  887.    * @Route("/api/invoices", name="get_invoices")
  888.    */
  889.   public function get_invoices(Request $request): JsonResponse
  890.   {
  891.     $token $request->headers->get('token');
  892.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  893.     if ($userToken != null && (time() - $userToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION) {
  894.       $array_invoices = array();
  895.       $orders $this->em->getRepository('App:Transaction')
  896.         ->getUserTransactions($userToken->getUser()->getId());
  897.       foreach ($orders as $order) {
  898.         $facture_url $this->generateUrl('account_pdf_facture', array('reference' => $order['reference_interne']));
  899.         $array_invoices[] = array(
  900.           "reference" => $order['reference_interne'],
  901.           "date" => $order['date'],
  902.           "montant" => $order['montant_ttc_reel'],
  903.           "facture" => $facture_url
  904.         );
  905.       }
  906.       return new JsonResponse(array("success" => true"datas" => $array_invoices));
  907.     }
  908.     return new JsonResponse(array('error' => "Erreur - veuillez vous relogger"));
  909.   }
  910.   /**
  911.    * @Route("/api/invoices/{reference}", name="account_pdf_facture")
  912.    */
  913.   public function account_pdf_facture(Request $request$reference): JsonResponse
  914.   {
  915.     $token $request->headers->get('token');
  916.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  917.     if ($userToken != null && (time() - $userToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION) {
  918.       $this->logger->error('Create pdf ($userToken)', [$userToken]);
  919.       $this->params['show_menu'] = 0;
  920.       $pdfOptions = new Options();
  921.       $pdfOptions->set('defaultFont''Arial');
  922.       $dompdf = new Dompdf($pdfOptions);
  923.       $order $this->em->getRepository('App:Transaction')->findOneBy(array(
  924.         'reference_interne' => $reference
  925.       ));
  926.       $orderItems = array();
  927.       $items $order->getTransactionItems();
  928.       $this->logger->error('Create pdf ($order)', [$order]);
  929.       foreach ($items as $i) {
  930.         if ($i->getCarteCadeau() != null) {
  931.           $tmp = array(
  932.             'reference' => 'CARTECADEAU-' $i->getCarteCadeau()->getCode(),
  933.             'title' => "Carte cadeau " $i->getCarteCadeau()->getUtilisateurDestinataire()->getEmail(),
  934.             'quantite' => 1,
  935.             'prix_ht' => $i->getCarteCadeau()->getValeur(),
  936.             'prix_ttc' => $i->getCarteCadeau()->getValeur()
  937.           );
  938.         } else if ($i->getGiftMembership() != null) {
  939.           $this->logger->error('Create pdf ($i->getGiftMembership())', [$i->getGiftMembership()]);
  940.           $tmp = array(
  941.             'reference' => 'ABONNEMENTCADEAU-' $i->getGiftMembership()->getMonths(),
  942.             'title' => "Abonnement cadeau " $i->getGiftMembership()->getSender()->getEmail(),
  943.             'quantite' => 1,
  944.             'prix_ht' => round($i->getGiftMembership()->getAmountTTC() / 1.149752),
  945.             'prix_ttc' => $i->getGiftMembership()->getAmountTTC()
  946.           );
  947.         } else {
  948.           $tmp = array(
  949.             'reference' => 'BKDO-' str_pad($i->getProduit()->getId(), 6"0"STR_PAD_LEFT),
  950.             'title' => $i->getProduit()->getTitreFr(),
  951.             'quantite' => 1,
  952.             'prix_ht' => $i->getPrixHt(),
  953.             'prix_ttc' => $i->getPrixTtc()
  954.           );
  955.         }
  956.         array_push($orderItems$tmp);
  957.       }
  958.       $montant_tva_5 $this->em->getRepository('App:TransactionItems')->getSumTvaMontant($order->getId(), '5.50');
  959.       $montant_tva_20 $this->em->getRepository('App:TransactionItems')->getSumTvaMontant($order->getId(), '20.00');
  960.       $promo $order->getMontantBonAchat();
  961.       $soustotal $order->getMontantTtcNominal();
  962.       $html $this->renderView('Main/account/invoice.html.twig', [
  963.         'isCa' => $this->isCa,
  964.         'items' => $orderItems,
  965.         'sous_total_ttc' => $soustotal,
  966.         'promo' => $promo,
  967.         'reference' => $reference,
  968.         'date' => $order->getDate(),
  969.         'client_prenom' => $userToken->getUser()->getPrenom(),
  970.         'client_nom' => $userToken->getUser()->getNom(),
  971.         'montant_tva_5' => $montant_tva_5,
  972.         'montant_tva_20' => $montant_tva_20,
  973.         'ttc_reel' => $order->getMontantTtcReel()
  974.       ]);
  975.       $dompdf->loadHtml($html);
  976.       $dompdf->setPaper('A4''portrait');
  977.       $dompdf->render();
  978.       return new Response($dompdf->stream("facture_" $reference ".pdf", [
  979.         "Attachment" => true
  980.       ]));
  981.     }
  982.     return new JsonResponse(array('error' => "Erreur - veuillez vous relogger"));
  983.   }
  984.   /**
  985.    * @Route("/api/wishlist/add", name="add_wishlit")
  986.    */
  987.   public function add_wishlist(Request $request): JsonResponse
  988.   {
  989.     $token $request->headers->get('token');
  990.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  991.     if ($userToken != null && (time() - $userToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION) {
  992.       $produit $this->em->getRepository(Produit::class)->find($request->request->get('book_id'));
  993.       if ($produit != null) {
  994.         $wishlist $this->em->getRepository('App:UserWishlists')->findOneBy(array('user' => $userToken->getUser(), 'produit' => $produit));
  995.         if ($wishlist != null) {
  996.           return new JsonResponse(array('error' => "Erreur - produit déjà dans la liste de souhait"));
  997.         } else {
  998.           $wishlist = new UserWishlists;
  999.           $wishlist->setUser($userToken->getUser())
  1000.             ->setProduit($produit)
  1001.             ->setDate(new \DateTime);;
  1002.           $this->em->persist($wishlist);
  1003.           $this->em->flush();
  1004.           return new JsonResponse(array('success' => "Produit ajouté Ã  la liste de souhait"));
  1005.         }
  1006.       } else {
  1007.         return new JsonResponse(array('error' => "Erreur - produit non trouvé"));
  1008.       }
  1009.     } else {
  1010.       return new JsonResponse(array('error' => "Erreur - veuillez vous relogger"));
  1011.     }
  1012.   }
  1013.   /**
  1014.    * @Route("/api/wishlist/remove", name="remove_wishlit")
  1015.    */
  1016.   public function remove_wishlist(Request $request): JsonResponse
  1017.   {
  1018.     $token $request->headers->get('token');
  1019.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  1020.     if ($userToken != null && (time() - $userToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION) {
  1021.       $produit $this->em->getRepository(Produit::class)->find($request->request->get('book_id'));
  1022.       if ($produit != null) {
  1023.         $wishlist $this->em->getRepository('App:UserWishlists')->findOneBy(array('user' => $userToken->getUser(), 'produit' => $produit));
  1024.         if ($wishlist != null) {
  1025.           $this->em->remove($wishlist);
  1026.           $this->em->flush();
  1027.           return new JsonResponse(array('success' => "Produit retiré de la liste de souhait"));
  1028.         } else {
  1029.           return new JsonResponse(array('error' => "Erreur - produit non trouvé dans la liste de souhait"));
  1030.         }
  1031.       } else {
  1032.         return new JsonResponse(array('error' => "Erreur - produit non trouvé"));
  1033.       }
  1034.     } else {
  1035.       return new JsonResponse(array('error' => "Erreur - veuillez vous relogger"));
  1036.     }
  1037.   }
  1038.   /**
  1039.    * @Route("/api/creategiftcard", name="create_gift_card")
  1040.    * @throws Exception
  1041.    */
  1042.   public function create_gift_card(Request $requestStringManager $stringManager): JsonResponse
  1043.   {
  1044.     $post $request->request;
  1045.     $carte = new CarteCadeau;
  1046.     $date = new \DateTime;
  1047.     if ($this->getUser() != null) {
  1048.       $carte->setUtilisateurAcheteur($this->getUser());
  1049.     }
  1050.     $currency $request->request->get('currency');
  1051.     $devise $this->em->getRepository('App:Devise')->findOneByCode(strtoupper($currency));
  1052.     $temps json_encode(array(
  1053.       'prenom' => $post->get('prenom'),
  1054.       'email' => $post->get('email'),
  1055.       'rue' => $post->get('rue'),
  1056.       'codePostal' => $post->get('codePostal'),
  1057.       'ville' => $post->get('ville'),
  1058.       'pays' => $post->get('pays'),
  1059.       'date_reception' => $post->get('date')
  1060.     ));
  1061.     $endDate = new \DateTime();
  1062.     $endDate->add(new \DateInterval('P1Y'));
  1063.     if (strtoupper($currency) === 'CAD') {
  1064.       $endDate = new \DateTime('2100-01-01');
  1065.     }
  1066.     $carte
  1067.       ->setDestinatairesTemp($temps)
  1068.       ->setCanal($post->get('sendMethod'))
  1069.       ->setEtat('projet')
  1070.       ->setValeur($post->get('amount'))
  1071.       ->setMessage($post->get('message'))
  1072.       ->setSoldeUtilise(0)
  1073.       ->setDevise($devise)
  1074.       ->setDateAchat($date)
  1075.       ->setDateCreation(new \DateTime('now'))
  1076.       ->setDateLimite($endDate)
  1077.       ->setService($devise->getCode() === "CAD" 1);
  1078.     if ($devise->getCode() === "CAD") {
  1079.       $carte->setCode('CARTE' $stringManager->generateRandomCode());
  1080.     } else {
  1081.       $carte->setCode('BCARTE' $stringManager->generateRandomCode(5));
  1082.     }
  1083.     if ($request->files->get('illustration_custom') != null) {
  1084.       $file $request->files->get('illustration_custom');
  1085.       try {
  1086.         $file->move('../public/images_carte_cadeau/'$file->getClientOriginalName());
  1087.         $carte->setImage($file->getClientOriginalName());
  1088.       } catch (FileException $e) {
  1089.         return new JsonResponse(array('error' => 'upload image problem'));
  1090.       }
  1091.     } else {
  1092.       if ($devise->getCode() !== 'CAD') {
  1093.         if ($post->get('illustration_1') != null && $post->get('illustration_1') !== "null") {
  1094.           $carte->setImage('A.jpg');
  1095.         } else if ($post->get('illustration_2') != null && $post->get('illustration_2') !== "null") {
  1096.           $carte->setImage('B.jpg');
  1097.         } else if ($post->get('illustration_3') != null && $post->get('illustration_3') !== "null") {
  1098.           $carte->setImage('C.jpg');
  1099.         } else if ($post->get('illustration_4') != null && $post->get('illustration_4') !== "null") {
  1100.           $carte->setImage('D.jpg');
  1101.         } else if ($post->get('illustration_5') != null && $post->get('illustration_5') !== "null") {
  1102.           $carte->setImage('E.jpg');
  1103.         } else {
  1104.           $carte->setImage('A.jpg');
  1105.         }
  1106.       }
  1107.     }
  1108.     $this->em->persist($carte);
  1109.     $this->em->flush();
  1110.     return new JsonResponse(array('giftcard' => $carte->getId()));
  1111.   }
  1112.   /**
  1113.    * @Route("/api/create-gift-membership", name="create_gift_membership")
  1114.    * @throws Exception
  1115.    */
  1116.   public function create_gift_membership(Request $request): JsonResponse
  1117.   {
  1118.     $post $request->request;
  1119.     $giftMembership = new GiftMembership;
  1120.     $date = new \DateTime;
  1121.     $currency $post->get('currency');
  1122.     $emailSender $post->get('emailSender');
  1123.     $emailRecipient $post->get('emailRecipient');
  1124.     $firstName $post->get('firstName');
  1125.     $amount $post->get('amount');
  1126.     $message $post->get('message');
  1127.     $sendDate $post->get('sendDate');
  1128.     $sendDateObject = new \DateTime($sendDate);
  1129.     $devise $this->em->getRepository('App:Devise')->findOneBy(array('code' => strtoupper($currency)));
  1130.     $recipient $this->em->getRepository('App:User')->findOneBy(array('email' => $emailRecipient));
  1131.     if ($recipient !== null) {
  1132.       $giftMembership->setRecipient($recipient);
  1133.     }
  1134.     $sender $this->em->getRepository('App:User')->findOneBy(array('email' => $emailSender));
  1135.     if ($sender !== null) {
  1136.       $giftMembership->setSender($sender);
  1137.     }
  1138.     $giftMembership->setRecipientEmail($emailRecipient);
  1139.     $giftMembership->setMessage($message);
  1140.     $giftMembership->setDevise($devise);
  1141.     $giftMembership->setDateToSend($sendDateObject);
  1142.     $giftMembership->setMonths($amount);
  1143.     $giftMembership->setRecipientFirstName($firstName);
  1144.     $giftMembership->setCreationDate($date);
  1145.     $this->em->persist($giftMembership);
  1146.     $this->em->flush();
  1147.     return new JsonResponse(array('gift_membership' => $giftMembership->getId()));
  1148.   }
  1149.   /**
  1150.    * @Route("/api/create-gift-product", name="create_gift_product")
  1151.    * @throws Exception
  1152.    */
  1153.   public function create_gift_product(Request $request): JsonResponse
  1154.   {
  1155.     $post $request->request;
  1156.     $giftProduct = new GiftProduct();
  1157.     $date = new \DateTime;
  1158.     $emailSender $post->get('emailSender');
  1159.     $idAudiobook $post->get('idAudiobook');
  1160.     $currency $post->get('currency');
  1161.     $emailRecipient $post->get('emailRecipient');
  1162.     $firstName $post->get('firstName');
  1163.     $message $post->get('message');
  1164.     $devise $this->em->getRepository('App:Devise')->findOneBy(array('code' => strtoupper($currency)));
  1165.     $recipient $this->em->getRepository('App:User')->findOneBy(array('email' => $emailRecipient));
  1166.     $audiobook $this->em->getRepository(Produit::class)->find($idAudiobook);
  1167.     $giftProductOwned $this->em->getRepository('App:GiftProduct')->findOneBy(array('recipientEmail' => $emailRecipient'product' => $audiobook'validated' => true));
  1168.     $productOwned false;
  1169.     if ($recipient !== null) {
  1170.       $productOwned $this->em->getRepository('App:UserProduits')->findOneBy(array('user' => $recipient'produit' => $audiobook));
  1171.     }
  1172.     if ($giftProductOwned || $productOwned) {
  1173.       return new JsonResponse(array('error' => 'Ce livre audio appartient déjà au destinataire. Vous pouvez en choisir un autre.'));
  1174.     }
  1175.     if ($recipient !== null) {
  1176.       $giftProduct->setRecipient($recipient);
  1177.     }
  1178.     $giftProduct->setRecipientEmail($emailRecipient);
  1179.     $giftProduct->setMessage($message);
  1180.     $giftProduct->setDevise($devise);
  1181.     $giftProduct->setRecipientFirstName($firstName);
  1182.     $giftProduct->setCreationDate($date);
  1183.     $giftProduct->setValidated(false);
  1184.     $giftProduct->setRedeemed(false);
  1185.     $giftProduct->setProduct($audiobook);
  1186.     if ($emailSender !== null && $emailSender !== '') {
  1187.       $senderEntity $this->em->getRepository('App:User')->findOneBy(array('email' => $emailSender));
  1188.       if ($senderEntity) {
  1189.         $giftProduct->setSender($senderEntity);
  1190.       }
  1191.     }
  1192.     $this->em->persist($giftProduct);
  1193.     $this->em->flush();
  1194.     return new JsonResponse(array('gift_product' => $giftProduct->getId()));
  1195.   }
  1196.   /**
  1197.    * @Route("/api/create-algolia-reindex-request", name="create_algolia_reindex_request")
  1198.    * @throws Exception
  1199.    */
  1200.   public function create_algolia_reindex_request(Request $request): JsonResponse
  1201.   {
  1202.     $algoliaReindexRequest = new AlgoliaReindexRequest();
  1203.     $algoliaReindexRequest->setCreationDatetime(new \Datetime);
  1204.     $algoliaReindexRequest->setExecuted(true);
  1205.     $this->em->persist($algoliaReindexRequest);
  1206.     $this->em->flush();
  1207.     $products $this->em->getRepository(Produit::class)->findBy(array('active' => '1'));
  1208.     $this->searchService->clear(Produit::class);
  1209.     $this->searchService->index($this->em$products);
  1210.     return new JsonResponse(array('success' => 'Algolia reindexing has been triggered. The process will be completed in about five minutes. You can close this window.'));
  1211.   }
  1212.   /**
  1213.    * @Route("/api/trigger-narra-build", name="trigger_narra_build")
  1214.    * @throws Exception
  1215.    * @throws TransportExceptionInterface
  1216.    */
  1217.   public function trigger_narra_build(Request $request): JsonResponse
  1218.   {
  1219.     try {
  1220.       $webhookUrl 'https://webhooks.amplify.ca-central-1.amazonaws.com/prod/webhooks?id=d326e603-d700-437e-8c5e-8da37b64e4a4&token=jRs7xWa2Q1veQOjCeTRQGR3eQt3CTiKJEIAtL4SYVw';
  1221.       if ($_ENV['APP_ENV'] === 'dev') {
  1222.         $webhookUrl 'https://webhooks.amplify.ca-central-1.amazonaws.com/prod/webhooks?id=68c46f87-a1b8-4cca-a975-b453606355f4&token=mDnXkPDBjpubMmIOSwr3GmFAnCk85ZpJHNaDmSgOOk';
  1223.       }
  1224.       $httpClient HttpClient::create();
  1225.       $headers = ['Content-Type' => 'application/json'];
  1226.       $response $httpClient->request('POST'$webhookUrl, [
  1227.         'headers' => $headers,
  1228.       ]);
  1229.       if ($response->getStatusCode() === 200 || $response->getStatusCode() === 202 || $response->getStatusCode() === 201) {
  1230.         return new JsonResponse(['success' => 'Webhook triggered successfully']);
  1231.       } else {
  1232.         $this->logger->error('Response Content', [$response->getStatusCode()]);
  1233.         return new JsonResponse(['error' => 'Failed to trigger webhook'], 500);
  1234.       }
  1235.     } catch (\Exception $e) {
  1236.       $this->logger->error('Exception', [$e->getMessage()]);
  1237.       return new JsonResponse(['error' => $e->getMessage()], 500);
  1238.     }
  1239.   }
  1240.   /**
  1241.    * @Route("/api/pointsfidelite", name="get_pointsfidelite")
  1242.    */
  1243.   public function get_pointsfidelite(Request $request): JsonResponse
  1244.   {
  1245.     $token $request->headers->get('token');
  1246.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  1247.     if ($userToken != null && (time() - $userToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION) {
  1248.       return new JsonResponse(array('points' => $userToken->getUser()->getFidelite()));
  1249.     }
  1250.     return new JsonResponse(array("error" => "Une erreur s'est produite, veuillez vous relogger"));
  1251.   }
  1252.   /**
  1253.    * @Route("/api/coupons", name="get_mescoupons")
  1254.    */
  1255.   public function get_mescoupons(Request $request): JsonResponse
  1256.   {
  1257.     $token $request->headers->get('token');
  1258.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  1259.     if ($userToken != null && (time() - $userToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION) {
  1260.       $coupons $this->em->getRepository('App:Promotion')->findBy(array('user_allowed' => $userToken->getUser()->getId()));
  1261.       $results = array();
  1262.       foreach ($coupons as $promo) {
  1263.         $c = array(
  1264.           'code' => $promo->getCode(),
  1265.           'valeur' => $promo->getValeur(),
  1266.           'date_limite' => $promo->getDateFin()
  1267.         );
  1268.         $up $this->em->getRepository('App:Transaction')->findOneBy(array('client' => $userToken->getUser(), 'code_bon_achat' => $promo->getCode()));
  1269.         if ($up != null) {
  1270.           $c['use'] = true;
  1271.         } else {
  1272.           $c['use'] = false;
  1273.         }
  1274.         array_push($results$c);
  1275.       }
  1276.       $giftCards $this->em->getRepository('App:CarteCadeau')->getUsersCards($userToken->getUser()->getId());
  1277.       $giftCardsPrint $this->em->getRepository('App:CarteCadeau')->getUsersCardsPrint($userToken->getUser()->getId());
  1278.       foreach ($giftCardsPrint as &$giftCardPrint) {
  1279.         $giftCardPrint['transaction_reference'] = "";
  1280.         $transactionItem $this->em->getRepository('App:TransactionItems')->findOneBy([
  1281.           'cartecadeau' => $giftCardPrint['id'],
  1282.         ]);
  1283.         if ($transactionItem) {
  1284.           $transaction $this->em->getRepository('App:Transaction')->findOneBy([
  1285.             'id' => $transactionItem->getTransaction(),
  1286.           ]);
  1287.           if ($transaction) {
  1288.             $giftCardPrint['transaction_reference'] = $transaction->getReferenceInterne();
  1289.           }
  1290.         }
  1291.       }
  1292.       return new JsonResponse(array('coupons' => $results'giftcards' => $giftCards'giftCardsPrint' => $giftCardsPrint));
  1293.     }
  1294.     return new JsonResponse(array("error" => "Une erreur s'est produite, veuillez vous relogger"));
  1295.   }
  1296.   /**
  1297.    * @Route("/api/price/validate", name="price_validate")
  1298.    */
  1299.   public function price_validate(Request $request): JsonResponse
  1300.   {
  1301.     $products $request->request->get('products');
  1302.     $devise $this->em->getRepository(Devise::class)->find(4);
  1303.     $results = array();
  1304.     foreach ($products as $product_id) {
  1305.       $product $this->em->getRepository(Produit::class)->findOneBy(['id' => (int)$product_id]);
  1306.       if ($product == null) {
  1307.         array_push($results, array(
  1308.           'id' => $product_id,
  1309.           'prix' => "price not found"
  1310.         ));
  1311.       } else {
  1312.         $prix $product->getPrix();
  1313.         $datejour = new \DateTime();
  1314.         $prices_ca = array();
  1315.         foreach ($prix as $pp) {
  1316.           if ($pp->getDevise()->getCode() == "CAD") {
  1317.             if ($pp->getDateFin() == null || $pp->getDateFin() >= $datejour) {
  1318.               array_push($prices_ca, array(
  1319.                 'prix' => $pp->getPrixTtc(),
  1320.                 'date' => $pp->getDateFin(),
  1321.                 'precommande' => $pp->getPrecommande(),
  1322.                 'tva' => ($pp->getTva() != null) ? $pp->getTva()->getTaux() : null
  1323.               ));
  1324.             }
  1325.           }
  1326.         }
  1327.         usort($prices_ca$this->build_sorter('date'));
  1328.         if (empty($prices_ca)) {
  1329.           array_push($results, array(
  1330.             'id' => $product_id,
  1331.             'prix' => "price not found"
  1332.           ));
  1333.         } else {
  1334.           array_push($results, array(
  1335.             'id' => $product_id,
  1336.             'prix' => $prices_ca[0]['prix']
  1337.           ));
  1338.         }
  1339.       }
  1340.     }
  1341.     return new JsonResponse($results);
  1342.   }
  1343.   private
  1344.   function build_sorter($key): \Closure
  1345.   {
  1346.     return function ($a$b) use ($key) {
  1347.       //si null
  1348.       if ($a[$key] == null) {
  1349.         return 1;
  1350.       } else if ($b[$key] == null) {
  1351.         return -1;
  1352.       }
  1353.       if ($a[$key] > $b[$key]) {
  1354.         return -1;
  1355.       } else {
  1356.         return 1;
  1357.       }
  1358.     };
  1359.   }
  1360.   private function build_sorter_prices($key): \Closure
  1361.   {
  1362.     return function ($a$b) use ($key) {
  1363.       if ($a[$key] === null && $b[$key] === null) {
  1364.         return $b['id'] <=> $a['id'];
  1365.       } else if ($a[$key] === null) {
  1366.         return 1;
  1367.       } else if ($b[$key] === null) {
  1368.         return -1;
  1369.       }
  1370.       return $a[$key] <=> $b[$key]; // Otherwise, compare ending dates
  1371.     };
  1372.   }
  1373.   /**
  1374.    * @Route("/api/coupons/check", name="api_check_code_promo")
  1375.    *
  1376.    * CAUTION!!!
  1377.    * In this function there is a misuse of the total_ttc variable name that may cause confusion for the CAD version.
  1378.    * total_ttc = total price with taxes included
  1379.    * total_ht = total price without taxes
  1380.    */
  1381.   public
  1382.   function api_check_code_promo(Request $request): JsonResponse
  1383.   {
  1384.     $post $request->request;
  1385.     $token $request->headers->get('token');
  1386.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  1387.     if ($userToken != null && (time() - $userToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION) {
  1388.       $array_products json_decode($post->get('cart_products'), true);
  1389.       if ($post->get('cart_products') == null || !$array_products || $post->get('code_promo') == null || $post->get('ttc_total') == null) {
  1390.         return new JsonResponse(array('error' => 'Problem de paramètres'));
  1391.       }
  1392.       $cart_products $array_products['products'];
  1393.       $json = array();
  1394.       $json['error'] = "";
  1395.       $tvas = array(
  1396.         '5.500' => 0,
  1397.         '20.000' => 0,
  1398.         '14.975' => 0,
  1399.         '0.000' => 0
  1400.       );
  1401.       $total_ttc = (float)$post->get('ttc_total');
  1402.       $total_ht $total_ttc// This is helpful only for CAD
  1403.       if ($post->get('isCa') == 1) {
  1404.         $total_ht $total_ttc / (14.975 100);
  1405.       }
  1406.       $campagne_b false;
  1407.       $ccadeau false;
  1408.       $devise_id 1;
  1409.       $devise_code 'EUR';
  1410.       if ($post->get('isCa') == 1) {
  1411.         $devise_id 4;
  1412.         $devise_code "CAD";
  1413.       }
  1414.       $promo $this->em->getRepository(Promotion::class)->getCartPromo($post->get('code_promo'), $devise_id);
  1415.       if ($promo == null) {
  1416.         $promo $this->em->getRepository('App:CampagneCode')->getCartPromo($post->get('code_promo'));
  1417.         if ($promo != null) {
  1418.           $campagne_b true;
  1419.         }
  1420.       }
  1421.       if ($promo == null) {
  1422.         $promo $this->em->getRepository(CarteCadeau::class)->getCartPromo($post->get('code_promo'), $devise_id);
  1423.         if (!$promo) {
  1424.           $promo $this->em->getRepository(CarteCadeau::class)->getGiftCardPrint($post->get('code_promo'), $devise_id);
  1425.         }
  1426.         if ($promo != null) {
  1427.           $promo['type_valeur'] = 0;
  1428.           $promo['payeur'] = 'bookdoreille';
  1429.           if ($promo['solde_utilise'] >= $promo['valeur']) {
  1430.             $promo['valeur'] = 0;
  1431.             return new JsonResponse(array(
  1432.               'error' => 'Votre carte cadeau n\'a pas de solde.'
  1433.             ));
  1434.           } else {
  1435.             $promo['valeur'] = $promo['valeur'] - $promo['solde_utilise'];
  1436.           }
  1437.           $ccadeau true;
  1438.         }
  1439.       }
  1440.       if ($promo != null) {
  1441.         $json['devise'] = $devise_id;
  1442.         $json['type_valeur'] = $promo['type_valeur'];
  1443.         $montant_promo $promo['valeur'];
  1444.         $check_promo $this->em->getRepository(UserPromotions::class)->getPromoUser($promo['id'], $userToken->getUser()->getId());
  1445.         if (!$campagne_b) {
  1446.           if ($ccadeau === false && $check_promo != null) {
  1447.             return new JsonResponse(array('error' => 'Désolé, ce code a déja Ã©té utilisé.'));
  1448.           }
  1449.         } else {
  1450.           $campagnecode $this->em->getRepository('App:CampagneCode')
  1451.             ->findOneBy(array('code' => $post->get('code_promo')));
  1452.           $check_promo $this->em->getRepository('App:UserCampagnes')
  1453.             ->findOneBy(array('campagne_code' => $campagnecode));
  1454.           if ($check_promo != null) {
  1455.             return new JsonResponse(array(
  1456.               'error' => 'Le code saisit correspond Ã  un code promo: Désolé, ce code a déja Ã©té utilisé'
  1457.             ));
  1458.           }
  1459.         }
  1460.         $users $this->em->getRepository(Promotion::class)->getPromoUsers($promo['id']);
  1461.         $b true;
  1462.         if ($ccadeau === false && $campagne_b === false && $users != null) {
  1463.           $b false;
  1464.           if ($users['id'] == $userToken->getUser()->getId()) {
  1465.             $b true;
  1466.           }
  1467.         }
  1468.         if ($b === true) {
  1469.           if ($ccadeau === false) {
  1470.             if ($campagne_b === false) {
  1471.               $products $this->em->getRepository('App:Promotion')->getPromoProducts($promo['id']);
  1472.             } else {
  1473.               $products $this->em->getRepository('App:CampagnePromo')->getPromoProducts($promo['id']);
  1474.             }
  1475.           } else {
  1476.             $products = array();
  1477.           }
  1478.           if (!empty($products)) {
  1479.             $a false;
  1480.             $pallowed = array();
  1481.             $ttc_promo 0;
  1482.             foreach ($products as $p) {
  1483.               if (array_key_exists($p['id'], $cart_products)) {
  1484.                 $pallowed[] = $p['id'];
  1485.                 if ($devise_id === 4) {
  1486.                   $ttc_promo += $cart_products[$p['id']]/1.14975;
  1487.                 } else {
  1488.                   $ttc_promo += $cart_products[$p['id']];
  1489.                 }
  1490.                 $a true;
  1491.               }
  1492.             }
  1493.             if ($a) {
  1494.               if ($promo['type_valeur'] == 0) {
  1495.                 $total_ttc $total_ttc $promo['valeur'];
  1496.                 if (($total_ttc) <= 0) {
  1497.                   if ($post->get('ttc_total') > $promo['valeur']) {
  1498.                     $montant_promo $promo['valeur'];
  1499.                     if ($devise_id === 4) {
  1500.                       $total_ttc = ($post->get('ttc_total') / (0.14975)) - $promo['valeur'];
  1501.                     } else {
  1502.                       $total_ttc $post->get('ttc_total') - $promo['valeur'];
  1503.                     }
  1504.                   } else {
  1505.                     if ($devise_id === 4) {
  1506.                       $montant_promo = ($post->get('ttc_total') / (0.14975));
  1507.                     } else {
  1508.                       $montant_promo $post->get('ttc_total');
  1509.                     }
  1510.                     $total_ttc 0;
  1511.                   }
  1512.                 } else {
  1513.                   foreach ($cart_products as $id => $amount) {
  1514.                     $montant_part 0;
  1515.                     if (in_array($id$pallowed)) {
  1516.                       $part $amount $ttc_promo 100;
  1517.                       $montant_part $montant_promo $part 100;
  1518.                     }
  1519.                     $prix $this->em->getRepository('App:ProduitPrix')->getProductPrice($id$devise_code);
  1520.                     $prix_ht = ($amount $montant_part) / ($prix['taux'] / 100);
  1521.                     $tva round($prix_ht * ($prix['taux'] / 100), 2);
  1522.                     $tvas[$prix['taux']] += $tva;
  1523.                     if ($post->get('isCa') == 1) {
  1524.                       $tvas['5.000'] = round($prix_ht * (100), 2);
  1525.                       $tvas['9.975'] = round($prix_ht * (9.975 100), 2);
  1526.                     }
  1527.                   }
  1528.                 }
  1529.                 $rtva = array();
  1530.                 foreach ($tvas as $key => $val) {
  1531.                   $tvva $this->em->getRepository('App:Tva')->findOneByTaux($key);
  1532.                   $tva_id null;
  1533.                   if ($tvva != null) {
  1534.                     $tva_id $tvva->getId();
  1535.                   }
  1536.                   array_push($rtva, array('id' => $tva_id'taux' => $key'val' => round($val2)));
  1537.                 }
  1538.                 $json['montant_promo'] = round($montant_promo2);
  1539.                 $json['total_ttc'] = round($total_ttc2);
  1540.                 $json['tvas'] = $rtva;
  1541.               } else {
  1542.                 $montant_promo $ttc_promo * ($montant_promo 100);
  1543.                 foreach ($cart_products as $id => $amount) {
  1544.                   $montant_part 0;
  1545.                   if (in_array($id$pallowed)) {
  1546.                     $part $amount $ttc_promo 100;
  1547.                     $montant_part $montant_promo $part 100;
  1548.                   }
  1549.                   $prix $this->em->getRepository('App:ProduitPrix')->getProductPrice($id$devise_code);
  1550.                   $prix_ht = ($amount $montant_part) / ($prix['taux'] / 100);
  1551.                   $tva round($prix_ht * ($prix['taux'] / 100), 2);
  1552.                   $tvas[$prix['taux']] += $tva;
  1553.                   if ($post->get('isCa') == 1) {
  1554.                     $tvas['5.000'] = round($prix_ht * (100), 2);
  1555.                     $tvas['9.975'] = round($prix_ht * (9.975 100), 2);
  1556.                   }
  1557.                 }
  1558.                 $rtva = array();
  1559.                 foreach ($tvas as $key => $val) {
  1560.                   $tvva $this->em->getRepository('App:Tva')->findOneByTaux($key);
  1561.                   $tva_id null;
  1562.                   if ($tvva != null) {
  1563.                     $tva_id $tvva->getId();
  1564.                   }
  1565.                   $rtva[] = array('id' => $tva_id'taux' => $key'val' => round($val2));
  1566.                 }
  1567.                 $total_ttc $total_ttc $montant_promo;
  1568.                 $json['montant_promo'] = round($montant_promo2);
  1569.                 $json['total_ttc'] = round($total_ttc2);
  1570.                 $json['tvas'] = $rtva;
  1571.               }
  1572.             } else {
  1573.               return new JsonResponse(array('error' => "Le code que vous avez renseigné n'est pas valable sur le(s) produit(s) que vous avez choisi"));
  1574.             }
  1575.           } else {
  1576.             if ($ccadeau === false && $check_promo != null) {
  1577.               return new JsonResponse(array('error' => 'Désolé, ce code a déja Ã©té utilisé.'));
  1578.             }
  1579.             if ($promo['type_valeur'] == 0) {
  1580.               $test_ttc $total_ttc $montant_promo;
  1581.               if (($test_ttc) <= 0) {
  1582.                 if ($post->get('ttc_total') > $promo['valeur']) {
  1583.                   $montant_promo $promo['valeur'];
  1584.                   if ($devise_id === 4) {
  1585.                     $total_ttc = ($post->get('ttc_total') / (0.14975)) - $promo['valeur'];
  1586.                   } else {
  1587.                     $total_ttc $post->get('ttc_total') - $promo['valeur'];
  1588.                   }
  1589.                 } else {
  1590.                   $montant_promo $post->get('ttc_total');
  1591.                   $total_ttc 0;
  1592.                 }
  1593.               } else {
  1594.                 foreach ($cart_products as $id => $amount) {
  1595.                   $part $amount $total_ttc 100;
  1596.                   $montant_part $montant_promo $part 100;
  1597.                   $prix $this->em->getRepository('App:ProduitPrix')->getProductPrice($id$devise_code);
  1598.                   if ($prix == null) {
  1599.                     return new JsonResponse(array('error' => 'Produit inexistant'));
  1600.                   }
  1601.                   $prix_ht $amount $montant_part / ($prix['taux'] / 100);
  1602.                   $tva round($prix_ht * ($prix['taux'] / 100), 2);
  1603.                   $tvas[$prix['taux']] += $tva;
  1604.                   if ($post->get('isCa') == 1) {
  1605.                     $tvas['5.000'] = round($prix_ht * (100), 2);
  1606.                     $tvas['9.975'] = round($prix_ht * (9.975 100), 2);
  1607.                   }
  1608.                 }
  1609.                 $total_ttc $total_ttc $montant_promo;
  1610.               }
  1611.               $rtva = array();
  1612.               foreach ($tvas as $key => $val) {
  1613.                 $tvva $this->em->getRepository('App:Tva')->findOneByTaux($key);
  1614.                 $tva_id null;
  1615.                 if ($tvva != null) {
  1616.                   $tva_id $tvva->getId();
  1617.                 }
  1618.                 array_push($rtva, array('id' => $tva_id'taux' => $key'val' => round($val2)));
  1619.               }
  1620.               $json['montant_promo'] = round($montant_promo2);
  1621.             } else {
  1622.               if ($post->get('isCa') == 1) {
  1623.                 $promo_reel $total_ht * ($montant_promo 100);
  1624.               } else {
  1625.                 $promo_reel $total_ttc * ($montant_promo 100);
  1626.               }
  1627.               foreach ($cart_products as $id => $amount) {
  1628.                 $part $amount $total_ttc 100;
  1629.                 $montant_part $promo_reel $part 100;
  1630.                 $prix $this->em->getRepository(ProduitPrix::class)->getProductPrice($id$devise_code);
  1631.                 if ($prix == null) {
  1632.                   return new JsonResponse(array('error' => 'Produit inexistant'));
  1633.                 }
  1634.                 $prix_ht = ($amount $montant_part) / ($prix['taux'] / 100);
  1635.                 $tva round($prix_ht * ($prix['taux'] / 100), 2);
  1636.                 $tvas[$prix['taux']] += $tva;
  1637.                 if ($post->get('isCa') == 1) {
  1638.                   $tvas['5.000'] = round($prix_ht * (100), 2);
  1639.                   $tvas['9.975'] = round($prix_ht * (9.975 100), 2);
  1640.                 }
  1641.               }
  1642.               $rtva = array();
  1643.               foreach ($tvas as $key => $val) {
  1644.                 $tvva $this->em->getRepository('App:Tva')->findOneByTaux($key);
  1645.                 $tva_id null;
  1646.                 if ($tvva != null) {
  1647.                   $tva_id $tvva->getId();
  1648.                 }
  1649.                 $rtva[] = array('id' => $tva_id'taux' => $key'val' => round($val2));
  1650.               }
  1651.               $total_ttc $total_ttc $total_ttc * ($montant_promo 100);
  1652.               if ($post->get('isCa') == 1) {
  1653.                 $total_ht $total_ht $total_ht * ($montant_promo 100);
  1654.               }
  1655.               $json['montant_promo'] = round($promo_reel2);
  1656.             }
  1657.             $json['total_ht'] = round($total_ht2); // This is helpful only for CAD
  1658.             $json['total_ttc'] = round($total_ttc2);
  1659.             $json['tvas'] = $rtva;
  1660.           }
  1661.         } else {
  1662.           return new JsonResponse(array('error' => "Vous n'ètes pas autorisé Ã  utiliser ce code promo"));
  1663.         }
  1664.       } else {
  1665.         return new JsonResponse(array('error' => "Le code que vous avez renseigné n'est pas valable, merci de vérifier votre saisie..."));
  1666.       }
  1667.       return new JsonResponse($json);
  1668.     }
  1669.     return new JsonResponse(array("error" => "Une erreur s'est produite, veuillez vous relogger"));
  1670.   }
  1671.   /**
  1672.    * @Route("/api/check-promo-code-credits", name="api_check_promo_code_credits")
  1673.    */
  1674.   public
  1675.   function api_check_promo_code_credits(Request $request): JsonResponse
  1676.   {
  1677.     $post $request->request;
  1678.     $token $request->headers->get('token');
  1679.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  1680.     if (!$userToken) {
  1681.       return new JsonResponse(['error' => 'Operation not permitted'], Response::HTTP_UNAUTHORIZED);
  1682.     }
  1683.     $code $post->get('code');
  1684.     if (!$code) {
  1685.       return new JsonResponse(['error' => 'codeInvalid'], Response::HTTP_BAD_REQUEST);
  1686.     }
  1687.     $codeObject $this->em->getRepository(GiftCreditsPromoCode::class)->findOneBy(array('code' => $code));
  1688.     if (!$codeObject) {
  1689.       return new JsonResponse(['error' => 'codeInvalid'], Response::HTTP_BAD_REQUEST);
  1690.     }
  1691.     if ($codeObject->isRedeemed()) {
  1692.       return new JsonResponse(['error' => 'codeRedeemed'], Response::HTTP_BAD_REQUEST);
  1693.     }
  1694.     $creditsCount $codeObject->getCredits();
  1695.     $userObject $userToken->getUser();
  1696.     $userCredits $userObject->getCredits();
  1697.     $userObject->setCredits($userCredits $creditsCount);
  1698.     $this->em->persist($userObject);
  1699.     $codeObject->setRedeemed(true);
  1700.     $codeObject->setRecipient($userObject);
  1701.     $this->em->persist($codeObject);
  1702.     $this->em->flush();
  1703.     $currentYear date('Y');
  1704.     $httpClient HttpClient::create();
  1705.     $message '{
  1706.               "key": "'$_ENV['MANDRILL_API_KEY_CA'] .'",
  1707.               "template_name": "credit-redeemed-notification",
  1708.               "template_content": [],
  1709.               "message": {
  1710.                   "from_email": "communication@narra.audio",
  1711.                   "from_name": "Narra",
  1712.                   "to": [
  1713.                       {
  1714.                           "email": "'.$userObject->getEmail().'",
  1715.                           "name": "'.$userObject->getPrenom().'",
  1716.                           "type": "to"
  1717.                       }
  1718.                   ],
  1719.                   "subject": "Votre crédit est maintenant activé !",
  1720.                   "merge_language": "mailchimp",
  1721.                   "global_merge_vars": [
  1722.                       {
  1723.                           "name": "COMPANY",
  1724.                           "content": "Narra"
  1725.                       },
  1726.                       {
  1727.                           "name": "CURRENT_YEAR",
  1728.                           "content": "'.$currentYear.'"
  1729.                       }
  1730.                   ]
  1731.               }
  1732.           }';
  1733.     try {
  1734.       $response $httpClient->request('POST''https://mandrillapp.com/api/1.0/messages/send-template', [
  1735.         'headers' => [
  1736.           'Content-Type' => 'application/json',
  1737.         ],
  1738.         'body' => $message,
  1739.       ]);
  1740.       $statusCode $response->getStatusCode();
  1741.       if ($statusCode !== 200) {
  1742.         $this->logger->error('Mailchimp Webhook request failed with status code: ' $statusCode);
  1743.       }
  1744.     } catch (TransportExceptionInterface $e) {
  1745.       $this->logger->error('Mailchimp Webhook request failed with error: ' $e->getMessage());
  1746.     }
  1747.     return new JsonResponse(['success' => true'credits' => $creditsCount], Response::HTTP_OK);
  1748.   }
  1749.   /**
  1750.    * @Route("/api/newpromofidelite", name="add_newpromofidelite")
  1751.    */
  1752.   public
  1753.   function add_newpromofidelite(Request $request): JsonResponse
  1754.   {
  1755.     $token $request->headers->get('token');
  1756.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  1757.     if ($userToken != null && (time() - $userToken->getCreatedAt()->getTimestamp()) < self::TOKEN_VALIDITY_DURATION) {
  1758.       $json = array();
  1759.       if ($userToken->getUser() != null && $userToken->getUser()->getFidelite() >= 10) {
  1760.         $date = new \DateTime;
  1761.         $points $userToken->getUser()->getFidelite();
  1762.         $valeur $points 10;
  1763.         $devise $this->em->getRepository('App:Devise')->find(1);
  1764.         $payeur $this->em->getRepository('App:PromotionPayeur')->find(1);
  1765.         $code 'PF' $this->generer_code_carte_cadeau(8);
  1766.         $date_fin = new \DateTime;
  1767.         $date_fin->modify('+1 year');
  1768.         $promotion = new Promotion;
  1769.         $promotion
  1770.           ->setCode($code)
  1771.           ->setDateDebut($date)
  1772.           ->setDateFin($date_fin)
  1773.           ->setValeur($valeur)
  1774.           ->setTypeValeur(0)
  1775.           ->setPayeur('bookdoreille')
  1776.           ->setDevise($devise)
  1777.           ->setService($devise->getCode() === "CAD" 1)
  1778.           ->setMultiUser(false)
  1779.           ->setPromotionPayeur($payeur)
  1780.           ->setUserAllowed($userToken->getUser());
  1781.         $this->em->persist($promotion);
  1782.         $user $userToken->getUser();
  1783.         $user->setFidelite(0);
  1784.         $this->em->persist($user);
  1785.         $this->em->flush();
  1786.         $json['success'] = true;
  1787.         $json['code'] = $code;
  1788.       } else {
  1789.         $json['success'] = false;
  1790.         $json['message'] = "Vous n'avez pas de points fidélité";
  1791.       }
  1792.       return new JsonResponse($json);
  1793.     }
  1794.     return new JsonResponse(array("error" => "Une erreur s'est produite, veuillez vous relogger"));
  1795.   }
  1796.   private
  1797.   function generer_code_carte_cadeau($length 8): string
  1798.   {
  1799.     $chars '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1800.     $string '';
  1801.     for ($i 0$i $length$i++) {
  1802.       $string .= $chars[rand(0strlen($chars) - 1)];
  1803.     }
  1804.     return $string;
  1805.   }
  1806.   private function processProducts($produits$type$country): array
  1807.   {
  1808.     $results = array();
  1809.     if (count($produits) > && $produits[0] !== null) {
  1810.       foreach ($produits as $p) {
  1811.         $categories = array();
  1812.         $categories_id = array();
  1813.         $genresSerie = array();
  1814.         if ($p->getGenre1() != null) {
  1815.           if ($p->getGenre1()->getGroupe() != null) {
  1816.             $categories_id[] = $p->getGenre1()->getGroupe()->getId();
  1817.           }
  1818.           $genresSerie[] = $p->getGenre1()->getId();
  1819.         }
  1820.         if ($p->getGenre2() != null) {
  1821.           if ($p->getGenre2()->getGroupe() != null) {
  1822.             $categories_id[] = $p->getGenre2()->getGroupe()->getId();
  1823.           }
  1824.           $genresSerie[] = $p->getGenre2()->getId();
  1825.         }
  1826.         $categories_id array_unique($categories_id);
  1827.         foreach ($categories_id as $id) {
  1828.           $groupegenre $this->em->getRepository('App:GroupeGenres')->find($id);
  1829.           $categories[] = array('id' => $groupegenre->getId());
  1830.         }
  1831.         $sousGenresSerie = array();
  1832.         if ($p->getSousgenre1() != null) {
  1833.           $sousGenresSerie[] = $p->getSousgenre1()->getId();
  1834.         }
  1835.         if ($p->getSousgenre2() != null) {
  1836.           $sousGenresSerie[] = $p->getSousgenre2()->getId();
  1837.         }
  1838.         $themes = array();
  1839.         foreach ($p->getThemes() as $theme) {
  1840.           $themes[] = $theme->getId();
  1841.         }
  1842.         $jeunesse = array();
  1843.         if ($p->getPublics() != null && $p->getPublics()->getId() == 3) {
  1844.           $jeunesse = array(
  1845.             'detail_jeunesse' => ($p->getPublicsJeunesse() != null) ? $p->getPublicsJeunesse()->getLibelleFr() : null,
  1846.             'age_min' => $p->getJeunesseAgeMin(),
  1847.             'age_max' => $p->getJeunesseAgeMin()
  1848.           );
  1849.         }
  1850.         $auteurs = array();
  1851.         $authorsDetails = array();
  1852.         foreach ($p->getAuteurs() as $tier) {
  1853.           $auteurs[] = $tier->getId();
  1854.           $authorsDetails[] = array(
  1855.             "name" => $tier->getPrenom() . " " $tier->getNom(),
  1856.             "pseudonyme" => $tier->getPseudonyme(),
  1857.             "uri" => $tier->getAlgoliaName(),
  1858.             "id" => $tier->getId(),
  1859.             "image" => $tier->getImageName()
  1860.           );
  1861.         }
  1862.         $interpretes = array();
  1863.         $interpretersDetails = array();
  1864.         foreach ($p->getInterpretes() as $tier) {
  1865.           $interpretes[] = $tier->getId();
  1866.           $interpretersDetails[] = array(
  1867.             "name" => $tier->getPrenom() . " " $tier->getNom(),
  1868.             "pseudonyme" => $tier->getPseudonyme(),
  1869.             "uri" => $tier->getAlgoliaName(),
  1870.             "id" => $tier->getId(),
  1871.             "image" => $tier->getImageName()
  1872.           );
  1873.         }
  1874.         $publisher $p->getEditor();
  1875.         $publisherDetails = [];
  1876.         if ($publisher != null) {
  1877.           $publisherDetails = array(
  1878.             "name" => $publisher->getPrenom() . " " $publisher->getNom(),
  1879.             "slug" => $publisher->getAlgoliaName(),
  1880.           );
  1881.         }
  1882.         $traducteurs = array();
  1883.         foreach ($p->getTraducteurs() as $tier) {
  1884.           $traducteurs[] = $tier->getId();
  1885.         }
  1886.         $illustrateurs = array();
  1887.         foreach ($p->getIllustrateurs() as $tier) {
  1888.           $illustrateurs[] = $tier->getId();
  1889.         }
  1890.         $compositeurs = array();
  1891.         foreach ($p->getCompositeurs() as $tier) {
  1892.           $compositeurs[] = $tier->getId();
  1893.         }
  1894.         $prixlitteraires = array();
  1895.         foreach ($p->getPrixLitteraires() as $tier) {
  1896.           $prixlitteraires[] = $tier->getId();
  1897.         }
  1898.         $arr_prix_vente $this->em->getRepository(ProduitPrix::class)->getProductPrice($p->getId());
  1899.         $prix_vente null;
  1900.         $date_fin_precommande null;
  1901.         if ($arr_prix_vente != null) {
  1902.           $prix_vente $arr_prix_vente['prix_ttc'];
  1903.           if ($arr_prix_vente['precommande']) {
  1904.             $date_fin_precommande = ($arr_prix_vente['date_fin'] != null) ? $arr_prix_vente['date_fin'] : null;
  1905.           }
  1906.         }
  1907.         $arr_prix_vente_ca $this->em->getRepository(ProduitPrix::class)->getProductPrice($p->getId(), 'CAD');
  1908.         $prix_vente_ca null;
  1909.         if ($arr_prix_vente_ca != null) {
  1910.           $prix_vente_ca $arr_prix_vente_ca['prix_ttc'];
  1911.         }
  1912.         $prix $p->getPrix();
  1913.         $datejour = new \DateTime();
  1914.         $prices = array();
  1915.         $prices_ca = array();
  1916.         $tva null;
  1917.         foreach ($prix as $pp) {
  1918.           if ($pp->getDevise()->getCode() == "CAD") {
  1919.             if ($pp->getDateFin() == null || $pp->getDateFin() >= $datejour) {
  1920.               $prices_ca[] = array(
  1921.                 'id' => $pp->getId(),
  1922.                 'prix' => $pp->getPrixTtc(),
  1923.                 'date' => $pp->getDateFin(),
  1924.                 'precommande' => $pp->getPrecommande(),
  1925.                 'tva' => ($pp->getTva() != null) ? $pp->getTva()->getTaux() : null
  1926.               );
  1927.             }
  1928.           } else {
  1929.             if ($pp->getDateFin() == null || $pp->getDateFin() >= $datejour) {
  1930.               $prices[] = array(
  1931.                 'id' => $pp->getId(),
  1932.                 'prix' => $pp->getPrixTtc(),
  1933.                 'date' => $pp->getDateFin(),
  1934.                 'precommande' => $pp->getPrecommande(),
  1935.                 'tva' => ($pp->getTva() != null) ? $pp->getTva()->getTaux() : null
  1936.               );
  1937.             }
  1938.           }
  1939.         }
  1940.         usort($prices$this->build_sorter_prices('date'));
  1941.         $precommande false;
  1942.         if (empty($prices)) {
  1943.         } else {
  1944.           $tva $prices[0]['tva'];
  1945.           $precommande $prices[0]['precommande'];
  1946.         }
  1947.         usort($prices_ca$this->build_sorter_prices('date'));
  1948.         $precommandeCa false;
  1949.         if (empty($prices_ca)) {
  1950.         } else {
  1951.           $precommandeCa $prices_ca[0]['precommande'];
  1952.         }
  1953.         $genres = [
  1954.           $p->getGenre1(),
  1955.           $p->getGenre2(),
  1956.           $p->getSousgenre1(),
  1957.           $p->getSousgenre2()
  1958.         ];
  1959.         foreach ($genres as &$genre) {
  1960.           if ($genre !== null) {
  1961.             $genre $genre->getLibelleFr();
  1962.           }
  1963.         }
  1964.         $genres array_values(array_filter($genres));
  1965.         $editor $p->getEditor();
  1966.         $editorName = [];
  1967.         if ($editor != null) {
  1968.           $editorName = array(
  1969.             "name" => $editor->getPrenom() . " " $editor->getNom(),
  1970.             "slug" => $editor->getAlgoliaName(),
  1971.           );
  1972.         }
  1973.         $collectionDatas = [];
  1974.         if ($p->getCollection()) {
  1975.           $collectionDatas[] = [
  1976.             'libelle' => $p->getCollection()->getLibelleFr(),
  1977.             'description' => $p->getCollection()->getDescriptionFr(),
  1978.           ];
  1979.         }
  1980.         $translatorDatas = [];
  1981.         if ($p->getTraducteurs()) {
  1982.           foreach ($p->getTraducteurs() as $translator) {
  1983.             if ($translator) {
  1984.               $translatorDatas[] = [
  1985.                 'name' => $translator->getNom() . "-" $translator->getPrenom(),
  1986.                 'uri' => $translator->getNom() . "-" $translator->getPrenom(),
  1987.                 'algolia_name' => $translator->getAlgoliaName(),
  1988.               ];
  1989.             }
  1990.           }
  1991.         }
  1992.         $directorDatas = [];
  1993.         if ($p->getRealisateurs()) {
  1994.           foreach ($p->getRealisateurs() as $director) {
  1995.             if ($director) {
  1996.               $directorDatas[] = [
  1997.                 'name' => $director->getNom() . "-" $director->getPrenom(),
  1998.                 'uri' => $director->getNom() . "-" $director->getPrenom(),
  1999.                 'algolia_name' => $director->getAlgoliaName(),
  2000.               ];
  2001.             }
  2002.           }
  2003.         }
  2004.         $compositorDatas = [];
  2005.         if ($p->getCompositeurs()) {
  2006.           foreach ($p->getCompositeurs() as $compositor) {
  2007.             if ($compositor) {
  2008.               $compositorDatas[] = [
  2009.                 'name' => $compositor->getNom() . "-" $compositor->getPrenom(),
  2010.                 'uri' => $compositor->getNom() . "-" $compositor->getPrenom(),
  2011.                 'algolia_name' => $compositor->getAlgoliaName(),
  2012.               ];
  2013.             }
  2014.           }
  2015.         }
  2016.         $prix_streaming $p->getPrixStreaming();
  2017.         $prices_streaming = array();
  2018.         $price_streaming null;
  2019.         $tva_streaming null;
  2020.         $simultaneite_streaming null;
  2021.         $nb_prets_streaming null;
  2022.         $duree_exploitation_streaming null;
  2023.         $duree_pret_streaming null;
  2024.         foreach ($prix_streaming as $pp) {
  2025.           if ($pp->getDateFin() == null || $pp->getDateFin() >= $datejour) {
  2026.             $prices_streaming[] = array(
  2027.               'prix' => $pp->getPrix(),
  2028.               'date' => $pp->getDateFin(),
  2029.               'tva' => ($pp->getTva() != null) ? $pp->getTva()->getTaux() : null,
  2030.               'simultaneite' => $pp->getSimultaneite(),
  2031.               'nb_prets' => $pp->getNombrePret(),
  2032.               'duree_exploitation' => $pp->getDureeAnnee(),
  2033.               'duree_pret' => $pp->getDureePret()
  2034.             );
  2035.           }
  2036.         }
  2037.         usort($prices_streaming$this->build_sorter('date'));
  2038.         if (empty($prices_streaming)) {
  2039.         } else {
  2040.           $price_streaming $prices_streaming[0]['prix'];
  2041.           $tva_streaming $prices_streaming[0]['tva'];
  2042.           $simultaneite_streaming $prices_streaming[0]['simultaneite'];
  2043.           $nb_prets_streaming $prices_streaming[0]['nb_prets'];
  2044.           $duree_exploitation_streaming $prices_streaming[0]['duree_exploitation'];
  2045.           $duree_pret_streaming $prices_streaming[0]['duree_pret'];
  2046.         }
  2047.         $prix_education $p->getPrixEducation();
  2048.         $prices_education = array();
  2049.         $price_education null;
  2050.         $tva_education null;
  2051.         $simultaneite_education null;
  2052.         $nb_prets_education null;
  2053.         $duree_exploitation_education null;
  2054.         $duree_pret_education null;
  2055.         foreach ($prix_education as $pp) {
  2056.           if ($pp->getDateFin() == null || $pp->getDateFin() >= $datejour) {
  2057.             $prices_education[] = array(
  2058.               'prix' => $pp->getPrix(),
  2059.               'date' => $pp->getDateFin(),
  2060.               'tva' => ($pp->getTva() != null) ? $pp->getTva()->getTaux() : null,
  2061.               'simultaneite' => $pp->getSimultaneite(),
  2062.               'nb_prets' => $pp->getNombrePret(),
  2063.               'duree_exploitation' => $pp->getDureeAnnee(),
  2064.               'duree_pret' => $pp->getDureePret()
  2065.             );
  2066.           }
  2067.         }
  2068.         usort($prices_education$this->build_sorter('date'));
  2069.         if (empty($prices_education)) {
  2070.         } else {
  2071.           $price_education $prices_education[0]['prix'];
  2072.           $tva_education $prices_education[0]['tva'];
  2073.           $simultaneite_education $prices_education[0]['simultaneite'];
  2074.           $nb_prets_education $prices_education[0]['nb_prets'];
  2075.           $duree_exploitation_education $prices_education[0]['duree_exploitation'];
  2076.           $duree_pret_education $prices_education[0]['duree_pret'];
  2077.         }
  2078.         $tmp = array(
  2079.           'obj_id' => $p->getId(),
  2080.           'active' => $p->getActive(),
  2081.           'id_pipe_drive' => $p->getIdCrm(),
  2082.           'image_hd' => $this->domain 'produit/hd/' $p->getImageHdName(),
  2083.           'image_hd_name' => $p->getImageHdName(),
  2084.           'alt_image' => $p->getCopyrightImage(),
  2085.           'titre_fr' => $p->getTitreFr(),
  2086.           'sous_titre_fr' => $p->getSousTitreFr(),
  2087.           'titre_original' => $p->getTitreOriginal(),
  2088.           'serie' => array(
  2089.             'serie_id' => ($p->getSerie() != null) ? $p->getSerie()->getId() : null,
  2090.             'serie_titre' => ($p->getSerie() != null) ? $p->getSerie()->getTitre() : null,
  2091.             'tome' => $p->getNumeroTome(),
  2092.             'categories' => $categories,
  2093.             'genres' => $genresSerie,
  2094.             'sousgenres' => $sousGenresSerie
  2095.           ),
  2096.           'themes' => $themes,
  2097.           'public' => ($p->getPublics() != null) ? $p->getPublics()->getLibelleFr() : null,
  2098.           'jeunesse' => $jeunesse,
  2099.           'auteurs' => $auteurs,
  2100.           'authors_details' => $authorsDetails,
  2101.           'interpretes' => $interpretes,
  2102.           'interpreters_details' => $interpretersDetails,
  2103.           'traducteurs' => $traducteurs,
  2104.           'illustrateurs' => $illustrateurs,
  2105.           'compositeurs' => $compositeurs,
  2106.           'prix_litteraires' => $prixlitteraires,
  2107.           'editeur' => ($p->getEditor() != null) ? $p->getEditor()->getId() : null,
  2108.           'publisher_details' => $publisherDetails,
  2109.           'fournisseur' => ($p->getFournisseur() != null) ? $p->getFournisseur()->getId() : null,
  2110.           'version' => ($p->getVersion() != null) ? $p->getVersion()->getLibelleFr() : null,
  2111.           'duree' => $p->getDureeMin(),
  2112.           'collection' => ($p->getCollection() != null) ? $p->getCollection()->getLibelleFr() : null,
  2113.           'type_realisation' => ($p->getTypeRealisation() != null) ? $p->getTypeRealisation()->getLibelleFr() : null,
  2114.           'ean_telechargement' => $p->getEanTelechargement(),
  2115.           'ean_cd' => $p->getEanCd(),
  2116.           'resume' => $p->getResumeFr(),
  2117.           'url_presentation_origine' => $p->getUrlOriginePresentationFr(),
  2118.           'tracklist' => $p->getEnrichissementsFr(),
  2119.           'coup_de_coeur_libraire' => $p->getCoupDeCoeurLibraire(),
  2120.           'video_html' => $p->getVideo(),
  2121.           'url_extrait' => $this->file_service->getUrlExtrait($p->getId()),
  2122.           'annee_production' => $p->getAnneeProduction(),
  2123.           'annee_edition' => $p->getAnneeEdition(),
  2124.           'copyright' => $p->getCopyright(),
  2125.           'has_chapitre_gratuit' => $p->getBoolChapitreGratuit(),
  2126.           'langue_audio' => $p->getLangueSources(),
  2127.           'langue_originale' => $p->getLangueOriginale(),
  2128.           'prix_reference' => $p->getPrixReference(),
  2129.           'prix_reference_ca' => $p->getPrixReferenceCa(),
  2130.           'prix_vente' => $prix_vente,
  2131.           'prix_vente_ca' => $prix_vente_ca,
  2132.           'date_fin_precommande' => $date_fin_precommande,
  2133.           'is_new' => $p->getTitreALaUne(),
  2134.           'is_bestseller' => $p->getBestSeller(),
  2135.           'is_bestseller_ca' => $p->getBestSellerCa(),
  2136.           'is_exclu_numerique' => $p->getProduitAppel(),
  2137.           'date_creation' => ($p->getDateCreation() != null) ? $p->getDateCreation()->format('c') : null,
  2138.           'date_modification' => ($p->getDateUpdate() != null) ? $p->getDateUpdate()->format('c') : null,
  2139.           'alias_url' => $p->getAliasUrl(),
  2140.           'promotion' => $p->getPrixReference() != null && $p->getPrixReference() != $prix_vente,
  2141.           'promotion_ca' => $p->getPrixReferenceCa() != null && $p->getPrixReferenceCa() != $prix_vente_ca,
  2142.           'taux_tva' => $tva,
  2143.           'preorder' => $precommande,
  2144.           'preorder_ca' => $precommandeCa,
  2145.           'genres' => $genres,
  2146.           'editor' => $editorName,
  2147.           'id' => $p->getId(),
  2148.           'activate' => $p->getActive(),
  2149.           'activate_free_chapter' => $p->getBoolChapitreGratuit(),
  2150.           'date_updated' => $p->getDateUpdate(),
  2151.           'date_updated_timestamp' => $p->getDateUpdate() ? $p->getDateUpdate()->getTimestamp() : null,
  2152.           'exclus' => $p->getProduitAppel(),
  2153.           'title_on_page_one' => $p->getTitreALaUne(),
  2154.           'bibliostream' => $p->getBibliostream(),
  2155.           'isCa' => $p->getBoolCad(),
  2156.           'isEur' => $p->getBoolEur(),
  2157.           'tome' => $p->getNumeroTome(),
  2158.           'url_origin' => $p->getUrlOriginePresentationFr(),
  2159.           'video' => $p->getVideo(),
  2160.           'year_edition' => $p->getAnneeEdition(),
  2161.           'year_production' => $p->getAnneeProduction(),
  2162.           'collections' => $collectionDatas,
  2163.           'duree_min' => $p->getDureeMin(),
  2164.           'isbn' => $p->getIsbn(),
  2165.           'editor_number' => $p->getNumeroEditeur(),
  2166.           'ean_download' => $p->getEanTelechargement(),
  2167.           'ean_lend' => $p->getEanPret(),
  2168.           'ean' => $p->getEanTelechargement(),
  2169.           'abonnement' => $p->getAbonnement(),
  2170.           'abonnementCT' => $p->getIsAbonnementCT(),
  2171.           'isJeunesse' => $jeunesse,
  2172.           'translator' => $translatorDatas,
  2173.           'director' => $directorDatas,
  2174.           'compositor' => $compositorDatas,
  2175.           'image_liste_uri' => $p->getImageListeName(),
  2176.           'image_hd_uri' => $p->getImageHdName(),
  2177.           'product_uri' => $p->getAliasUrl(),
  2178.           'news' => $p->getTitreALaUne(),
  2179.           'bestseller' => $p->getBestSeller(),
  2180.           'bestseller_ca' => $p->getBestSellerCa(),
  2181.           'most_pre_purchased' => $p->getMostPrePurchased(),
  2182.           'most_pre_purchased_ca' => $p->getMostPrePurchasedCa(),
  2183.           'date_creation_timestamp' => $p->getDateCreation()->getTimestamp(),
  2184.           'date_fin_precommande_ca' => $p->getDateFinPrecommandeCa(),
  2185.           'duration' => intval($p->getDureeMin()),
  2186.           'prix_pnb' => (float)$price_streaming,
  2187.           'tva_pnb' => (float)$tva_streaming,
  2188.           'simultaneite_pnb' => $simultaneite_streaming,
  2189.           'nb_prets_pnb' => $nb_prets_streaming,
  2190.           'duree_exploitation_pnb' => $duree_exploitation_streaming,
  2191.           'duree_pret_pnb' => $duree_pret_streaming,
  2192.           'nb_tracks' => $p->getNbTracks(),
  2193.           'nb_audio_file' => $p->getNbAudioFiles(),
  2194.           'weight' => $p->getPoids(),
  2195.           'prix_pns' => (float)$price_education,
  2196.           'tva_pns' => (float)$tva_education,
  2197.           'simultaneite_pns' => $simultaneite_education,
  2198.           'nb_prets_pns' => $nb_prets_education,
  2199.           'duree_exploitation_pns' => $duree_exploitation_education,
  2200.           'duree_pret_pns' => $duree_pret_education,
  2201.           'coup_de_coeur' => $p->getCoupDeCoeurLibraire(),
  2202.           'coup_de_coeur_ca' => $p->getCoupDeCoeurLibraireCa(),
  2203.           'cat1A' => $p->getCat1A(),
  2204.           'cat2A' => $p->getCat2A(),
  2205.           'cat1B' => $p->getCat1B(),
  2206.           'cat2B' => $p->getCat2B(),
  2207.           'cat3' => $p->getCat3(),
  2208.           'livre_d_ici' => $p->getLivreDIci(),
  2209.         );
  2210.         if ($type === 'preorder') {
  2211.           if (($country === 'fr' && $precommande === true) || ($country === 'ca' && $precommandeCa === true)) {
  2212.             $results[] = $tmp;
  2213.           }
  2214.         } else {
  2215.           $results[] = $tmp;
  2216.         }
  2217.       }
  2218.     }
  2219.     return $results;
  2220.   }
  2221.   /**
  2222.    * @Route("/api/download-invoice", name="download_invoice")
  2223.    */
  2224.   public function downloadInvoice(Request $request): JsonResponse {
  2225.     $token $request->headers->get('token');
  2226.     $userToken $this->em->getRepository('App:AuthToken')->findOneBy(array('value' => $token));
  2227.     if (!$request->request->get('idTransaction') || !$userToken) {
  2228.       return new JsonResponse(array("error" => true"message" => "Transaction ID or user token were not found."), 500);
  2229.     }
  2230.     $transaction $this->em->getRepository(Transaction::class)->findOneBy(array('reference_interne' => $request->request->get('idTransaction')));
  2231.     if (!$transaction) {
  2232.       return new JsonResponse(array("error" => true"message" => "Transaction entity not found."), 500);
  2233.     }
  2234.     $devise $transaction->getDevise();
  2235.     $deviseId $devise->getId();
  2236.     $user $transaction->getClient();
  2237.     $cartObject json_decode($transaction->getCartJson());
  2238.     if ($cartObject && $deviseId === 4) {
  2239.       $productsCart $cartObject->items;
  2240.       $cartObject->giftMemberships = [];
  2241.     } else {
  2242.       $cartObject = new \stdClass();
  2243.       $cartObject->subscriptionDiscount 0;
  2244.       $cartObject->discount 0;
  2245.       $cartObject->isGiftCard false;
  2246.       $cartObject->giftCards = [];
  2247.       $cartObject->credits_cart 0;
  2248.       $cartObject->giftMemberships = [];
  2249.       $codePromo $transaction->getCodeBonAchat();
  2250.       $promo $this->em->getRepository('App:Promotion')->getCartPromo($codePromo$deviseId);
  2251.       if ($promo === null) {
  2252.         $promo $this->em->getRepository('App:CampagneCode')->getCartPromo($codePromo);
  2253.         if ($promo === null) {
  2254.           $promo $this->em->getRepository('App:CarteCadeau')->getCartPromo($codePromo$deviseId);
  2255.           if ($promo) {
  2256.             $cartObject->isGiftCard true;
  2257.           }
  2258.         }
  2259.       }
  2260.       if ($cartObject->isGiftCard && $deviseId === 4) {
  2261.         $cartObject->subtotal $transaction->getMontantHtNominal();
  2262.       } else {
  2263.         $cartObject->subtotal $transaction->getMontantHtReel();
  2264.       }
  2265.       $cartObject->total $transaction->getMontantTtcReel();
  2266.       if ($promo) {
  2267.         $cartObject->discount $transaction->getMontantBonAchat();
  2268.       }
  2269.       $productsCart = [];
  2270.       $transactionItems $this->em->getRepository('App:TransactionItems')->findBy([
  2271.         'transaction' => $transaction,
  2272.       ]);
  2273.       $cartObject->tps 0;
  2274.       $cartObject->tvq 0;
  2275.       foreach ($transactionItems as $transactionItem) {
  2276.         $product $transactionItem->getProduit();
  2277.         $giftCard $transactionItem->getCartecadeau();
  2278.         $transactionType $transactionItem->getType();
  2279.         $transactionTypeId $transactionType->getId();
  2280.         if ($product) {
  2281.           $productTemp = new \stdClass();
  2282.           $productTemp->id $product->getId();
  2283.           $productTemp->title $product->getTitreFr();
  2284.           $productTemp->price_no_discount $transactionItem->getPrixTtc();
  2285.           $productsCart[] = $productTemp;
  2286.           if ($deviseId === 1) {
  2287.             $cartObject->tps += $transactionItem->getTvaMontant();
  2288.           } else if ($deviseId === 4) {
  2289.             $priceWithoutTaxes $transactionItem->getTtcReel()/1.14975;
  2290.             $cartObject->tps += $priceWithoutTaxes * (5/100);
  2291.             $cartObject->tvq += $priceWithoutTaxes * (9.975/100);
  2292.           }
  2293.         } else if ($giftCard) {
  2294.           $productTemp = new \stdClass();
  2295.           $productTemp->id $giftCard->getId();
  2296.           $productTemp->title 'Carte cadeau';
  2297.           $productTemp->price $giftCard->getValeur();
  2298.           $cartObject->giftCards[] = $productTemp;
  2299.         } else if ($transactionTypeId === 4) {
  2300.           $giftMembership $transactionItem->getGiftMembership();
  2301.           $productTemp = new \stdClass();
  2302.           $productTemp->id $giftMembership->getId();
  2303.           $productTemp->title 'Abonnement cadeau (' $giftMembership->getMonths() . ' mois)';
  2304.           $productTemp->price $transactionItem->getHtReel();
  2305.           $cartObject->tps += $transactionItem->getHtReel() * (5/100);
  2306.           $cartObject->tvq += $transactionItem->getHtReel() * (9.975/100);
  2307.           $cartObject->giftMemberships[] = $productTemp;
  2308.         }
  2309.       }
  2310.       if ($transaction->getCredits()) {
  2311.         $cartObject->credits_cart $transaction->getCredits();
  2312.       }
  2313.     }
  2314.     $decimalSeparator '.';
  2315.     $thousandsSeparator ',';
  2316.     if ($deviseId === 4) {
  2317.       $decimalSeparator ',';
  2318.       $thousandsSeparator '.';
  2319.     }
  2320.     $subtotal number_format($cartObject->subtotal2$decimalSeparator$thousandsSeparator);
  2321.     if ($cartObject->subtotal >= && $cartObject->subtotal 10) {
  2322.       $subtotal '0' $subtotal;
  2323.     }
  2324.     $tps number_format($cartObject->tps2$decimalSeparator$thousandsSeparator);
  2325.     if ($cartObject->tps >= && $cartObject->tps 10) {
  2326.       $tps '0' $tps;
  2327.     }
  2328.     $tvq number_format($cartObject->tvq2$decimalSeparator$thousandsSeparator);
  2329.     if ($cartObject->tvq >= && $cartObject->tvq 10) {
  2330.       $tvq '0' $tvq;
  2331.     }
  2332.     $total number_format($cartObject->total2$decimalSeparator$thousandsSeparator);
  2333.     if ($cartObject->total >= && $cartObject->total 10) {
  2334.       $total '0' $total;
  2335.     }
  2336.     $discountPromo "";
  2337.     $discountGiftCard "";
  2338.     $subscriptionDiscount "";
  2339.     $productsFinal = [];
  2340.     if ($cartObject->subscriptionDiscount != 0) {
  2341.       $subscriptionDiscount .= number_format($cartObject->subscriptionDiscount2$decimalSeparator$thousandsSeparator);
  2342.       if ($cartObject->subscriptionDiscount >= && $cartObject->subscriptionDiscount 10) {
  2343.         $subscriptionDiscount '0' $subscriptionDiscount;
  2344.       }
  2345.     }
  2346.     if ($cartObject->isGiftCard && $cartObject->discount != 0) {
  2347.       $discountGiftCard .= number_format($cartObject->discount2$decimalSeparator$thousandsSeparator);
  2348.       if ($cartObject->discount >= && $cartObject->discount 10) {
  2349.         $discountGiftCard '0' $discountGiftCard;
  2350.       }
  2351.     }
  2352.     if (!$cartObject->isGiftCard && $cartObject->discount != 0) {
  2353.       $discountPromo .= number_format($cartObject->discount2$decimalSeparator$thousandsSeparator);
  2354.       if ($cartObject->discount >= && $cartObject->discount 10) {
  2355.         $discountPromo '0' $discountPromo;
  2356.       }
  2357.     }
  2358.     $counter 0;
  2359.     foreach ($productsCart as $product) {
  2360.       $productEntity $this->em->getRepository('App:Produit')->find($product->id);
  2361.       $productsFinal[$counter]["title"] = $product->title;
  2362.       $productsFinal[$counter]["ean"] = $productEntity->getEanTelechargement();
  2363.       $productsFinal[$counter]["quantity"] = 1;
  2364.       if ($deviseId === 1) {
  2365.         $productsFinal[$counter]["price"] = number_format($product->price_no_discount2$decimalSeparator$thousandsSeparator);
  2366.       } else if ($deviseId === 4) {
  2367.         $productsFinal[$counter]["price"] = number_format($product->price_no_discount/1.149752$decimalSeparator$thousandsSeparator) . ' $';
  2368.         if (($product->price_no_discount/1.14975) >= && ($product->price_no_discount/1.14975) < 10) {
  2369.           $productsFinal[$counter]["price"] = '0' $productsFinal[$counter]["price"];
  2370.         }
  2371.       }
  2372.       $counter++;
  2373.     }
  2374.     if ($cartObject->credits_cart != 0) {
  2375.       $productsFinal[$counter]["ean"] = 'CREDITS'.($cartObject->credits_cart*5);
  2376.       $productsFinal[$counter]["title"] = 'Lot de '.($cartObject->credits_cart*5).' crédits';
  2377.       $productsFinal[$counter]["price"] = number_format($cartObject->credits_cart*74.992$decimalSeparator$thousandsSeparator) . ' $';
  2378.       $productsFinal[$counter]["quantity"] = 1;
  2379.       $counter++;
  2380.     }
  2381.     foreach ($cartObject->giftCards as $giftCard) {
  2382.       $productsFinal[$counter]["ean"] = $giftCard->id;
  2383.       $productsFinal[$counter]["title"] = "Carte cadeau";
  2384.       if ($deviseId === 1) {
  2385.         $productsFinal[$counter]["price"] = $giftCard->price;
  2386.       } else if ($deviseId === 4) {
  2387.         $productsFinal[$counter]["price"] = number_format($giftCard->price2$decimalSeparator$thousandsSeparator) . ' $';
  2388.       }
  2389.       $productsFinal[$counter]["quantity"] = 1;
  2390.       $counter++;
  2391.     }
  2392.     foreach ($cartObject->giftMemberships as $giftMembership) {
  2393.       $productsFinal[$counter]["ean"] = $giftMembership->id;
  2394.       $productsFinal[$counter]["title"] = $giftMembership->title;
  2395.       $productsFinal[$counter]["price"] = number_format($giftMembership->price2$decimalSeparator$thousandsSeparator) . ' $';;
  2396.       $productsFinal[$counter]["quantity"] = 1;
  2397.       $counter++;
  2398.     }
  2399.     $productsJsonString '';
  2400.     $counter 0;
  2401.     foreach ($productsFinal as $product) {
  2402.       $productsJsonString .= '{
  2403.         "ean": "'.$product['ean'].'",
  2404.         "quantity": "'.$product['quantity'].'",
  2405.         "product": "'.$product['title'].'",
  2406.         "price": "'.$product['price'].'"
  2407.       }';
  2408.       if ($counter != (sizeof($productsFinal) - 1)) {
  2409.         $productsJsonString .= ',';
  2410.       }
  2411.       $counter++;
  2412.     }
  2413.     $downloadURL '';
  2414.     $client HttpClient::create();
  2415.     $templateId '';
  2416.     if ($deviseId === 1) {
  2417.       $templateId 'C18B2177-2FF8-431E-8CA7-19DC99B67388';
  2418.     } else if ($deviseId === 4) {
  2419.       $templateId 'D28EC1E5-E228-45D7-947A-767F344EAEF1';
  2420.     }
  2421.     try {
  2422.       $res $client->request('POST'"https://api.pdfmonkey.io/api/v1/documents", [
  2423.         'headers' => [
  2424.           'Authorization' => 'Bearer ' $_ENV["PDFMONKEY_API_KEY"],
  2425.           'Content-Type' => 'application/json'
  2426.         ],
  2427.         'body' => '{
  2428.             "document": {
  2429.               "document_template_id": "'.$templateId.'",
  2430.               "status": "pending",
  2431.               "payload": {
  2432.                 "client_name": "'.$user->getPrenom().' '.$user->getNom().'",
  2433.                 "client_address": "'.$user->getAdressePostale().'",
  2434.                 "client_city": "'.$user->getVille().'",
  2435.                 "client_zip": "'.$user->getCodePostal().'",
  2436.                 "client_state": "'.$user->getProvince().'",
  2437.                 "client_country": "'.$user->getPays().'",
  2438.                 "client_email": "'.$user->getEmail().'",
  2439.                 "date": "'.$transaction->getDate()->format('d/m/Y').'",
  2440.                 "transaction": "'.$transaction->getReferenceInterne().'",
  2441.                 "payment_mode": "'.$transaction->getTerminal().' (Carte)",
  2442.                 "promo_code": "'.$transaction->getCodeBonAchat().'",
  2443.                 "promo_discount": "'.$discountPromo.'",
  2444.                 "membership_discount": "'.$subscriptionDiscount.'",
  2445.                 "gift_card_discount": "'.$discountGiftCard.'",
  2446.                 "subtotal": "'.$subtotal.'",
  2447.                 "tps": "'.$tps.'",
  2448.                 "tvq": "'.$tvq.'",
  2449.                 "total": "'.$total.'",
  2450.                 "item": [{
  2451.                   "produit":[
  2452.                     '.$productsJsonString.'
  2453.                   ]}
  2454.                 ]
  2455.               }
  2456.             }
  2457.           }'
  2458.       ]);
  2459.       $jsonString $res->getContent();
  2460.       $documentData json_decode($jsonStringtrue);
  2461.       if ($documentData) {
  2462.         $counter 0;
  2463.         while (true) {
  2464.           sleep(2);
  2465.           $res $client->request('GET'"https://api.pdfmonkey.io/api/v1/document_cards/" $documentData["document"]["id"], [
  2466.             'headers' => [
  2467.               'Authorization' => 'Bearer ' $_ENV["PDFMONKEY_API_KEY"],
  2468.               'Content-Type' => 'application/json'
  2469.             ]
  2470.           ]);
  2471.           $jsonString $res->getContent();
  2472.           $documentCardData json_decode($jsonStringtrue);
  2473.           if ($documentCardData['document_card']['download_url'] !== null) {
  2474.             $downloadURL $documentCardData['document_card']['download_url'];
  2475.             break;
  2476.           }
  2477.           if ($counter 10) {
  2478.             break;
  2479.           }
  2480.           $counter++;
  2481.         }
  2482.       } else {
  2483.         return new JsonResponse(array("error" => true"message" => "No document data."), 500);
  2484.       }
  2485.     } catch (Exception|RedirectionExceptionInterface|TransportExceptionInterface|ClientExceptionInterface|ServerExceptionInterface $e) {
  2486.       return new JsonResponse(array("error" => true"message" => $e->getMessage()), 500);
  2487.     }
  2488.     return new JsonResponse(array("success" => true"message" => "Success""downloadURL" => $downloadURL), 200);
  2489.   }
  2490. }