src/Controller/Admin/CommandeCrudController.php line 229

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Admin;
  3. use App\Entity\Article;
  4. use App\Entity\CommandArticle;
  5. use App\Entity\Commande;
  6. use App\Entity\User;
  7. use App\Service\NotificationManager;
  8. use DateTime;
  9. use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
  10. use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
  11. use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
  12. use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
  13. use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
  14. use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
  15. use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
  16. use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
  17. use App\Form\CommandArticleType;
  18. use App\Repository\AdresseRepository;
  19. use App\Repository\GouvernoratRepository;
  20. use App\Repository\UniteRegionalRepository;
  21. use Doctrine\ORM\EntityManager;
  22. use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
  23. use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
  24. use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
  25. use Symfony\Component\Routing\Annotation\Route;
  26. use Doctrine\ORM\EntityManagerInterface;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\HttpFoundation\Request;
  29. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  30. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  31. use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
  32. use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
  33. use EasyCorp\Bundle\EasyAdminBundle\Field\Field;
  34. use Symfony\Component\HttpFoundation\JsonResponse;
  35. use Symfony\Component\Routing\RouterInterface;
  36. use Symfony\Component\Serializer\SerializerInterface;
  37. use Symfony\Component\Security\Core\Security;
  38. use Symfony\Component\HttpFoundation\RequestStack;
  39. use Knp\Component\Pager\PaginatorInterface;
  40. use EasyCorp\Bundle\EasyAdminBundle\Config\Assets;
  41. use EasyCorp\Bundle\EasyAdminBundle\Config\Asset;
  42. use EasyCorp\Bundle\EasyAdminBundle\Field\HiddenField;
  43. use App\Service\ExportExl;
  44. use EasyCorp\Bundle\EasyAdminBundle\Filter\ArrayFilter;
  45. use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
  46. class CommandeCrudController extends AbstractCrudController
  47. {
  48.     public $em;
  49.     private $adminUrlGenerator;
  50.     private $request;
  51.      /**
  52.      * @param EntityManagerInterface $em
  53.      */
  54.     public function __construct(EntityManagerInterface $emRequestStack $requestAdminUrlGenerator $adminUrlGenerator)
  55.     {
  56.         $this->em $em;
  57.         $this->adminUrlGenerator $adminUrlGenerator;
  58.     }
  59.     public static function getEntityFqcn(): string
  60.     {
  61.         return Commande::class;
  62.     }
  63.     public function configureAssets(Assets $assets): Assets
  64.     {
  65.         return $assets->addJsFile(Asset::new('js/commandJs.js')->defer());
  66.     }
  67.     public function configureFields(string $pageName): iterable
  68.     {
  69.         return [
  70.             HiddenField::new('id')->hideOnIndex(),
  71.             AssociationField::new('user''nom utilisateur')->hideOnForm(),
  72.             DateField::new('date''Date')->setFormTypeOption('disabled''disabled')->setFormTypeOption('disabled''disabled'),
  73.             Field::new('tel','Tel')->setFormTypeOption('disabled''disabled')->setFormTypeOptions(["attr" => ['min' => '0''maxlength' => ,'pattern'=>'\d{8}''oninput'=>"this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"]])->setRequired(true),
  74.             TextField::new('email''Email')->setFormTypeOption('disabled''disabled'),
  75.             TextField::new('etat''Etat')->setFormTypeOption('disabled''disabled'),
  76.             // TextareaField::new('motifs', 'Motif de refus')->hideOnIndex(),
  77.             NumberField::new('totalPrice')->setFormTypeOption('disabled''disabled')->hideOnIndex(),
  78.             // CollectionField::new('commandes', 'Commandes')
  79.             //     ->allowAdd(true)
  80.             //     ->allowDelete(true)
  81.             //     ->setEntryIsComplex(true)
  82.             //     ->setEntryType(CommandArticleType::class)
  83.             //     ->setFormTypeOptions([
  84.             //         'by_reference' => 'true',
  85.             //         'mapped' => true,
  86.             //         'required' => true
  87.             //     ])->hideOnIndex()
  88.         ];
  89.     }
  90.     public function configureActions(Actions $actions): Actions
  91.     {
  92.         $excelExport Action::new('excelExport''Excel')
  93.         ->setIcon('fa fa-download')
  94.         ->linkToCrudAction('excelExport')
  95.         ->setCssClass('btn')
  96.         ->createAsGlobalAction();
  97.         $actions->add(Crud::PAGE_INDEXAction::DETAIL)
  98.             ->add(Crud::PAGE_INDEX$excelExport)
  99.             ->remove(Crud::PAGE_INDEXAction::NEW)
  100.             ->remove(Crud::PAGE_DETAILAction::EDIT)
  101.             ->remove(Crud::PAGE_EDITAction::SAVE_AND_CONTINUE)
  102.             ->remove(Crud::PAGE_EDITAction::SAVE_AND_RETURN)
  103.             ->remove(Crud::PAGE_INDEXAction::DETAIL)
  104.             ->update(Crud::PAGE_INDEXAction::EDIT, function (Action $action) {
  105.                 return $action->setLabel('Visualiser');
  106.             })
  107.             ->update(Crud::PAGE_NEWAction::SAVE_AND_RETURN, function (Action $action) {
  108.                 return $action->setLabel('Enregistrer');
  109.             });
  110.         ;
  111.         $valider Action::new('valider''Valider''fa fa-check-circle')
  112.             ->linkToCrudAction('validerLCommande')->displayIf(static function ($entity) {
  113.                 return $entity->getEtat() == 'En cours';
  114.             });
  115.         $refuser Action::new('refuser''Refuser''fa fa-ban')
  116.             ->linkToUrl("#")->setHtmlAttributes(['id' => 'refuseBtn'])->displayIf(static function ($entity) {
  117.                 return $entity->getEtat() == 'En cours';
  118.             });
  119.         return $actions
  120.             ->add(Crud::PAGE_EDIT$valider)
  121.           //  ->add(Crud::PAGE_EDIT, $refuser)
  122.             ->add(Crud::PAGE_INDEX$valider)
  123.         ;
  124.     }
  125.     public function validerLCommande(EntityManagerInterface $entityManager,  RouterInterface $router ,AdminContext $context NotificationManager  $notificationManager)
  126.     {
  127.         $lcommande $context->getEntity()->getInstance();
  128.        
  129.         $lCommandArticle $entityManager->getRepository(CommandArticle::class)->findBy([
  130.             'Commande' => $lcommande->getId()
  131.         ]);     
  132.            foreach ($lCommandArticle as $commandArticle) {
  133.             $qnt 0;
  134.             $qnt $commandArticle->getQuantite();
  135.             $article $commandArticle->getArticle()->getId();
  136.             $larticleRepository $entityManager->getRepository(Article::class);
  137.             $larticleRepository->updateArticleQuantity($commandArticle);
  138.             
  139.            }
  140.        $lcommande->setEtat('Valide');
  141.         $entityManager->persist($lcommande);
  142.         $entityManager->flush();
  143.         $url $this->adminUrlGenerator
  144.             ->setController(CommandeCrudController::class)
  145.             ->setAction(Action::INDEX)
  146.             ->setEntityId($lcommande->getId())
  147.             ->generateUrl();
  148.             $urlCommande $router->generate('command_detail', ['id' => $lcommande->getId()]);
  149.             $user $entityManager->getRepository(User::class)->find($lcommande->getUser());
  150.            
  151.             $notification_message 'Votre Commande a été validée !' $lcommande->getId() . ' ';
  152.             $notificationManager->pushMessage('Votre Commande a été validée !'$notification_message$user$urlCommande);
  153.         return $this->redirect($url);
  154.         
  155.     }
  156.     // public function refuserLCommande(RequestStack $request, EntityManagerInterface $entityManager, AdminContext $context)
  157.     // {
  158.     //     $lcommande = $context->getEntity()->getInstance();
  159.     //     // $lcommande->setMotifs($context->getEntity()->getInstance()->getMotifs());
  160.     //     $lcommande->setEtat('Refuse');
  161.     //     $entityManager->persist($lcommande);
  162.     //     $entityManager->flush();
  163.     //     $url = $this->adminUrlGenerator
  164.     //         ->setController(CommandeCrudController::class)
  165.     //         ->setAction(Action::EDIT)
  166.     //         ->setEntityId($lcommande->getId())
  167.     //         ->generateUrl();
  168.     //     return $this->redirect($url);
  169.     // }
  170.     final public function configureCrud(Crud $crud): Crud
  171.     {
  172.         return $crud
  173.             ->setPageTitle(Crud::PAGE_INDEX'Liste des Commandes')
  174.             ->overrideTemplates([
  175.                 //'crud/new' => 'admin/Commande/Commande_edit.html.twig',
  176.                 'crud/edit' => 'admin/commande/commande_edit.html.twig',
  177.             ]);
  178.     }
  179.     #[Route('/delete/command/article/{id}/{parentId}'name'delete_command_article')]
  180.     public function showByEquipeDetail(CommandArticle $commande$parentIdRequest $requestEntityManagerInterface $entityManager): Response
  181.     {
  182.         $id $commande->getId();
  183.         $url $this->adminUrlGenerator
  184.             ->setController(CommandeCrudController::class)
  185.             ->setAction(Action::EDIT)
  186.             ->setEntityId($parentId)
  187.             ->generateUrl();
  188.         $entityManager->remove($commande);
  189.         $entityManager->flush();
  190.         return $this->redirect($url);
  191.     }
  192.     #[Route('/show/cart'name'show_cart')]
  193.     public function showCart(RequestStack $requestStackEntityManagerInterface $entityManager): Response
  194.     {
  195.         $session $requestStack->getSession();
  196.         $listCommand $session->get('listCommand', []);
  197.         $somme 0;
  198.         $newList = [];
  199.         foreach ($listCommand as $elem) {
  200.             $ca = new CommandArticle();
  201.             $find $entityManager->getRepository(Article::class)->find($elem['id']);
  202.             $ca->setArticle($find);
  203.             $ca->setQuantite($elem['quantity']);
  204.             $somme $somme + ($find->getPrix() * $elem['quantity']);
  205.             $ca->setPrixUnitaire($find->getPrix());
  206.             array_push($newList$ca);
  207.         }
  208.         return $this->render('commande/index.html.twig', ['listCommand' => $newList'somme' => $somme]);
  209.     }
  210.     #[Route('/make/command/delete/{id}'name'make_command_delete')]
  211.     public function deleteCommand($idRequestStack $requestStack): Response
  212.     {
  213.         $session $requestStack->getSession();
  214.         $listCommand $session->get('listCommand', []);
  215.         $exist false;
  216.         $i 0;
  217.         while ($i count($listCommand) && $exist == false) {
  218.             if ($listCommand[$i]['id'] == $id) {
  219.                 $exist true;
  220.                 array_splice($listCommand$i1);
  221.             } else {
  222.                 $i++;
  223.             }
  224.         }
  225.         $session->set('listCommand'$listCommand);
  226.         //return $this->render('commande/index.html.twig',['listCommand' => $listCommand]);
  227.         return $this->redirectToRoute('show_cart');
  228.     }
  229.     #[Route('/make/article/delete/{id}'name'make_article_delete')]
  230.     public function deleteCommand2(CommandArticle $commandEntityManagerInterface $entityManager): JsonResponse
  231.     {
  232.         $entityManager->remove($command);
  233.         $entityManager->flush();
  234.         return new JsonResponse(['data' => $command], Response::HTTP_OK, ['Content-Type''application/json']);
  235.     }
  236.     #[Route('/delete/command/{id}'name'delete_command')]
  237.     public function deleteCommand3(Commande $commandEntityManagerInterface $entityManager): Response
  238.     {
  239.         //dd($command);
  240.         $entityManager->remove($command);
  241.         $entityManager->flush();
  242.         return $this->redirectToRoute('index_article');
  243.     }
  244.     /**
  245.      * @Route("/make/command", name="make_command", methods={"POST"})
  246.      */
  247.     public function add(Request $requestRequestStack $requestStackSerializerInterface $serializerSecurity $security): JsonResponse
  248.     {
  249.         $session $requestStack->getSession();
  250.         $listCommand $session->get('listCommand', []);
  251.         $data json_decode($request->getContent(), true);
  252.         $exist false;
  253.         $i 0;
  254.         while ($i count($listCommand) && $exist == false) {
  255.             if ($listCommand[$i]['id'] == $data['id']) {
  256.                 $exist true;
  257.             } else {
  258.                 $i++;
  259.             }
  260.         }
  261.         if ($exist == true) {
  262.             $listCommand[$i]['quantity'] = $data["quantity"];
  263.         } else {
  264.             array_push($listCommand$data);
  265.         }
  266.         $session->set('listCommand'$listCommand);
  267.         return new JsonResponse(['data' => $listCommand], Response::HTTP_OK, ['Content-Type''application/json']);
  268.     }
  269.      /**
  270.      * @Route("/make/command/after/save/{id}/{quantity}", name="make_command_after_save", methods={"POST"})
  271.      */
  272.     public function addAfterSave(CommandArticle $command$quantityRequest $requestEntityManagerInterface $entityManager): JsonResponse
  273.     {
  274.         $command->setQuantite($quantity);
  275.         $entityManager->persist($command);
  276.         $entityManager->flush();
  277.         return new JsonResponse(['data' => 'done'], Response::HTTP_OK, ['Content-Type''application/json']);
  278.     }
  279.     /**
  280.      * @Route("/refuse/command/{id}/{motifs}", name="refuse_command", methods={"POST"})
  281.      */
  282.     public function refuseCommand(Commande $command$motifsRequest $requestEntityManagerInterface $entityManager): JsonResponse
  283.     {
  284.         $command->setMotifs($motifs);
  285.         $command->setEtat('Refuse');
  286.         $entityManager->persist($command);
  287.         $entityManager->flush();
  288.         return new JsonResponse(['data' => 'done'], Response::HTTP_OK, ['Content-Type''application/json']);
  289.     }
  290.     #[Route('/make/command/confirm'name'make_command_confirm')]
  291.     public function showByArticleDetail(Request $requestEntityManagerInterface $entityManager
  292.     Security $securityRequestStack $requestStack,
  293.     GouvernoratRepository $gouvernoratRepository,
  294.     UniteRegionalRepository $uniteRegionalRepository,
  295.     AdresseRepository $adresseRepository,
  296.     NotificationManager $notificationManager
  297.     ): Response
  298.     {
  299.         // $data = json_decode($request->getContent(), true);
  300.         $session $requestStack->getSession();
  301.         $listCommandArticle $session->get('listCommand', []);
  302.         $edit_demande_url =  $this->adminUrlGenerator
  303.                 ->setController(CommandeCrudController::class)
  304.                 ->setAction(Action::INDEX)
  305.                 ->generateUrl();
  306.         if (count($listCommandArticle) > 0) {
  307.             $commande = new Commande();
  308.             $sommeT 0;
  309.             foreach ($listCommandArticle as $elem) {
  310.                 $somme 0;
  311.                 $commandeArticle = new CommandArticle();
  312.                 $find $entityManager->getRepository(Article::class)->find($elem['id']);
  313.                 $commandeArticle->setArticle($find);
  314.                 $commandeArticle->setQuantite($elem['quantity']);
  315.                 $somme $somme + ($find->getPrix() * $elem['quantity']);
  316.                 $commandeArticle->setPrixUnitaire($find->getPrix());
  317.                 // $entityManager->persist($commandeArticle);
  318.                 $commande->addCommande($commandeArticle);
  319.                 $sommeT $sommeT $somme;
  320.             }
  321.             $commande->setTotalPrice($sommeT);
  322.             $commande->setDate(new \DateTime());
  323.             $commande->setMotifs("");
  324.             $commande->setEmail($request->request->get('email'' '));
  325.             $commande->setAdresse($request->request->get('adresse'' '));
  326.             $commande->setTel($request->request->get('tel'' '));
  327.             $commande->setUser($security->getUser());
  328.             $uniteRegionals $uniteRegionalRepository->findAll();
  329.                 foreach($uniteRegionals as $uniteRegional){
  330.                    $adresse $adresseRepository->findOneBy(
  331.                     [
  332.                         'id' => $uniteRegional->getAdresse(),
  333.                         'gouvernorat' => (int)$request->request->get('gouvernourat'null)
  334.                     ]);
  335.                 }
  336.             $gouv $gouvernoratRepository->findOneBy(['id' => (int)$request->request->get('gouvernourat'null)]);
  337.             $commande->setGouvernorat($gouv);
  338.             if($adresse){
  339.                 $commande->setAdresseUNITE($adresse->getAdresse());
  340.                 $commande->setCODEPOSTALUNITE($adresse->getCodePostale());
  341.             }
  342.          
  343.             $listCommand = [];
  344.             $session->set('listCommand'$listCommand);
  345.             $this->addFlash('success''votre commande a bien été envoyée!');
  346.             $entityManager->persist($commande);
  347.             $entityManager->flush();
  348.             $notification_message 'Nouvelle Commande !   ';
  349.             $admins $this->em->getRepository(User::class)->findByRole('ROLE_ADMIN');
  350.             foreach($admins as $admin){
  351.                 $notificationManager->pushMessage('Nouvelle Commande !'$notification_message$admin$edit_demande_url);
  352.             }
  353.         }
  354.         //return $this->render('commande/index.html.twig',['listCommand' => $listCommand, 'somme' => $sommeT]);
  355.         //return $this->redirectToRoute('show_article_detail', ['id' => $article->getId()]);
  356.         return $this->redirectToRoute('show_cart');
  357.     }
  358.     #[Route('/command/detail/{id}'name'command_detail')]
  359.     public function detailCommand(Commande $command,
  360.      EntityManagerInterface $entityManager
  361.     UniteRegionalRepository $uniteRegionalRepository,
  362.     AdresseRepository $adresseRepository
  363.     ): Response
  364.     {
  365.         $somme 0;
  366.         foreach ($command->getCommandes() as $elem) {
  367.             $somme $somme + ($elem->getPrixUnitaire() * $elem->getQuantite());
  368.         }
  369.         $command->setTotalPrice($somme);
  370.         $entityManager->persist($command);
  371.         $entityManager->flush();
  372.         $gouv $command->getGouvernorat()->getId();
  373.         $unite_regional  $uniteRegionalRepository->findByGouvernorat($gouv);
  374.        
  375.        
  376.         if (!empty($unite_regional)) {
  377.             $adresse $adresseRepository->findById($unite_regional[0]->getAdresse()->getId());
  378.             $adresse $adresse[0]; // Access the first element if it exists
  379.             $unite_regional $unite_regional[0];
  380.             $adresseEtat true;
  381.         } else {
  382.             // Handle the case when the address is not found
  383.             // You can set $adresse to a default value or show an error message.
  384.             // For example, you can set $adresse to an empty array:
  385.             $adresse = [];
  386.             $unite_regional=[];
  387.             $adresseEtat false;
  388.         }
  389.                 return $this->render('commande/commande_detail.html.twig', [
  390.          'command' => $command,
  391.          'unite_regional' =>$unite_regional
  392.          'adresseEtat' =>$adresseEtat
  393.          'adresse' => $adresse]);
  394.     }
  395.     #[Route('/command/history/'name'command_history')]
  396.     public function historyCommand(Security $securityRequest $requestEntityManagerInterface $entityManagerPaginatorInterface $paginator): Response
  397.     {
  398.         $donnees $entityManager->getRepository(Commande::class)->findBy(["user" => $security->getUser()], ['id' => 'DESC']);
  399.         $commands $paginator->paginate(
  400.             $donnees,
  401.             $request->query->getInt('page'1),
  402.             10
  403.         );
  404.         return $this->render('commande/commande_history.html.twig', ['commands' => $commands]);
  405.     }
  406.     public function excelExport(EntityManagerInterface $entityManagerExportExl $exportExlService) {
  407.         $data $entityManager->getRepository(Commande::class)->findAll();
  408.         $file_full_name =  $exportExlService->xlsExportModel($data);
  409.         return $this->file($file_full_name);
  410.     }
  411.     public function configureFilters(Filters $filters): Filters
  412.     {
  413.         return $filters
  414.         ->add(ArrayFilter::new('etat''Etat')->setChoices(array_combine(Commande::STATUS_ARRAYCommande::STATUS_ARRAY)));
  415.     }
  416.     #[Route('/notif/countCommandArticleByUser'name'count_command_article_by_user')]
  417. public function countCommandArticleByUser(RequestStack $requestStackEntityManagerInterface $entityManager): JsonResponse
  418. {
  419.     $session $requestStack->getSession();
  420.         $listCommand $session->get('listCommand', []);
  421.         $count 0;
  422.         $newList = [];
  423.         foreach ($listCommand as $elem) {
  424.             $ca = new CommandArticle();
  425.             $find $entityManager->getRepository(Article::class)->find($elem['id']);
  426.             $ca->setArticle($find);
  427.             $ca->setQuantite($elem['quantity']);
  428.             $count $count 1;
  429.          
  430.         }
  431.     return $this->json(['count' => $count]);
  432. }
  433. }