src/Controller/Admin/AffaireCrudController.php line 196

  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('client')->setColumns(3),
  117.             TextField::new('site')
  118.                 ->setLabel('Site étude')
  119.                 ->addCssClass('site-field')
  120.                 ->setColumns(3),
  121.             TextField::new('siteContact')->setLabel('Site contact')->setColumns(4),
  122.         ];
  123.         // Propositions - suivi commercial
  124.         $fields[] = PropositionsField::new('propositions')
  125.             ->onlyOnIndex()
  126.             ->setSortable(false);
  127.         $fields[] = CollectionField::new('propositions')
  128.             ->hideOnIndex()
  129.             ->formatValue(function ($value) {
  130.                 return $value->getAvancement()->contains("validée") ? "validée" "Pas validée";
  131.             })
  132.             ->setEntryIsComplex()
  133.             ->useEntryCrudForm(PropositionCrudController::class)
  134.             ->setLabel('Proposition / Suivi commercial')
  135.             ->setColumns(12);
  136.         $fieldsSuite = [
  137.             // Suivi technique / Rapports
  138.             CollectionField::new('dossiers')
  139.                 ->hideOnIndex()
  140.                 ->setEntryIsComplex()
  141.                 ->setEntryType(DossierType::class)
  142.                 ->setLabel('Dossier / Suivi technique')
  143.                 ->setColumns(12),
  144.             // Site
  145.             FormField::addPanel(),
  146.             BooleanField::new('copyClientSite')->setLabel('Copier les coordonnées du client')->hideOnIndex()->setColumns(12 ),
  147.             TextField::new('siteContactTel')->setLabel('Téléphone contact')->hideOnIndex()->setColumns(2),
  148.             TextField::new('siteContactMail')->setLabel('Mail contact')->hideOnIndex()->setColumns(3),
  149.             TextField::new('siteAdresse')->setLabel('Adresse')->hideOnIndex()->setColumns(4),
  150.             TextField::new('siteCodePostal')->setLabel('CP')->hideOnIndex()->setColumns(1),
  151.             TextField::new('siteVille')->setLabel('Ville')->hideOnIndex()->setColumns(2),
  152.         ];
  153.         return array_merge($fields$fieldsSuite);
  154.     }
  155.     public static function getSubscribedEvents(): array
  156.     {
  157.         return [
  158.             BeforeEntityPersistedEvent::class => ['addAffaire'],
  159.             BeforeEntityUpdatedEvent::class => ['updateAffaire'],
  160. //            AfterEntityBuiltEvent::class => ['setPropositions'],
  161. //            AfterEntityBuiltEvent::class => ['processAffaire'],
  162.         ];
  163.     }
  164.     public function processAffaire(AfterEntityBuiltEvent $event)
  165.     {
  166. //        $entity = $event->getEntity();
  167. //        $entity->setProposition1("Prop " . "blabla");
  168.     }
  169.     public function updateAffaire(BeforeEntityUpdatedEvent $event)
  170.     {
  171.         $entity $event->getEntityInstance();
  172.         if (!($entity instanceof Affaire)) {
  173.             return;
  174.         }
  175.         if ($entity->isCopyClientSite()){
  176.             $this->processClientSite($entity);
  177.         }
  178.         $this->processPropositions($entity);
  179.     }
  180.     public function addAffaire(BeforeEntityPersistedEvent $event)
  181.     {
  182.         $entity $event->getEntityInstance();
  183.         if (!($entity instanceof Affaire)) {
  184.             return;
  185.         }
  186.         $this->setNumeroAffaire($entity);
  187.         $this->processPropositions($entity);
  188.     }
  189.     public function setNumeroAffaire(Affaire $entity): void
  190.     {
  191.         $newNumAffaire $this->affaireRepository->getNewNumAffaire(date('Y'));
  192.         $entity->setNumeroAffaire($newNumAffaire);
  193.         $entity->setCreatedAt(new \DateTime('now'));
  194.     }
  195. //    public function setPropositions(AfterEntityBuiltEvent $event)
  196. //    {
  197. //        $entity = $event->getEntity()->getInstance();
  198. //        $entity->setProposition1("Ceci est la prop 1");
  199. //    }
  200.     public function edit(AdminContext $context)
  201.     {
  202.         if ($context->getRequest()->query->has('duplicate')) {
  203.             $entity $context->getEntity()->getInstance();
  204.             /** @var Affaire $clonedAffaire */
  205.             $clonedAffaire = clone $entity;
  206.             $clonedAffaire->setCreatedAt(new \DateTime('now'));
  207.             $clonedAffaire->setDuplicate(true);
  208.             $propositions $entity->getPropositions();
  209.             if($propositions && count($propositions) > 0){
  210.                 $newProp = new Proposition();
  211.                 $p1 $propositions[0];
  212. //                $newProp = clone $p1;
  213. //                $newProp = clone $p1;
  214.                 $newProp->setObjet($p1->getObjet());
  215.                 $newProp->setCategorie($p1->getCategorie());
  216.                 $newProp->setMontantHT($p1->getMontantHT());
  217.             }
  218.             foreach ($propositions as $prop) {
  219. //                /** @var Proposition $clonedProp */
  220. //                $clonedProp = clone $prop;
  221.                 $clonedAffaire->removeProposition($prop);
  222. //                //TODO remove factures et sous traitance ?
  223. ////                foreach ()
  224. //                $clonedAffaire->addProposition($clonedProp);
  225.             }
  226.             if ($newProp)
  227.                 $clonedAffaire->addProposition($newProp);
  228.             $this->setNumeroAffaire($clonedAffaire);
  229.             $context->getRequest()->query->remove('duplicate');
  230. //            $context->getRequest()->query->set('crudAction', 'new');
  231.             $context->getEntity()->setInstance($clonedAffaire);
  232.         }
  233.         return parent::edit($context);
  234.     }
  235.     public function configureActions(Actions $actions): Actions
  236.     {
  237.         $duplicate Action::new('duplicate''Dupliquer')
  238.             ->setIcon('fa fa-copy')
  239.             ->linkToUrl(
  240.                 function (Affaire $entity) {
  241.                     return $this->adminUrlGenerator
  242.                         ->setAction(Action::EDIT)
  243.                         ->setEntityId($entity->getId())
  244.                         ->set('duplicate''1')
  245.                         ->generateUrl();
  246.                 }
  247.             );
  248.         $actions
  249.             ->add(Crud::PAGE_INDEX$duplicate)
  250.             ->update(Crud::PAGE_INDEXAction::EDIT, function (Action $action) {
  251.                 return $action->setIcon('fa fa-file-alt');
  252.             })
  253.             ->update(Crud::PAGE_EDITAction::SAVE_AND_CONTINUE, function (Action $action) {
  254.                 $action->displayIf(static function ($entity) {
  255. //                    dump($entity);
  256.                     return !$entity->isDuplicate();
  257. //                    return $entity->getSite() == "Ecole d'Ussacccc";
  258.                 });
  259.                 return $action->setIcon('fa fa-file-alt');
  260.             });;
  261.         $actions
  262.             ->remove(Crud::PAGE_INDEXAction::DELETE);
  263.         return parent::configureActions($actions);
  264.     }
  265.     /**
  266.      * @param Affaire $entity
  267.      * @return void
  268.      */
  269.     private function processPropositions(Affaire $entity): void
  270.     {
  271.         foreach ($entity->getPropositions() as $proposition) {
  272.             foreach ($proposition->getCommandes() as $commande) {
  273.                 $commande->setProposition($proposition);
  274.             }
  275. //            if($proposition->getFactures()->count() > 0) {
  276. //                $toutesFacturesSoldees = true;
  277. //                foreach ($proposition->getFactures() as $facture) {
  278. //                    $facture->setProposition($proposition);
  279. //                    if(!$facture->isSoldee()) {
  280. //                        $toutesFacturesSoldees = false;
  281. //                    }
  282. //                }
  283. //            } else {
  284. //                $toutesFacturesSoldees = false;
  285. //            }
  286.             if ($proposition->isValide()) {
  287.                 $proposition->setAvancement("Commande soldée");
  288. //            } elseif ($proposition->isValide()) {
  289. //                $proposition->setAvancement("Commande validée");
  290.             } else if ($proposition->getDateValidite() !== null) {
  291.                 $proposition->setAvancement("Commande validée");
  292.             } elseif ($proposition->getDateEnvoi() !== null) {
  293.                 $proposition->setAvancement("Devis envoyé");
  294.             } else {
  295.                 $proposition->setAvancement("Préparation devis");
  296.             }
  297.             $entity->setProposition1("Prop " $proposition->getAvancement());
  298.         }
  299.     }
  300.     private function processClientSite(Affaire $entity)
  301.     {
  302.         if($entity->getClient() != null){
  303.             $entity->setSiteContactMail($entity->getClient()->getEmail());
  304.             $entity->setSiteContactTel($entity->getClient()->getTelephone());
  305.             $entity->setSiteAdresse($entity->getClient()->getAdresse());
  306.             $entity->setSiteCodePostal($entity->getClient()->getCodePostal());
  307.             $entity->setSiteVille($entity->getClient()->getVille());
  308.         }
  309.     }
  310. }