src/Controller/CompanyController.php line 163

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\BillingAddress;
  4. use App\Traits\Tools;
  5. use App\Entity\Company;
  6. use App\Entity\Contact;
  7. use App\Entity\DeliveryAddress;
  8. use App\Entity\Status;
  9. use App\Entity\User;
  10. use App\Form\CompanyType;
  11. use App\Service\FileUploader;
  12. use App\Repository\CompanyRepository;
  13. use App\Repository\StatusRepository;
  14. use App\Repository\UserRepository;
  15. use Symfony\Component\Mailer\MailerInterface;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  21. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  23. use Symfony\Component\HttpFoundation\File\UploadedFile;
  24. /**
  25.  * @Route("/company")
  26.  */
  27. class CompanyController extends AbstractController
  28. {
  29.     use Tools;
  30.     private $mailerInterface;
  31.     public function __construct(MailerInterface $mailerInterface)
  32.     {
  33.         $this->mailerInterface $mailerInterface;
  34.     }
  35.     /**
  36.      * @Route("/", name="company_index", methods={"GET", "POST"})
  37.      * @Security("is_granted('ROLE_COMMERCIAL') or is_granted('ROLE_ACCOUNTANT')")
  38.      *
  39.      * @param CompanyRepository $companyRepository
  40.      *
  41.      * @return Response
  42.      */
  43.     public function index(CompanyRepository $companyRepositoryStatusRepository $statusRepository): Response
  44.     {
  45.         if (isset($_POST['submitFilter']) && isset($_POST['filter'])) {
  46.             $_SESSION['filter'] = $_POST['filter'];
  47.         } elseif (isset($_POST['submitFilter']) && !isset($_POST['filter'])) {
  48.             unset($_SESSION['filter']);
  49.         } else{
  50.             $_SESSION['filter'] = [123]; // Default filters for hide archived companies
  51.         }
  52.         switch ($this->checkAccess()) {
  53.             case 'admin':
  54.             case 'accountant':
  55.                 $companies = isset($_SESSION['filter'])
  56.                     ? $companyRepository->findByStatus($_SESSION['filter'],["id" => "DESC"])
  57.                     : $companyRepository->findBy([], ["id" => "DESC"]);
  58.                 break;
  59.             case 'commercial':
  60.                 $companies = isset($_SESSION['filter'])
  61.                     ? $companyRepository->findByCommercialAndStatus($this->getUser()->getId(), $_SESSION['filter'])
  62.                     : $companyRepository->findByCommercial($this->getUser()->getId());
  63.                 break;
  64.             default:
  65.                 $companies = [];
  66.                 break;
  67.         }
  68.         $statusArray = [];
  69.         foreach ($statusRepository->findAll() as $status) {
  70.             $statusArray[] = [
  71.                 'label' => $status->getName(),
  72.                 'value' => $status->getId(),
  73.                 'selected' => isset($_SESSION['filter']) && in_array($status->getId(), $_SESSION['filter'])
  74.             ];
  75.         }
  76.         return $this->render('company/index.html.twig', [
  77.             'companies' => $companies,
  78.             'statusArray' => $statusArray
  79.         ]);
  80.     }
  81.     /**
  82.      * @Route("/new", name="company_new", methods={"GET","POST"})
  83.      *
  84.      * @param Request $request
  85.      * @param UserPasswordEncoderInterface $passwordEncoder
  86.      * @param FileUploader $fileUploader
  87.      * @param UserRepository $userRepository
  88.      *
  89.      * @return Response
  90.      */
  91.     public function new(Request $requestUserPasswordEncoderInterface $passwordEncoderFileUploader $fileUploaderUserRepository $userRepository): Response
  92.     {
  93.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  94.         $company = new Company();
  95.         $form $this->createForm(CompanyType::class, $company)->handleRequest($request);
  96.         if ($form->isSubmitted() && $form->isValid()) {
  97.             $entityManager $this->getDoctrine()->getManager();
  98.             $company->setCommercial($this->getUser());
  99.             // Create associated user owner company and add error if duplicate emails
  100.             $this->autoCreateOwner($company$entityManager$passwordEncoder$userRepository);
  101.             $entityManager->persist($company);
  102.             $entityManager->flush();
  103.             /** @var UploadedFile $kbis */
  104.             $kbis $form->get('kbis')->getData();
  105.             if (!empty($kbis)) {
  106.                 $kbis->company_id $company->getId();
  107.                 $fileUploader->upload($kbis'kbis');
  108.             }
  109.             /** @var UploadedFile $exceptionPriceFile */
  110.             $exceptionPriceFile $form->get('exception_price_file')->getData();
  111.             if (!empty($exceptionPriceFile)) {
  112.                 $exceptionPriceFile->company_id $company->getId();
  113.                 $fileUploader->upload($exceptionPriceFile'exception_price_file');
  114.             }
  115.             \App\Entity\Log::addLogFromController(
  116.                 "Create Company : ".$company->getName(),
  117.                 $company->getId(),
  118.                 $this->getUser(),
  119.                 null,
  120.                 $company,
  121.                 null,
  122.                 $entityManager
  123.             );
  124.             return $this->redirectToRoute('company_show', ['id' => $company->getId()]);
  125.         }
  126.         return $this->render('company/new.html.twig', [
  127.             'company' => $company,
  128.             'form' => $form->createView(),
  129.             'action' => 'new'
  130.         ]);
  131.     }
  132.     /**
  133.      * @Route("/{id}", name="company_show", methods={"GET"})
  134.      *
  135.      * @param Company $company
  136.      *
  137.      * @return Response
  138.      */
  139.     public function show(Company $company): Response
  140.     {
  141.         if (null !== $this->check($company)) {
  142.             return $this->redirectToRoute('app_logout');
  143.         }
  144.         $errors = [];
  145.         $errors['missing_contact'] = count($company->getContacts()) == true false;
  146.         $errors['missing_delivery_address'] = count($company->getDeliveryAddresses()) == true false;
  147.         $errors['missing_billing_address'] = null == $company->getBillingAddress() ? true false;
  148.         return $this->render('company/show.html.twig', [
  149.             'entitites_needed_to_be_filled' => $this->checkData($company),
  150.             'is_company_completed' => (in_array(true$errors) === true) ? false true,
  151.             'missing_contact' => $errors['missing_contact'],
  152.             'missing_delivery_address' => $errors['missing_delivery_address'],
  153.             'missing_billing_address' => $errors['missing_billing_address'],
  154.             'company' => $company,
  155.             'files' => $company->getFiles() ?: [],
  156.             'action' => 'new'
  157.         ]);
  158.     }
  159.     /**
  160.      * Check if required fields are empty returns true if need to be filled
  161.      *
  162.      * @param Company $company
  163.      *
  164.      * @return array
  165.      */
  166.     public function checkData(Company $company): array
  167.     {
  168.         $errors = [
  169.             'company' => [],
  170.             'contacts' => [],
  171.             'billing_addresses' => [],
  172.             'delivery_addresses' => []
  173.         ];
  174.         foreach ($company->getRequiredFields() as $field_required) {
  175.             if (empty($company->{"$field_required"}())) {
  176.                 $errors['company'] = $company->getId();
  177.             }
  178.         }
  179.         if (!$company->hasFile('kbis')) {
  180.             $errors['company'] = $company->getId();
  181.         }
  182.         foreach ($company->getContacts() as $contact) {
  183.             if (!$this->checkContact($contact)) {
  184.                 $errors['contacts'][] = $contact->getId();
  185.             };
  186.         }
  187.         foreach ($company->getDeliveryAddresses() as $delivery_address) {
  188.             if (!$this->checkDeliveryAddress($delivery_address)) {
  189.                 $errors['delivery_addresses'][] = $delivery_address->getId();
  190.             }
  191.         }
  192.         if (null !== $company->getBillingAddress()) {
  193.             if (!$this->checkBillingAddress($company->getBillingAddress())) {
  194.                 $errors['billing_addresses'][] = $company->getBillingAddress()->getId();
  195.             };
  196.         }
  197.         return $errors;
  198.     }
  199.     /**
  200.      * Check if required fields are empty
  201.      *
  202.      * @param Contact $contact
  203.      *
  204.      * @return bool
  205.      */
  206.     public function checkContact(Contact $contact): bool
  207.     {
  208.         foreach ($contact->getRequiredFields() as $field_required) {
  209.             if (empty($contact->{"$field_required"}())) {
  210.                 return false;
  211.             }
  212.         }
  213.         return true;
  214.     }
  215.     /**
  216.      * Check if required fields are empty returns true if need to be filled
  217.      *
  218.      * @param DeliveryAddress $delivery_address
  219.      *
  220.      * @return bool
  221.      */
  222.     public function checkDeliveryAddress(DeliveryAddress $delivery_address): bool
  223.     {
  224.         foreach ($delivery_address->getRequiredFields() as $field_required) {
  225.             if (empty($delivery_address->{"$field_required"}())) {
  226.                 return false;
  227.             }
  228.         }
  229.         return true;
  230.     }
  231.     /**
  232.      * Check if required fields are empty returns true if need to be filled
  233.      *
  234.      * @param BillingAddress $billing_address
  235.      *
  236.      * @return bool
  237.      */
  238.     public function checkBillingAddress(BillingAddress $billing_address): bool
  239.     {
  240.         foreach ($billing_address->getRequiredFields()['global'] as $global) {
  241.             if (empty($billing_address->{"$global"}())) {
  242.                 return false;
  243.             }
  244.         }
  245.         foreach ($billing_address->getRequiredFields()['invoice_mail_required'] as $value) {
  246.             if ($billing_address->getSendInvoiceMail()) {
  247.                 if (empty($billing_address->{"$value"}())) {
  248.                     return false;
  249.                 }
  250.             }
  251.         }
  252.         foreach ($billing_address->getRequiredFields()['prelevement_required'] as $prelevement_required) {
  253.             if ($billing_address->getPaymentMethod() == 'PRELEVEMENT') {
  254.                 if (empty($billing_address->{"$prelevement_required"}())) {
  255.                     return false;
  256.                 }
  257.             }
  258.         }
  259.         return true;
  260.     }
  261.     /**
  262.      * @Route("/{id}/edit", name="company_edit", methods={"GET","POST"})
  263.      *
  264.      * @param Request $request
  265.      * @param Company $company
  266.      * @param FileUploader $fileUploader
  267.      *
  268.      * @return Response
  269.      */
  270.     public function edit(Request $requestCompany $companyFileUploader $fileUploader): Response
  271.     {
  272.         if (null !== $this->check($company)) {
  273.             return $this->redirectToRoute('app_logout');
  274.         }
  275.         $current_status $company->getStatus()->getId();
  276.         $form $this->createForm(CompanyType::class, $company);
  277.         $form->handleRequest($request);
  278.         if ($form->isSubmitted() && $form->isValid()) {
  279.             if ($company->getLocked()) {
  280.                 $this->addFlash('warning''Société verrouillé, vous ne pouvez pas la modifier');
  281.                 return $this->redirectToRoute('company_show', ['id' => $company->getId()]);
  282.             }
  283.             $this->getDoctrine()->getManager()->flush();
  284.             /** @var UploadedFile $kbis */
  285.             $kbis $form->get('kbis')->getData();
  286.             if (!empty($kbis)) {
  287.                 $kbis->company_id $company->getId();
  288.                 $fileUploader->upload($kbis'kbis');
  289.             }
  290.             /** @var UploadedFile $exceptionPriceFile */
  291.             $exceptionPriceFile $form->get('exception_price_file')->getData();
  292.             if (!empty($exceptionPriceFile)) {
  293.                 $exceptionPriceFile->company_id $company->getId();
  294.                 $fileUploader->upload($exceptionPriceFile'exception_price_file');
  295.             }
  296.             if ($current_status != $company->getStatus()->getId()) {
  297.                 switch ($company->getStatus()->getId()) {
  298.                     case 3:
  299.                         try {
  300.                             MailerController::sendMailToAccountant($this->mailerInterface$company$this->getDoctrine()->getManager());
  301.                             $this->addFlash('success''Email envoyé');
  302.                         } catch (TransportExceptionInterface $e) {
  303.                             $this->addFlash('warning'$e->getMessage());
  304.                         }
  305.                         break;
  306.                     case 4:
  307.                         try {
  308.                             MailerController::sendMailCompanyImported($this->mailerInterface$company$this->getDoctrine()->getManager());
  309.                             $this->addFlash('success''Email envoyé');
  310.                         } catch (TransportExceptionInterface $e) {
  311.                             $this->addFlash('warning'$e->getMessage());
  312.                         }
  313.                         break;
  314.                 }
  315.             }
  316.             \App\Entity\Log::addLogFromController(
  317.                 "Edit Company",
  318.                 $company->getId(),
  319.                 $this->getUser(),
  320.                 $company,
  321.                 null,
  322.                 null,
  323.                 $this->getDoctrine()->getManager()
  324.             );
  325.             if (
  326.                 $this->isGranted('ROLE_ACCOUNTANT')
  327.                 || $this->isGranted('ROLE_COMMERCIAL')
  328.                 || count($company->getDeliveryAddresses()) >= 1
  329.             ) {
  330.                 return $this->redirectToRoute('company_show', ['id' => $company->getId()]);
  331.             }
  332.             /** Redirection to Contact form creation to continue process inscription */
  333.             return $this->redirectToRoute('contact_new', ['id_company' => $company->getId()]);
  334.         }
  335.         return $this->render('company/edit.html.twig', [
  336.             'company' => $company,
  337.             'files' => $company->getFiles(),
  338.             'form' => $form->createView(),
  339.             'action' => 'edit'
  340.         ]);
  341.     }
  342.     /**
  343.      * @Route("/{id}", name="company_delete", methods={"DELETE"})
  344.      * @Security("is_granted('ROLE_ADMIN')")
  345.      *
  346.      * @param Request $request
  347.      * @param Company $company
  348.      *
  349.      * @return Response
  350.      */
  351.     public function delete(Request $requestCompany $company): Response
  352.     {
  353.         if (null !== $this->check($company)) {
  354.             return $this->redirectToRoute('app_logout');
  355.         }
  356.         if ($this->isCsrfTokenValid('delete' $company->getId(), $request->request->get('_token'))) {
  357.             $entityManager $this->getDoctrine()->getManager();
  358.             \App\Entity\Log::addLogFromController(
  359.                 "Delete Company ".$company->getName(),
  360.                 $company->getId(),
  361.                 $this->getUser(),
  362.                 null,
  363.                 null,
  364.                 null,
  365.                 $entityManager
  366.             );
  367.             $entityManager->remove($company);
  368.             $entityManager->flush();
  369.             foreach ($company->getFiles() as $file) {
  370.                 unlink($file->getRealPath());
  371.             }
  372.         }
  373.         return $this->redirectToRoute('company_index');
  374.     }
  375.     /**
  376.      * @Route("/company_file_delete/{controller}/{id}/{timestamp}/{inode}", name="company_file_delete", methods={"GET","POST"})
  377.      *
  378.      * @param Company $company
  379.      * @param string $timestamp
  380.      * @param string $inode
  381.      *
  382.      * @return Response
  383.      */
  384.     public function deleteFile(string $controllerCompany $companystring $timestampstring $inode): Response
  385.     {
  386.         if ($file $company->getFile($timestamp$inode)) {
  387.             unlink($file->getRealPath());
  388.         }
  389.         if ($controller === 'company') {
  390.             return $this->redirectToRoute('company_edit', ['id' => $company->getId()]);
  391.         }
  392.         return $this->redirectToRoute('billing_address_edit', ['id' => $company->getBillingAddress()->getId()]);
  393.     }
  394.     /**
  395.      * @Route("/send_message/{id}", name="company_send_message", methods={"POST", "GET"})
  396.      *
  397.      * @param Request $request
  398.      * @param Company $company
  399.      *
  400.      * @return Response
  401.      */
  402.     public function sendMessage(Request $requestCompany $company): Response
  403.     {
  404.         if (null !== $this->check($company)) {
  405.             return $this->redirectToRoute('app_logout');
  406.         }
  407.         $form $this->createForm(CompanyType::class, $company);
  408.         $form->handleRequest($request);
  409.         MailerController::sendEmail(
  410.             $this->mailerInterface,
  411.             $company,
  412.             [
  413.                 'subject' => $request->request->get('subject'),
  414.                 'message' => $request->request->get('message'),
  415.                 'token_link' => $request->getSchemeAndHttpHost() . $this->generateUrl('app_api', ['token' => $company->getOwner()->getApiToken(), 'id' => $company->getId()]),
  416.             ]
  417.         );
  418.         $this->addFlash('success''Email envoyé');
  419.         return $this->redirectToRoute('company_show', ['id' => $company->getId()]);
  420.     }
  421.     /**
  422.      * @param Company $company
  423.      * @param ObjectManager $entityManager
  424.      * @param UserPasswordEncoderInterface $passwordEncoder
  425.      *
  426.      * @return bool|void
  427.      */
  428.     protected function autoCreateOwner(Company $company$entityManagerUserPasswordEncoderInterface $passwordEncoderUserRepository $userRepository)
  429.     {
  430.         if ($user $userRepository->findOneBy(['email' => $company->getEmail()])) {
  431.             $company->setOwner($user);
  432.             return false;
  433.         }
  434.         $user = new User();
  435.         $user->setFirstname($company->getName());
  436.         $user->setLastname($company->getName());
  437.         $user->setEmail($company->getEmail());
  438.         $user->setRoles(['ROLE_CLIENT']);
  439.         $user->setPassword($passwordEncoder->encodePassword(
  440.             $user,
  441.             $company->getName() . mt_rand(1010000)
  442.         ));
  443.         $entityManager->persist($user);
  444.         $company->setOwner($user);
  445.     }
  446.     /**
  447.      * @param Company $company
  448.      *
  449.      * @return bool|null
  450.      */
  451.     protected function check(Company $company): ?bool
  452.     {
  453.         if ($this->checkAccess() == 'denied') {
  454.             return false;
  455.         }
  456.         if ($this->checkAccess() == 'commercial') {
  457.             if ($company->getCommercial()->getId() != $this->getUser()->getId()) {
  458.                 return false;
  459.             }
  460.         } elseif ($this->checkAccess() == 'client') {
  461.             if ($company->getOwner()->getId() != $this->getUser()->getId()) {
  462.                 return false;
  463.             }
  464.         }
  465.         return null;
  466.     }
  467.     /**
  468.      * @Route("/send_to_accountant/{id}", name="company_to_accountant", methods={"POST", "GET"})
  469.      *
  470.      * @param Company $company
  471.      *
  472.      * @return Response
  473.      */
  474.     public function sendToAcountant(Company $company): Response
  475.     {
  476.         if (null !== $this->check($company)) {
  477.             return $this->redirectToRoute('app_logout');
  478.         }
  479.         $entityManager =  $this->getDoctrine()->getManager();
  480.         $company->setStatus($entityManager->find(Status::class, 3));
  481.         $entityManager->persist($company);
  482.         $entityManager->flush();
  483.         try {
  484.             MailerController::sendMailToAccountant($this->mailerInterface$company$entityManager);
  485.             $this->addFlash('success''Email envoyé');
  486.             
  487.             \App\Entity\Log::addLogFromController(
  488.             "Send Information to Accountant",
  489.             $company->getId(),
  490.             $this->getUser(),
  491.             null,
  492.             null,
  493.             null,
  494.             $entityManager
  495.         );
  496.         } catch (TransportExceptionInterface $e) {
  497.             $this->addFlash('warning'$e->getMessage());
  498.         }
  499.         return $this->redirectToRoute('company_show', ['id' => $company->getId()]);
  500.     }
  501.     /**
  502.      * @Route("/send_validate_importation/{id}", name="send_validate_importation", methods={"POST", "GET"})
  503.      *
  504.      * @param Company $company
  505.      *
  506.      * @return Response
  507.      */
  508.     public function sendValidateImportation(Company $company): Response
  509.     {
  510.         if (null !== $this->check($company)) {
  511.             return $this->redirectToRoute('app_logout');
  512.         }
  513.         $entityManager =  $this->getDoctrine()->getManager();
  514.         $company->setStatus($entityManager->find(Status::class, 4));
  515.         $company->setLocked(true);
  516.         $entityManager->persist($company);
  517.         $entityManager->flush();
  518.         try {
  519.             MailerController::sendMailCompanyImported($this->mailerInterface$company$entityManager);
  520.             $this->addFlash('success''Email envoyé');
  521.         } catch (TransportExceptionInterface $e) {
  522.             $this->addFlash('warning'$e->getMessage());
  523.         }
  524.         return $this->redirectToRoute('company_show', ['id' => $company->getId()]);
  525.     }
  526.     /**
  527.      * @Route("/{id}/lock", name="company_lock", methods={"GET","POST"})
  528.      * @Security("is_granted('ROLE_ADMIN')")
  529.      *
  530.      * @param Company $company
  531.      *
  532.      * @return Response
  533.      */
  534.     public function toggleLock(Company $company): Response
  535.     {
  536.         $entityManager =  $this->getDoctrine()->getManager();
  537.         $company->setLocked(!$company->getLocked());
  538.         $entityManager->persist($company);
  539.         $entityManager->flush();
  540.         \App\Entity\Log::addLogFromController(
  541.             $company->getLocked() ? 
  542.             "Lock Company ".$company->getName() : 
  543.             "Unlock Company ".$company->getName(),
  544.             $company->getId(),
  545.             $this->getUser(),
  546.             $company,
  547.             null,
  548.             null,
  549.             $this->getDoctrine()->getManager()
  550.         );
  551.         $this->addFlash('success'$company->getLocked() ? 'Société verrouillé' 'Société déverrouillé');
  552.         return $this->redirectToRoute('company_index');
  553.     }
  554. }