src/Controller/Admin/CommandeCrudController.php line 230

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 AbstractBaseCrudController
  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'methods: ['POST'])]
  180.     public function showByEquipeDetail(CommandArticle $commande$parentIdRequest $requestEntityManagerInterface $entityManager): Response
  181.     {
  182.         $this->validateRequestCsrfToken($request'delete');
  183.         $id $commande->getId();
  184.         $url $this->adminUrlGenerator
  185.             ->setController(CommandeCrudController::class)
  186.             ->setAction(Action::EDIT)
  187.             ->setEntityId($parentId)
  188.             ->generateUrl();
  189.         $entityManager->remove($commande);
  190.         $entityManager->flush();
  191.         return $this->redirect($url);
  192.     }
  193.     #[Route('/show/cart'name'show_cart')]
  194.     public function showCart(RequestStack $requestStackEntityManagerInterface $entityManager): Response
  195.     {
  196.         $session $requestStack->getSession();
  197.         $listCommand $session->get('listCommand', []);
  198.         $somme 0;
  199.         $newList = [];
  200.         foreach ($listCommand as $elem) {
  201.             $ca = new CommandArticle();
  202.             $find $entityManager->getRepository(Article::class)->find($elem['id']);
  203.             $ca->setArticle($find);
  204.             $ca->setQuantite($elem['quantity']);
  205.             $somme $somme + ($find->getPrix() * $elem['quantity']);
  206.             $ca->setPrixUnitaire($find->getPrix());
  207.             array_push($newList$ca);
  208.         }
  209.         return $this->render('commande/index.html.twig', ['listCommand' => $newList'somme' => $somme]);
  210.     }
  211.     #[Route('/make/command/delete/{id}'name'make_command_delete'methods: ['POST'])]
  212.     public function deleteCommand(Request $request$idRequestStack $requestStack): Response
  213.     {
  214.         $this->validateRequestCsrfToken($request'ajax');
  215.         $session $requestStack->getSession();
  216.         $listCommand $session->get('listCommand', []);
  217.         $exist false;
  218.         $i 0;
  219.         while ($i count($listCommand) && $exist == false) {
  220.             if ($listCommand[$i]['id'] == $id) {
  221.                 $exist true;
  222.                 array_splice($listCommand$i1);
  223.             } else {
  224.                 $i++;
  225.             }
  226.         }
  227.         $session->set('listCommand'$listCommand);
  228.         //return $this->render('commande/index.html.twig',['listCommand' => $listCommand]);
  229.         return $this->redirectToRoute('show_cart');
  230.     }
  231.     #[Route('/make/article/delete/{id}'name'make_article_delete'methods: ['POST'])]
  232.     public function deleteCommand2(Request $requestCommandArticle $commandEntityManagerInterface $entityManager): JsonResponse
  233.     {
  234.         $this->validateRequestCsrfToken($request'ajax');
  235.         $entityManager->remove($command);
  236.         $entityManager->flush();
  237.         return new JsonResponse(['data' => $command], Response::HTTP_OK, ['Content-Type''application/json']);
  238.     }
  239.     #[Route('/delete/command/{id}'name'delete_command'methods: ['POST'])]
  240.     public function deleteCommand3(Request $requestCommande $commandEntityManagerInterface $entityManager): Response
  241.     {
  242.         $this->validateRequestCsrfToken($request'delete');
  243.         $entityManager->remove($command);
  244.         $entityManager->flush();
  245.         return $this->redirectToRoute('index_article');
  246.     }
  247.     /**
  248.      * @Route("/make/command", name="make_command", methods={"POST"})
  249.      */
  250.     public function add(Request $requestRequestStack $requestStackSerializerInterface $serializerSecurity $security): JsonResponse
  251.     {
  252.         $this->validateRequestCsrfToken($request'ajax');
  253.         $session $requestStack->getSession();
  254.         $listCommand $session->get('listCommand', []);
  255.         $data json_decode($request->getContent(), true);
  256.         $exist false;
  257.         $i 0;
  258.         while ($i count($listCommand) && $exist == false) {
  259.             if ($listCommand[$i]['id'] == $data['id']) {
  260.                 $exist true;
  261.             } else {
  262.                 $i++;
  263.             }
  264.         }
  265.         if ($exist == true) {
  266.             $listCommand[$i]['quantity'] = $data["quantity"];
  267.         } else {
  268.             array_push($listCommand$data);
  269.         }
  270.         $session->set('listCommand'$listCommand);
  271.         return new JsonResponse(['data' => $listCommand], Response::HTTP_OK, ['Content-Type''application/json']);
  272.     }
  273.      /**
  274.      * @Route("/make/command/after/save/{id}/{quantity}", name="make_command_after_save", methods={"POST"})
  275.      */
  276.     public function addAfterSave(CommandArticle $command$quantityRequest $requestEntityManagerInterface $entityManager): JsonResponse
  277.     {
  278.         $this->validateRequestCsrfToken($request'ajax');
  279.         $command->setQuantite($quantity);
  280.         $entityManager->persist($command);
  281.         $entityManager->flush();
  282.         return new JsonResponse(['data' => 'done'], Response::HTTP_OK, ['Content-Type''application/json']);
  283.     }
  284.     /**
  285.      * @Route("/refuse/command/{id}/{motifs}", name="refuse_command", methods={"POST"})
  286.      */
  287.     public function refuseCommand(Commande $command$motifsRequest $requestEntityManagerInterface $entityManager): JsonResponse
  288.     {
  289.         $this->validateRequestCsrfToken($request'ajax');
  290.         $command->setMotifs($motifs);
  291.         $command->setEtat('Refuse');
  292.         $entityManager->persist($command);
  293.         $entityManager->flush();
  294.         return new JsonResponse(['data' => 'done'], Response::HTTP_OK, ['Content-Type''application/json']);
  295.     }
  296.     #[Route('/make/command/confirm'name'make_command_confirm')]
  297.     public function showByArticleDetail(Request $requestEntityManagerInterface $entityManager
  298.     Security $securityRequestStack $requestStack,
  299.     GouvernoratRepository $gouvernoratRepository,
  300.     UniteRegionalRepository $uniteRegionalRepository,
  301.     AdresseRepository $adresseRepository,
  302.     NotificationManager $notificationManager
  303.     ): Response
  304.     {
  305.         if ($request->isMethod('POST')) {
  306.             $this->validateRequestCsrfToken($request'submit');
  307.         }
  308.         // $data = json_decode($request->getContent(), true);
  309.         $session $requestStack->getSession();
  310.         $listCommandArticle $session->get('listCommand', []);
  311.         $edit_demande_url =  $this->adminUrlGenerator
  312.                 ->setController(CommandeCrudController::class)
  313.                 ->setAction(Action::INDEX)
  314.                 ->generateUrl();
  315.         if (count($listCommandArticle) > 0) {
  316.             $commande = new Commande();
  317.             $sommeT 0;
  318.             foreach ($listCommandArticle as $elem) {
  319.                 $somme 0;
  320.                 $commandeArticle = new CommandArticle();
  321.                 $find $entityManager->getRepository(Article::class)->find($elem['id']);
  322.                 $commandeArticle->setArticle($find);
  323.                 $commandeArticle->setQuantite($elem['quantity']);
  324.                 $somme $somme + ($find->getPrix() * $elem['quantity']);
  325.                 $commandeArticle->setPrixUnitaire($find->getPrix());
  326.                 // $entityManager->persist($commandeArticle);
  327.                 $commande->addCommande($commandeArticle);
  328.                 $sommeT $sommeT $somme;
  329.             }
  330.             $commande->setTotalPrice($sommeT);
  331.             $commande->setDate(new \DateTime());
  332.             $commande->setMotifs("");
  333.             $commande->setEmail($request->request->get('email'' '));
  334.             $commande->setAdresse($request->request->get('adresse'' '));
  335.             $commande->setTel($request->request->get('tel'' '));
  336.             $commande->setUser($security->getUser());
  337.             $uniteRegionals $uniteRegionalRepository->findAll();
  338.                 foreach($uniteRegionals as $uniteRegional){
  339.                    $adresse $adresseRepository->findOneBy(
  340.                     [
  341.                         'id' => $uniteRegional->getAdresse(),
  342.                         'gouvernorat' => (int)$request->request->get('gouvernourat'null)
  343.                     ]);
  344.                 }
  345.             $gouv $gouvernoratRepository->findOneBy(['id' => (int)$request->request->get('gouvernourat'null)]);
  346.             $commande->setGouvernorat($gouv);
  347.             if($adresse){
  348.                 $commande->setAdresseUNITE($adresse->getAdresse());
  349.                 $commande->setCODEPOSTALUNITE($adresse->getCodePostale());
  350.             }
  351.          
  352.             $listCommand = [];
  353.             $session->set('listCommand'$listCommand);
  354.             $this->addFlash('success'$this->trans('flash.order_sent'));
  355.             $entityManager->persist($commande);
  356.             $entityManager->flush();
  357.             $notification_message 'Nouvelle Commande !   ';
  358.             $admins $this->em->getRepository(User::class)->findByRole('ROLE_ADMIN');
  359.             foreach($admins as $admin){
  360.                 $notificationManager->pushMessage('Nouvelle Commande !'$notification_message$admin$edit_demande_url);
  361.             }
  362.         }
  363.         //return $this->render('commande/index.html.twig',['listCommand' => $listCommand, 'somme' => $sommeT]);
  364.         //return $this->redirectToRoute('show_article_detail', ['id' => $article->getId()]);
  365.         return $this->redirectToRoute('show_cart');
  366.     }
  367.     #[Route('/command/detail/{id}'name'command_detail')]
  368.     public function detailCommand(Commande $command,
  369.      EntityManagerInterface $entityManager
  370.     UniteRegionalRepository $uniteRegionalRepository,
  371.     AdresseRepository $adresseRepository
  372.     ): Response
  373.     {
  374.         $somme 0;
  375.         foreach ($command->getCommandes() as $elem) {
  376.             $somme $somme + ($elem->getPrixUnitaire() * $elem->getQuantite());
  377.         }
  378.         $command->setTotalPrice($somme);
  379.         $entityManager->persist($command);
  380.         $entityManager->flush();
  381.         $gouv $command->getGouvernorat()->getId();
  382.         $unite_regional  $uniteRegionalRepository->findByGouvernorat($gouv);
  383.        
  384.        
  385.         if (!empty($unite_regional)) {
  386.             $adresse $adresseRepository->findById($unite_regional[0]->getAdresse()->getId());
  387.             $adresse $adresse[0]; // Access the first element if it exists
  388.             $unite_regional $unite_regional[0];
  389.             $adresseEtat true;
  390.         } else {
  391.             // Handle the case when the address is not found
  392.             // You can set $adresse to a default value or show an error message.
  393.             // For example, you can set $adresse to an empty array:
  394.             $adresse = [];
  395.             $unite_regional=[];
  396.             $adresseEtat false;
  397.         }
  398.                 return $this->render('commande/commande_detail.html.twig', [
  399.          'command' => $command,
  400.          'unite_regional' =>$unite_regional
  401.          'adresseEtat' =>$adresseEtat
  402.          'adresse' => $adresse]);
  403.     }
  404.     #[Route('/command/history/'name'command_history')]
  405.     public function historyCommand(Security $securityRequest $requestEntityManagerInterface $entityManagerPaginatorInterface $paginator): Response
  406.     {
  407.         $donnees $entityManager->getRepository(Commande::class)->findBy(["user" => $security->getUser()], ['id' => 'DESC']);
  408.         $commands $paginator->paginate(
  409.             $donnees,
  410.             $request->query->getInt('page'1),
  411.             10
  412.         );
  413.         return $this->render('commande/commande_history.html.twig', ['commands' => $commands]);
  414.     }
  415.     public function excelExport(EntityManagerInterface $entityManagerExportExl $exportExlService) {
  416.         $data $entityManager->getRepository(Commande::class)->findAll();
  417.         $file_full_name =  $exportExlService->xlsExportModel($data);
  418.         return $this->file($file_full_name);
  419.     }
  420.     public function configureFilters(Filters $filters): Filters
  421.     {
  422.         return $filters
  423.         ->add(ArrayFilter::new('etat''Etat')->setChoices(array_combine(Commande::STATUS_ARRAYCommande::STATUS_ARRAY)));
  424.     }
  425.     #[Route('/notif/countCommandArticleByUser'name'count_command_article_by_user')]
  426. public function countCommandArticleByUser(RequestStack $requestStackEntityManagerInterface $entityManager): JsonResponse
  427. {
  428.     $session $requestStack->getSession();
  429.         $listCommand $session->get('listCommand', []);
  430.         $count 0;
  431.         $newList = [];
  432.         foreach ($listCommand as $elem) {
  433.             $ca = new CommandArticle();
  434.             $find $entityManager->getRepository(Article::class)->find($elem['id']);
  435.             $ca->setArticle($find);
  436.             $ca->setQuantite($elem['quantity']);
  437.             $count $count 1;
  438.          
  439.         }
  440.     return $this->json(['count' => $count]);
  441. }
  442. }