src/Controller/WorkflowController.php line 79

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Historique;
  4. use App\Entity\Workflow;
  5. use App\Entity\Mission;
  6. use App\Entity\User;
  7. use App\Enum\Manager;
  8. use App\Repository\JobRepository;
  9. use App\Repository\MissionRepository;
  10. use App\Repository\CampaignRepository;
  11. use App\Repository\UserRepository;
  12. use App\Entity\WorkflowAction;
  13. use App\Enum\Role;
  14. use App\Enum\Trigger;
  15. use App\Enum\Operation;
  16. use App\Entity\WorkflowStep;
  17. use App\Event\Workflow\Step\WorkflowStepEditedEvent;
  18. use Symfony\Component\HttpFoundation\JsonResponse;
  19. use App\Event\ClientUpdatedEvent;
  20. use App\Form\WorkflowActionType;
  21. use App\Form\WorkflowStepType;
  22. use App\Form\WorkflowType;
  23. use App\Repository\WorkflowActionRepository;
  24. use App\Repository\WorkflowRepository;
  25. use App\Repository\WorkflowStepRepository;
  26. use Doctrine\ORM\EntityManagerInterface;
  27. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  28. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  29. use Symfony\Component\HttpFoundation\Exception\BadRequestException;
  30. use Symfony\Component\HttpFoundation\RedirectResponse;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use Symfony\Component\HttpFoundation\Response;
  33. use Symfony\Component\Routing\Annotation\Route;
  34. use App\Entity\EmailTemplate;
  35. use App\Form\EmailTemplateType;
  36. use App\Form\ExteralUserType;
  37. use App\Service\DynamicHostService;
  38. use App\Service\WorkflowService;
  39. use Symfony\Component\Security\Core\Security;
  40. #[Route('/admin/workflows')]
  41. class WorkflowController extends AbstractController
  42. {
  43.     
  44.     private $agencyForUser null
  45.     
  46.     public function __construct(private WorkflowService $workflowService,DynamicHostService $dynamicHostService,Security $security)
  47.     {
  48.         
  49.         $company $dynamicHostService->getCompany();
  50.         $curentUser $security?->getUser();
  51.         if (!is_null($curentUser) and !is_null($curentUser?->getRoles()) and in_array('ROLE_MANAGER'$curentUser?->getRoles())) {
  52.             $company $curentUser?->getCompany();
  53.         }
  54.         $this->agencyForUser $company
  55.         
  56.     }
  57.     
  58.     #[Route('/checkform'name'check-form'methods: ['GET'])]
  59.     public function checkform(Request $request): JsonResponse
  60.     {   
  61.         $workflowName =   $request->query->get('name');
  62.         $productId $request->query->get('product-id');
  63.         $companyId $request->query->get('company-id');
  64.         $worflowId $request->query->get('worflow-id');
  65.         
  66.         $isNameExist $this->workflowService->alreadyHaveWorkflowName($workflowName,$worflowId);
  67.         $isNameProductWorflowAnCompanyExist $this->workflowService->alreadyHaveProductAndCompany($productId,$companyId,$worflowId);
  68.         return new JsonResponse([
  69.             'isNameWorkflowExist'=> $isNameExist,
  70.             'isNameProductAndCompanyExist'=> $isNameProductWorflowAnCompanyExist,
  71.         ]);
  72.     }
  73.     #[Route('/checkstep/{id}'name'check-step'methods: ['GET'])]
  74.     public function checkStep(Workflow $workflow): JsonResponse
  75.     {   
  76.         $steps $workflow->getSteps();
  77.         $stepsValidation = [];
  78.         $numberSteps sizeof($steps);
  79.       
  80.         foreach ($steps as $keyStep => $step) {
  81.         
  82.                     $actions $step->getActions();
  83.                     $actionValidation 0
  84.                     $actionValidationWithStp=0;
  85.                     $nbrValidatorToValidateStep=0;
  86.                     
  87.                     $closeAction 0;
  88.                     $noEmailTemplate = [];
  89.                     $noJobStepDescription = !$this->isHaveJobStepDescription($step); 
  90.                     $noJobsInStepForSubcontractor= !$this->isHaveJobsInStepForSubcontractor($step);;
  91.                     $haveValidatorStepError false;
  92.                     $validatorStepError=[];
  93.                     foreach ($actions as $key => $action) {
  94.                          $triggers $action->getTriggers();
  95.                          $validatorActions $this->haveValidatorAction($step$action$key);
  96.                       
  97.                         $validatorStepError=$validatorActions;
  98.                         
  99.                         if(sizeof($validatorStepError) == 0){
  100.                             $nbrValidatorToValidateStep ++;
  101.                          }
  102.                          foreach ($triggers as $key => $trigger) {
  103.     
  104.                             if($trigger->getTriggerType()== Trigger::VALIDATION){
  105.                                 $actionValidation++;
  106.                             }
  107.                             if($trigger->getTriggerType()== Trigger::VALIDATION && $trigger->getOperation()==Operation::NEXT_STEP ){
  108.                                 $actionValidationWithStp++;
  109.                             }
  110.                             if($trigger->getTriggerType()== Trigger::CLOSED_STEP){
  111.                                     $closeAction ++;
  112.                             }
  113.                             if((in_array($trigger->getTriggerType(),[Trigger::ENTER_STEP,Trigger::EXIT_STEP]) || $trigger->getOperation()==Operation::EMAIL) && $trigger->getEmailTemplate() == null){
  114.                                     $noEmailTemplate = [...$noEmailTemplate$action->getName()];
  115.                         }
  116.                          }
  117.                     }
  118.     
  119.                     $stepsValidation=[...$stepsValidation,[
  120.                                             'name'=> $step->getName(),
  121.                                             'responsable'=> $step->getManager(),
  122.                                             'job'=>$step->getJob()?->getName(),
  123.                                             'subcontractor_description'=>$step->getSupplierDescription(),
  124.                                             'client_description'=>$step->getCustomerDescription(),
  125.                                             'isLastStep'=> false,
  126.                                             'position'=>$step->getPosition(),
  127.                                             'nbrStep'=>$numberSteps,
  128.                                             'noDescription'=> $noJobStepDescription,
  129.                                             'noJobs'=>$noJobsInStepForSubcontractor,
  130.                                             'validatorStepError'=> $nbrValidatorToValidateStep ? [] : $validatorStepError,
  131.                                             'actions'=>[
  132.                                                 'haveValidationWithAction'=> $actionValidationWithStp true false,
  133.                                                 'haveValidation'=> $actionValidationWithStp == && $actionValidation true false,
  134.                                                 'haveClosedAction'=> $closeAction>true false,
  135.                                                 'missingEmailTemplate'=>$noEmailTemplate 
  136.                                             ]
  137.                     ]];
  138.         }
  139.         $workflowValidation['nameWorflow']= $workflow->getName();
  140.         $workflowValidation['nameAlredyExist']= false;
  141.         $workflowValidation['productAndClientExiste']= false;
  142.         $workflowValidation['steps']= $stepsValidation;
  143.         return new JsonResponse($workflowValidation);
  144.     }
  145.     private function isHaveJobStepDescription(WorkflowStep $step){
  146.         $manager $step->getManager(); 
  147.         $customerDescription $step->getCustomerDescription();
  148.         if($manager == Manager::JOB){
  149.            return  !empty($step->getCustomerDescription()) && !is_null($step->getCustomerDescription()) && isset($customerDescription);
  150.         }
  151.         return  !empty($step->getSupplierDescription() ) && !is_null($step->getSupplierDescription());
  152.     }
  153.     
  154.     private function isHaveJobsInStepForSubcontractor(WorkflowStep $step){
  155.         $manager $step->getManager(); 
  156.         if($manager == Manager::JOB){
  157.             return !is_null($step->getJob()) ; 
  158.         }
  159.         return true;
  160.     }
  161.     private function haveValidatorAction(WorkflowStep $step,WorkflowAction $action$indexAction){
  162.         
  163.         switch ($step->getManager() ) {
  164.             case Manager::CLIENT:
  165.                 if($action->getRecipient() != Role::ROLE_CLIENT){
  166.                      return [
  167.                                 'message'=> "client",
  168.                                 'step_position'=>$step->getPosition(),
  169.                                 'action_index'=> $indexAction,
  170.                                 'job_subcontractor'=>''
  171.                      ];
  172.                 }
  173.             break;
  174.             case Manager::JOB:
  175.                 if(!($action->getRecipient() == Role::ROLE_SUBCONTRACTOR && $action->getJob() == $step->getJob())){
  176.                     return [
  177.                             'message'=> "sous-traitant",
  178.                             'step_position'=>$step->getPosition(),
  179.                             'job_subcontractor'=>$step->getJob()? $step->getJob()->getName() : '-',
  180.                             'action_index'=> $indexAction
  181.                     ];
  182.                }
  183.             break;
  184.             case Manager::CLIENT_EXTERNAL:
  185.                 if(!($action->getRecipient() == Role::ROLE_USER_SPECIFIC && sizeof($action->getUser())!=0  && $this->isUserInStepIsInRecipientAtAction($step->getUserResponsable(),$action->getUser()) == true)){
  186.                     
  187.                     $userResponsables = ($step->getUserResponsable())->toArray();
  188.                     $userResponsables array_reduce($userResponsables, function($carry,$item){ return "$carry {$item->getFullName()},";});
  189.                     return [
  190.                             'message'=> "utilisateur specifique",
  191.                             'responsable'=> $userResponsables,
  192.                             'step_position'=>$step->getPosition(),
  193.                             'action_index'=> $indexAction,
  194.                             'job_subcontractor'=>''
  195.                     ];
  196.                }
  197.                 
  198.             break;
  199.         }
  200.         return []; 
  201.     }
  202.     private function isUserInStepIsInRecipientAtAction($usersInStep,$usersInAction){
  203.       
  204.          foreach ($usersInStep as $key => $user) {
  205.               foreach ($usersInAction as $key => $usr) {
  206.                         if($user->getId()== $usr->getId()){
  207.                              return true
  208.                         }
  209.               }
  210.          }
  211.          return false;
  212.     }
  213.     /**
  214.      * Displays the index view of the templates
  215.      *
  216.      * @param WorkflowRepository $workflowRepository
  217.      *
  218.      * @return Response template /workflow/index.html.twig
  219.      */
  220.     #[Route(''name'workflow_index')]
  221.     public function index(WorkflowRepository $workflowRepository,DynamicHostService $dynamicHostService): Response
  222.     {
  223.         $isAgency false;
  224.         // $workflow =  $workflowRepository->getAll();
  225.         $company $dynamicHostService->getCompany();
  226.         $companyOwner $dynamicHostService->getCompany();
  227.         $workflow =  $workflowRepository->getWorkflowAdmin($company$companyOwner);
  228.         if ( in_array('ROLE_ADMIN_AGENCY',$this->getUser()->getRoles()) or in_array('ROLE_MANAGER',$this->getUser()->getRoles())) {
  229.             
  230.             $isAgency true;
  231.         }
  232.         return $this->render('workflow/index.html.twig', [
  233.             'workflows' => $workflow,
  234.             'isAgency' => $isAgency,
  235.         ]);
  236.     }
  237.     /**
  238.      * Displays the handle view for the workflows
  239.      *
  240.      * @param Workflow|null $workflow if defined, the workflow to edit
  241.      * @param Request $request
  242.      * @param EntityManagerInterface $entityManager
  243.      * @param WorkflowActionRepository $workflowActionRepository
  244.      * @param WorkflowStepRepository $workflowStepRepository
  245.      *
  246.      * @return Response template /workflow/handle.html.twig
  247.      */
  248.     #[Route('/ajouter'name'workflow_new')]
  249.     #[Route('/{id}'name'workflow_edit')]
  250.     public function handle(Workflow $workflow null,DynamicHostService $dynamicHostServiceRequest $request,JobRepository $jobRepositoryEntityManagerInterface $entityManagerWorkflowActionRepository $workflowActionRepositoryWorkflowStepRepository $workflowStepRepositoryEventDispatcherInterface $dispatcher,MissionRepository $missionRepositoryWorkflowRepository $workflowRepository,UserRepository $userRepository): Response
  251.     {
  252.         $workflowExist true;
  253.         if (null === $workflow) {
  254.             $workflowExist false;
  255.             $companyOwner $dynamicHostService->getCompany();
  256.             $workflow = (new Workflow())
  257.                 ->setTemplate(true)
  258.                 ->setOwner($companyOwner)
  259.                 ;
  260.         }
  261.         $allUsers $userRepository->findAll();
  262.         //campaing for workflow
  263.         $mission $missionRepository->findByWorkflow($workflow);
  264.         /*
  265.          * Handling the workflow informations form
  266.          */
  267.         $company null;
  268.         $isadminAgency false;
  269.         $company $this->getUser()->getCompany() ;
  270.         if (in_array("ROLE_ADMIN_AGENCY"$this->getUser()->getRoles()) ) {
  271.            
  272.             $isadminAgency true;
  273.             $company $this->getUser()->getCompany();
  274.         }
  275.         $form $this->createForm(WorkflowType::class, $workflow,['company'=>$company,'user'=>$allUsers,'isadminAgency'=>$isadminAgency]);
  276.         $form->handleRequest($request);
  277.         if ($form->isSubmitted() && $form->isValid()) {
  278.             if ($workflow->getTemplate() === false && null !== $workflow->getMission()) {
  279.                 $historique = (new Historique())
  280.                     ->setUser($this->getUser())
  281.                     ->setMission($workflow->getMission())
  282.                     ->setMessage($this->getUser().' a modifié le workflow');
  283.                 $entityManager->persist($historique);
  284.             }
  285.         //    if(!in_array('ROLE_ADMIN', $this->getUser()->getRoles()) && $company!=null && $workflow->getCompany()==null){
  286.         //        $workflow->setCompany($company);
  287.         //    }
  288.             $entityManager->persist($workflow);
  289.             $entityManager->flush();
  290.             
  291.             //link workflow into all mission if haven't workflow
  292.             if (!$workflowExist || $form->getData()->getCompany()) {
  293.                 $product $form->getData()->getProduct();
  294.                 $company $form->getData()->getCompany();
  295.                 
  296.   
  297.                 $sameWorkflow $workflowRepository->findWorkFlowByCompanyAndProduct($company$product);
  298.                 if (sizeof($sameWorkflow) >= 2) {
  299.                     $this->addFlash(
  300.                         type'error',
  301.                         message'Un workflow a déjà été créé pour ce service. Nous vous invitons à vérifier le processus existant ou en créer un nouveau pour un client en particulier si vous souhaitez activer un processus spécifique',
  302.                     );
  303.                     return $this->redirectToRoute('workflow_edit', ['id' => $workflow->getId()]);
  304.                 }
  305.                 $missions $missionRepository->findMissionWorkFlowNullByCompany($company,$product);
  306.                 $fisrtInsert true;
  307.                 foreach ($missions as $mission) {
  308.                     if ($fisrtInsert) {
  309.                         $mission->setWorkflow($workflow);
  310.                         
  311.                     }else{
  312.                         $newWorkflow = clone $workflow;
  313.                         $newWorkflow->setTemplate(false);
  314.                         $mission->setWorkflow($newWorkflow);
  315.                         $entityManager->persist($newWorkflow);
  316.                     }
  317.                     $fisrtInsert false;
  318.                     $entityManager->persist($mission);
  319.                     $entityManager->flush();
  320.                     
  321.                 }
  322.                 //end
  323.             }
  324.             
  325.             $this->addFlash(
  326.                 type'success',
  327.                 message'Le workflow a bien été enregistré',
  328.             );
  329.             return $this->redirectToRoute('workflow_edit', ['id' => $workflow->getId()]);
  330.         } elseif ($form->isSubmitted()) {
  331.             $this->addFlash(
  332.                 type'danger',
  333.                 message'Merci de corriger les erreurs',
  334.             );
  335.         }
  336.         /*
  337.          * Handling the new step form
  338.          *
  339.          * If the form is submitted when editing a step, we load it and throw a bad request exception if the step is not found
  340.          * If not, a new step is created
  341.          */
  342.         if (null !== $request->request->get('workflow_step') && isset($request->request->get('workflow_step')['stepId']) && !empty($request->request->get('workflow_step')['stepId'])) {
  343.             $step $workflowStepRepository->find($request->request->get('workflow_step')['stepId']);
  344.             $newSteps false;
  345.             if (null === $step) {
  346.                 throw new BadRequestException();
  347.             }
  348.         } else {
  349.             $step = new WorkflowStep();
  350.             $newSteps true;
  351.         }
  352.         $step->setWorkflow($workflow);
  353.         $addStepForm $this->createForm(WorkflowStepType::class, $step);
  354.         $addStepForm->handleRequest($request);
  355.         if ($addStepForm->isSubmitted() && $addStepForm->isValid()) {
  356.             //if new steps add position
  357.             if( $newSteps ){
  358.                 $step->setPosition(count($workflow->getSteps()));
  359.             }
  360.             // $userResponsableList = $step->getUserResponsables();
  361.             // foreach ($userResponsableList as $key => $userResponsable) {
  362.             //         $step->removeUserResponsable($userResponsable)
  363.             // }
  364.             // $newUserResponsable = 
  365.             // dump($request->request->get('workflow_step')['userResponsable']);
  366.             // dd($addStepForm);
  367.             $entityManager->persist($step);
  368.             $entityManager->flush();
  369.             $event = new WorkflowStepEditedEvent($step);
  370.             $dispatcher->dispatch($eventWorkflowStepEditedEvent::NAME);
  371.             $this->addFlash(
  372.                 type'success',
  373.                 message'L\'étape a bien été enregistrée',
  374.             );
  375.             return $this->redirectToRoute('workflow_edit', ['id' => $workflow->getId()]);
  376.         } elseif ($addStepForm->isSubmitted()) {
  377.             $this->addFlash(
  378.                 type'danger',
  379.                 message'Merci de corriger les erreurs',
  380.             );
  381.         }
  382.         /*
  383.          * Handling the new action form
  384.          *
  385.          * If the form is submitted when editing an action, we load it and throw a bad request exception if the action is not found
  386.          * If not, a new action is created
  387.          */
  388.         if (null !== $request->request->get('workflow_action') && isset($request->request->get('workflow_action')['actionId']) && !empty($request->request->get('workflow_action')['actionId'])) {
  389.             $action $workflowActionRepository->find($request->request->get('workflow_action')['actionId']);
  390.             if (null === $action) {
  391.                 throw new BadRequestException();
  392.             }
  393.         } else {
  394.             $action = new WorkflowAction();
  395.         }
  396.         $participantsListUserId = [];
  397.         if (!is_null($workflow->getCompany())) {
  398.             foreach ($allUsers as $user) {
  399.                 if (!is_null($user->getCompany()) && $user->getCompany()->getId() != $workflow->getCompany()->getId()) {
  400.                     $participantsListUserId[] = $user;
  401.                 }
  402.             }
  403.         }else{
  404.             $participantsListUserId $allUsers;
  405.         }
  406.         $companyAgency $dynamicHostService->getCompany();
  407.         $addActionForm $this->createForm(WorkflowActionType::class, $action, ['product' => $workflow->getProduct(),'participantsListUserId'=>$participantsListUserId]);
  408.         $addActionForm->handleRequest($request);
  409.         
  410.         if ($addActionForm->isSubmitted() && $addActionForm->isValid()) {
  411.             $entityManager->persist($action);
  412.             $entityManager->flush();
  413.             $this->addFlash(
  414.                 type'success',
  415.                 message'Le workflow a bien été enregistré',
  416.             );
  417.             return $this->redirectToRoute('workflow_edit', ['id' => $workflow->getId()]);
  418.         } elseif ($addStepForm->isSubmitted()) {
  419.             $this->addFlash(
  420.                 type'danger',
  421.                 message'Merci de corriger les erreurs',
  422.             );
  423.         }
  424.         
  425.         $emailTemplate = new EmailTemplate();
  426.         $jobs $jobRepository->findByAgency($this->agencyForUser);
  427.         $formEmailTemplate $this->createForm(EmailTemplateType::class, $emailTemplate);
  428.         $externalUser $this->createForm(ExteralUserType::class);
  429.         return $this->renderForm('workflow/handle.html.twig', [
  430.             'workflow' => $workflow,
  431.             'form' => $form,
  432.             'addStepForm' => $addStepForm,
  433.             'addActionForm' => $addActionForm,
  434.             'formEmailTemplate' => $formEmailTemplate,
  435.             'userInAction' => $action->getUser(),
  436.             'jobsProduct'=> $jobs
  437.         ]);
  438.     }
  439.     /**
  440.      * @param Request $request
  441.      * @param UserRepository $userRepository
  442.      * @param EntityManagerInterface $entityManagerInterface
  443.      * @param WorkflowActionRepository $workflowActionRepository
  444.      */
  445.     #[Route('/add/external'name'workflow_add_user_external')]
  446.     public function addUserExternal(Request $request,UserRepository $userRepository,EntityManagerInterface $entityManagerEventDispatcherInterface $dispatcher,WorkflowActionRepository $workflowActionRepository){
  447.         // Récupérer une variable POST spécifique
  448.         $email $request->request->get('email');
  449.         $role $request->request->get('role');
  450.         $userExist true;
  451.         $idAction $request->request->get('id_action');
  452.         $idWorkflow $request->request->get('id_workflow');
  453.         //verification if user is exist
  454.         $user $userRepository->findOneByEmail($email);
  455.         if (is_null($user)) {
  456.             $userExist false;
  457.             $user = new User();
  458.             $user->setEnabled(false);
  459.         }
  460.         $user->setEmail($email)
  461.             ->setRoles(['ROLE_CLIENT'])
  462.             ->setExternal(true)
  463.             ;
  464.         //liaison action
  465.         $action $workflowActionRepository->findOneById($idAction);
  466.         //end validation step
  467.         $entityManager->persist($user);
  468.         $entityManager->flush();
  469.         $role = ($role['role'] == 'ROLE_VALIDATOR_EXTERNAL') ? Role::ROLE_VALIDATOR_EXTERNALRole::ROLE_OBSERVER_EXTERNAL;
  470.         $action->setRecipient($role);
  471.         $action->addUser($user);;
  472.         $entityManager->persist($action);
  473.         $entityManager->flush();
  474.         if (!$userExist) {
  475.             $event = new ClientUpdatedEvent($usertrue);
  476.             $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  477.         }
  478.         $this->addFlash(
  479.             type'message',
  480.             message'Le validateur externe est bien ajouté à cette action',
  481.         );
  482.         return $this->redirectToRoute('workflow_edit', ['id' => $idWorkflow]);
  483.     }
  484.     /**
  485.      * Displays the handle view for the workflows
  486.      *
  487.      * @param Workflow|null $workflow if defined, the workflow to edit
  488.      * @param Request $request
  489.      * @param EntityManagerInterface $entityManager
  490.      * @param WorkflowActionRepository $workflowActionRepository
  491.      * @param WorkflowStepRepository $workflowStepRepository
  492.      *
  493.      * @return Response template /workflow/handle.html.twig
  494.      */
  495.     #[Route('/ajouter'name'workflow_new')]
  496.     #[Route('/test/{id}'name'workflow_edit2')]
  497.     public function handle2(Workflow $workflow nullRequest $requestEntityManagerInterface $entityManagerWorkflowActionRepository $workflowActionRepositoryWorkflowStepRepository $workflowStepRepositoryEventDispatcherInterface $dispatcher,MissionRepository $missionRepositoryWorkflowRepository $workflowRepository): Response
  498.     {
  499.         $workflowExist true;
  500.         if (null === $workflow) {
  501.             $workflowExist false;
  502.             $workflow = (new Workflow())
  503.                 ->setTemplate(true);
  504.         }
  505.         /*
  506.          * Handling the workflow informations form
  507.          */
  508.         $form $this->createForm(WorkflowType::class, $workflow);
  509.         $form->handleRequest($request);
  510.         if ($form->isSubmitted() && $form->isValid()) {
  511.             if ($workflow->getTemplate() === false && null !== $workflow->getMission()) {
  512.                 $historique = (new Historique())
  513.                     ->setUser($this->getUser())
  514.                     ->setMission($workflow->getMission())
  515.                     ->setMessage($this->getUser().' a modifié le workflow');
  516.                 $entityManager->persist($historique);
  517.             }
  518.             $entityManager->persist($workflow);
  519.             $entityManager->flush();
  520.             //link workflow into all mission if haven't workflow
  521.             
  522.             if (!$workflowExist || $form->getData()->getCompany()) {
  523.                 $product $form->getData()->getProduct();
  524.                 $company $form->getData()->getCompany();
  525.                 
  526.                 $sameWorkflow $workflowRepository->findWorkFlowByCompanyAndProduct($company$product);
  527.                 if (sizeof($sameWorkflow) >= 2) {
  528.                     $this->addFlash(
  529.                         type'error',
  530.                         message'Un workflow a déjà été créé pour ce service. Nous vous invitons à vérifier le processus existant ou en créer un nouveau pour un client en particulier si vous souhaitez activer un processus spécifique',
  531.                     );
  532.                     return $this->redirectToRoute('workflow_edit', ['id' => $workflow->getId()]);
  533.                 }
  534.                 $missions $missionRepository->findMissionWorkFlowNullByCompany($company,$product);
  535.                 $fisrtInsert true;
  536.                 foreach ($missions as $mission) {
  537.                     if ($fisrtInsert) {
  538.                         $mission->setWorkflow($workflow);
  539.                         
  540.                     }else{
  541.                         $newWorkflow = clone $workflow;
  542.                         $newWorkflow->setTemplate(false);
  543.                         $mission->setWorkflow($newWorkflow);
  544.                         $entityManager->persist($newWorkflow);
  545.                     }
  546.                     $fisrtInsert false;
  547.                     $entityManager->persist($mission);
  548.                     $entityManager->flush();
  549.                     
  550.                 }
  551.                 //end
  552.             }
  553.             
  554.             $this->addFlash(
  555.                 type'success',
  556.                 message'Le workflow a bien été enregistré',
  557.             );
  558.             return $this->redirectToRoute('workflow_edit', ['id' => $workflow->getId()]);
  559.         } elseif ($form->isSubmitted()) {
  560.             $this->addFlash(
  561.                 type'danger',
  562.                 message'Merci de corriger les erreurs',
  563.             );
  564.         }
  565.         /*
  566.          * Handling the new step form
  567.          *
  568.          * If the form is submitted when editing a step, we load it and throw a bad request exception if the step is not found
  569.          * If not, a new step is created
  570.          */
  571.         if (null !== $request->request->get('workflow_step') && isset($request->request->get('workflow_step')['stepId']) && !empty($request->request->get('workflow_step')['stepId'])) {
  572.             $step $workflowStepRepository->find($request->request->get('workflow_step')['stepId']);
  573.             if (null === $step) {
  574.                 throw new BadRequestException();
  575.             }
  576.         } else {
  577.             $step = new WorkflowStep();
  578.         }
  579.         $step->setWorkflow($workflow);
  580.         $addStepForm $this->createForm(WorkflowStepType::class, $step);
  581.         $addStepForm->handleRequest($request);
  582.         if ($addStepForm->isSubmitted() && $addStepForm->isValid()) {
  583.             $entityManager->persist($step);
  584.             $entityManager->flush();
  585.             $event = new WorkflowStepEditedEvent($step);
  586.             $dispatcher->dispatch($eventWorkflowStepEditedEvent::NAME);
  587.             $this->addFlash(
  588.                 type'success',
  589.                 message'L\'étape a bien été enregistrée',
  590.             );
  591.             return $this->redirectToRoute('workflow_edit', ['id' => $workflow->getId()]);
  592.         } elseif ($addStepForm->isSubmitted()) {
  593.             $this->addFlash(
  594.                 type'danger',
  595.                 message'Merci de corriger les erreurs',
  596.             );
  597.         }
  598.         /*
  599.          * Handling the new action form
  600.          *
  601.          * If the form is submitted when editing an action, we load it and throw a bad request exception if the action is not found
  602.          * If not, a new action is created
  603.          */
  604.         if (null !== $request->request->get('workflow_action') && isset($request->request->get('workflow_action')['actionId']) && !empty($request->request->get('workflow_action')['actionId'])) {
  605.             $action $workflowActionRepository->find($request->request->get('workflow_action')['actionId']);
  606.             if (null === $action) {
  607.                 throw new BadRequestException();
  608.             }
  609.         } else {
  610.             $action = new WorkflowAction();
  611.         }
  612.         $addActionForm $this->createForm(WorkflowActionType::class, $action, ['product' => $workflow->getProduct()]);
  613.         $addActionForm->handleRequest($request);
  614.         if ($addActionForm->isSubmitted() && $addActionForm->isValid()) {
  615.             $entityManager->persist($action);
  616.             $entityManager->flush();
  617.             $this->addFlash(
  618.                 type'success',
  619.                 message'Le workflow a bien été enregistré',
  620.             );
  621.             return $this->redirectToRoute('workflow_edit', ['id' => $workflow->getId()]);
  622.         } elseif ($addStepForm->isSubmitted()) {
  623.             $this->addFlash(
  624.                 type'danger',
  625.                 message'Merci de corriger les erreurs',
  626.             );
  627.         }
  628.         $emailTemplate = new EmailTemplate();
  629.         $formEmailTemplate $this->createForm(EmailTemplateType::class, $emailTemplate);
  630.         
  631.         return $this->renderForm('workflow/handle2.html.twig', [
  632.             'workflow' => $workflow,
  633.             'form' => $form,
  634.             'addStepForm' => $addStepForm,
  635.             'addActionForm' => $addActionForm,
  636.             'formEmailTemplate' => $formEmailTemplate,
  637.         ]);
  638.     }
  639.     
  640.     #[Route('/{id}/supprimer'name'workflow_delete' methods: ['GET'])]
  641.     public function delete(Workflow $workflowEntityManagerInterface $entityManager): RedirectResponse
  642.     {
  643.         $entityManager->remove($workflow);
  644.         $entityManager->flush();
  645.         $this->addFlash(
  646.             type'success',
  647.             message'Le workflow a bien été supprimé',
  648.         );
  649.         return $this->redirectToRoute('workflow_index');
  650.     }
  651.     #[Route('/{id}/dupliquer'name'workflow_duplicate'methods: ['GET'])]
  652.     public function duplicate(Workflow $workflowEntityManagerInterface $entityManager)
  653.     {
  654.         $workflowClone = clone $workflow;
  655.         $workflowClone->setName($workflowClone->getName().'_clone');
  656.         $workflowClone->setCompany(null);
  657.         $entityManager->persist($workflowClone);
  658.         $entityManager->flush();
  659.         $this->addFlash(
  660.             type'success',
  661.             message'Le workflow a bien été cloné',
  662.         );
  663.         return $this->redirectToRoute('workflow_index');
  664.     }
  665.     
  666. }