src/Controller/Admin/AffaireCrudController.php line 200

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Admin;
  3. use App\Entity\Affaire;
  4. use App\Entity\Proposition;
  5. use App\Field\PropositionsField;
  6. use App\Filter\AssociationFilter;
  7. use App\Form\CommandeType;
  8. use App\Form\DossierType;
  9. use App\Form\FactureType;
  10. use App\Form\PropositionType;
  11. use App\Repository\AffaireRepository;
  12. use App\Repository\UserRepository;
  13. use Doctrine\ORM\Mapping\Entity;
  14. use Doctrine\ORM\QueryBuilder;
  15. use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
  16. use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
  17. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  18. use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
  19. use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
  20. use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
  21. use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
  22. use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
  23. use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
  24. use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
  25. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityBuiltEvent;
  26. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  27. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  28. use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
  29. use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
  30. use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
  31. use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
  32. use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
  33. use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
  34. use EasyCorp\Bundle\EasyAdminBundle\Filter\ArrayFilter;
  35. use EasyCorp\Bundle\EasyAdminBundle\Filter\BooleanFilter;
  36. use EasyCorp\Bundle\EasyAdminBundle\Filter\EntityFilter;
  37. use EasyCorp\Bundle\EasyAdminBundle\Filter\TextFilter;
  38. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  39. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  40. class AffaireCrudController extends AbstractCrudController implements EventSubscriberInterface
  41. {
  42.     private $affaireRepository;
  43.     /**
  44.      * @var AdminUrlGenerator
  45.      */
  46.     private $adminUrlGenerator;
  47.     function __construct(AffaireRepository $affaireRepositoryAdminUrlGenerator $adminUrlGenerator) {
  48.         $this->affaireRepository $affaireRepository;
  49.         $this->adminUrlGenerator $adminUrlGenerator;
  50.     }
  51.     public static function getEntityFqcn(): string
  52.     {
  53.         return Affaire::class;
  54.     }
  55.     
  56.     public function configureFilters(Filters $filters): Filters
  57.     {
  58.         return $filters
  59.             ->add(EntityFilter::new('client'))
  60.             ->add(TextFilter::new('site'))
  61.             ->add(TextFilter::new('siteContact'))
  62.             ->add(EntityFilter::new('responsable'))
  63. //            ->add(TextFilter::new('responsable.nom'))
  64. //            ->add(TextFilter::new('responsable.trigramme'))
  65. //            ->add(TextFilter::new('avancement')->mapped(false))
  66.             ->add(AssociationFilter::new('propositions'))
  67. //            ->add(BooleanFilter::new('isDeleted'))
  68.         ;
  69.     }
  70.     
  71.     public function configureCrud(Crud $crud): Crud
  72.     {
  73.         return $crud
  74.             ->setPageTitle('index''Affaires')
  75.             ->setDefaultSort(['numeroAffaire' => 'DESC'])
  76.             ->setSearchFields([
  77.                 'numeroAffaire',
  78.                 'objet',
  79.                 'site',
  80.                 'siteContact',
  81.                 'client.societe',
  82.                 'client.contactNom',
  83.                 'client.contactPrenom',
  84.                 'categorie.libelleCourt',
  85.                 'categorie.libelleLong',
  86.                 'responsable.nom',
  87.                 'responsable.prenom',
  88.                 'responsable.trigramme',
  89.                 'propositions.objet',
  90.                 'propositions.avancement',
  91.                 'propositions.categorie',
  92.             ])
  93.             ->overrideTemplate('main_menu''admin/menu.html.twig')
  94.         ;
  95.     }
  96.     public function createIndexQueryBuilder(SearchDto $searchDtoEntityDto $entityDtoFieldCollection $fieldsFilterCollection $filters): QueryBuilder
  97.     {
  98.         $queryBuilder parent::createIndexQueryBuilder($searchDto$entityDto$fields$filters);
  99.         $queryBuilder->andWhere("entity.isDeleted = 0 or entity.isDeleted is null");
  100.         return $queryBuilder;
  101.     }
  102.     public function configureFields(string $pageName): iterable
  103.     {
  104.         $fields = [
  105.             // Affaire généralités
  106.             FormField::addPanel(),
  107.             TextField::new('numeroAffaire')
  108.                 ->setLabel('Numéro')
  109.                 ->setTemplatePath('field/linkedit.html.twig')
  110.                 ->setFormTypeOption('disabled','disabled')
  111.                 ->setColumns(1),
  112.             AssociationField::new('responsable')->setLabel('Resp')->setFormTypeOption(
  113.                 'query_builder', function (UserRepository  $userRepository){
  114.                 return $userRepository->findCollaborateurs();
  115.             })->setColumns(1),
  116.             AssociationField::new('agence')
  117.                 ->setLabel('Agence')
  118.                 ->setRequired(false)
  119.                 ->setColumns(2),
  120.             AssociationField::new('client')->setColumns(3),
  121.             TextField::new('site')
  122.                 ->setLabel('Site étude')
  123.                 ->addCssClass('site-field')
  124.                 ->setColumns(2),
  125.             TextField::new('siteContact')->setLabel('Site contact')->setColumns(3),
  126.         ];
  127.         // Propositions - suivi commercial
  128.         $fields[] = PropositionsField::new('propositions')
  129.             ->onlyOnIndex()
  130.             ->setSortable(false);
  131.         $fields[] = CollectionField::new('propositions')
  132.             ->hideOnIndex()
  133.             ->formatValue(function ($value) {
  134.                 return $value->getAvancement()->contains("validée") ? "validée" "Pas validée";
  135.             })
  136.             ->setEntryIsComplex()
  137.             ->useEntryCrudForm(PropositionCrudController::class)
  138.             ->setLabel('Proposition / Suivi commercial')
  139.             ->setColumns(12);
  140.         $fieldsSuite = [
  141.             // Suivi technique / Rapports
  142.             CollectionField::new('dossiers')
  143.                 ->hideOnIndex()
  144.                 ->setEntryIsComplex()
  145.                 ->setEntryType(DossierType::class)
  146.                 ->setLabel('Dossier / Suivi technique')
  147.                 ->setColumns(12),
  148.             // Site
  149.             FormField::addPanel(),
  150.             BooleanField::new('copyClientSite')->setLabel('Copier les coordonnées du client')->hideOnIndex()->setColumns(12 ),
  151.             TextField::new('siteContactTel')->setLabel('Téléphone contact')->hideOnIndex()->setColumns(2),
  152.             TextField::new('siteContactMail')->setLabel('Mail contact')->hideOnIndex()->setColumns(3),
  153.             TextField::new('siteAdresse')->setLabel('Adresse')->hideOnIndex()->setColumns(4),
  154.             TextField::new('siteCodePostal')->setLabel('CP')->hideOnIndex()->setColumns(1),
  155.             TextField::new('siteVille')->setLabel('Ville')->hideOnIndex()->setColumns(2),
  156.         ];
  157.         return array_merge($fields$fieldsSuite);
  158.     }
  159.     public static function getSubscribedEvents(): array
  160.     {
  161.         return [
  162.             BeforeEntityPersistedEvent::class => ['addAffaire'],
  163.             BeforeEntityUpdatedEvent::class => ['updateAffaire'],
  164. //            AfterEntityBuiltEvent::class => ['setPropositions'],
  165. //            AfterEntityBuiltEvent::class => ['processAffaire'],
  166.         ];
  167.     }
  168.     public function processAffaire(AfterEntityBuiltEvent $event)
  169.     {
  170. //        $entity = $event->getEntity();
  171. //        $entity->setProposition1("Prop " . "blabla");
  172.     }
  173.     public function updateAffaire(BeforeEntityUpdatedEvent $event)
  174.     {
  175.         $entity $event->getEntityInstance();
  176.         if (!($entity instanceof Affaire)) {
  177.             return;
  178.         }
  179.         if ($entity->isCopyClientSite()){
  180.             $this->processClientSite($entity);
  181.         }
  182.         $this->processPropositions($entity);
  183.     }
  184.     public function addAffaire(BeforeEntityPersistedEvent $event)
  185.     {
  186.         $entity $event->getEntityInstance();
  187.         if (!($entity instanceof Affaire)) {
  188.             return;
  189.         }
  190.         $this->setNumeroAffaire($entity);
  191.         $this->processPropositions($entity);
  192.     }
  193.     public function setNumeroAffaire(Affaire $entity): void
  194.     {
  195.         $newNumAffaire $this->affaireRepository->getNewNumAffaire(date('Y'));
  196.         $entity->setNumeroAffaire($newNumAffaire);
  197.         $entity->setCreatedAt(new \DateTime('now'));
  198.     }
  199. //    public function setPropositions(AfterEntityBuiltEvent $event)
  200. //    {
  201. //        $entity = $event->getEntity()->getInstance();
  202. //        $entity->setProposition1("Ceci est la prop 1");
  203. //    }
  204.     public function edit(AdminContext $context)
  205.     {
  206.         if ($context->getRequest()->query->has('duplicate')) {
  207.             $entity $context->getEntity()->getInstance();
  208.             /** @var Affaire $clonedAffaire */
  209.             $clonedAffaire = clone $entity;
  210.             $clonedAffaire->setCreatedAt(new \DateTime('now'));
  211.             $clonedAffaire->setDuplicate(true);
  212.             $propositions $entity->getPropositions();
  213.             if($propositions && count($propositions) > 0){
  214.                 $newProp = new Proposition();
  215.                 $p1 $propositions[0];
  216. //                $newProp = clone $p1;
  217. //                $newProp = clone $p1;
  218.                 $newProp->setObjet($p1->getObjet());
  219.                 $newProp->setCategorie($p1->getCategorie());
  220.                 $newProp->setMontantHT($p1->getMontantHT());
  221.             }
  222.             foreach ($propositions as $prop) {
  223. //                /** @var Proposition $clonedProp */
  224. //                $clonedProp = clone $prop;
  225.                 $clonedAffaire->removeProposition($prop);
  226. //                //TODO remove factures et sous traitance ?
  227. ////                foreach ()
  228. //                $clonedAffaire->addProposition($clonedProp);
  229.             }
  230.             if ($newProp)
  231.                 $clonedAffaire->addProposition($newProp);
  232.             $this->setNumeroAffaire($clonedAffaire);
  233.             $context->getRequest()->query->remove('duplicate');
  234. //            $context->getRequest()->query->set('crudAction', 'new');
  235.             $context->getEntity()->setInstance($clonedAffaire);
  236.         }
  237.         return parent::edit($context);
  238.     }
  239.     public function configureActions(Actions $actions): Actions
  240.     {
  241.         $duplicate Action::new('duplicate''Dupliquer')
  242.             ->setIcon('fa fa-copy')
  243.             ->linkToUrl(
  244.                 function (Affaire $entity) {
  245.                     return $this->adminUrlGenerator
  246.                         ->setAction(Action::EDIT)
  247.                         ->setEntityId($entity->getId())
  248.                         ->set('duplicate''1')
  249.                         ->generateUrl();
  250.                 }
  251.             );
  252.         $actions
  253.             ->add(Crud::PAGE_INDEX$duplicate)
  254.             ->update(Crud::PAGE_INDEXAction::EDIT, function (Action $action) {
  255.                 return $action->setIcon('fa fa-file-alt');
  256.             })
  257.             ->update(Crud::PAGE_EDITAction::SAVE_AND_CONTINUE, function (Action $action) {
  258.                 $action->displayIf(static function ($entity) {
  259. //                    dump($entity);
  260.                     return !$entity->isDuplicate();
  261. //                    return $entity->getSite() == "Ecole d'Ussacccc";
  262.                 });
  263.                 return $action->setIcon('fa fa-file-alt');
  264.             });;
  265.         $actions
  266.             ->remove(Crud::PAGE_INDEXAction::DELETE);
  267.         return parent::configureActions($actions);
  268.     }
  269.     /**
  270.      * @param Affaire $entity
  271.      * @return void
  272.      */
  273.     private function processPropositions(Affaire $entity): void
  274.     {
  275.         foreach ($entity->getPropositions() as $proposition) {
  276.             foreach ($proposition->getCommandes() as $commande) {
  277.                 $commande->setProposition($proposition);
  278.             }
  279. //            if($proposition->getFactures()->count() > 0) {
  280. //                $toutesFacturesSoldees = true;
  281. //                foreach ($proposition->getFactures() as $facture) {
  282. //                    $facture->setProposition($proposition);
  283. //                    if(!$facture->isSoldee()) {
  284. //                        $toutesFacturesSoldees = false;
  285. //                    }
  286. //                }
  287. //            } else {
  288. //                $toutesFacturesSoldees = false;
  289. //            }
  290.             if ($proposition->isValide()) {
  291.                 $proposition->setAvancement("Commande soldée");
  292. //            } elseif ($proposition->isValide()) {
  293. //                $proposition->setAvancement("Commande validée");
  294.             } else if ($proposition->getDateValidite() !== null) {
  295.                 $proposition->setAvancement("Commande validée");
  296.             } elseif ($proposition->getDateEnvoi() !== null) {
  297.                 $proposition->setAvancement("Devis envoyé");
  298.             } else {
  299.                 $proposition->setAvancement("Préparation devis");
  300.             }
  301.             $entity->setProposition1("Prop " $proposition->getAvancement());
  302.         }
  303.     }
  304.     private function processClientSite(Affaire $entity)
  305.     {
  306.         if($entity->getClient() != null){
  307.             $entity->setSiteContactMail($entity->getClient()->getEmail());
  308.             $entity->setSiteContactTel($entity->getClient()->getTelephone());
  309.             $entity->setSiteAdresse($entity->getClient()->getAdresse());
  310.             $entity->setSiteCodePostal($entity->getClient()->getCodePostal());
  311.             $entity->setSiteVille($entity->getClient()->getVille());
  312.         }
  313.     }
  314. }