PrestataireAdmin.php 39 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6 7
<?php

namespace App\Admin;

use App\Entity\AccountPrestataire;
use App\Entity\Adherent;
use App\Entity\ContactPrestataire;
8 9
use App\Entity\CotisationAdherent;
use App\Entity\CotisationPrestataire;
Julien Jorry committed
10 11 12 13 14 15 16 17 18 19
use App\Entity\EtatPrestataire;
use App\Entity\GlobalParameter;
use App\Entity\Groupe;
use App\Entity\Prestataire;
use App\Entity\Rubrique;
use App\Entity\User;
use App\Entity\Usergroup;
use App\Enum\CurrencyEnum;
use App\Events\MLCEvents;
use App\Events\PrestataireEvent;
20
use App\Exporter\CustomDoctrineORMQuerySourceIterator;
Julien Jorry committed
21 22 23
use App\Form\Type\ContactEntityFormType;
use App\Form\Type\GeolocPrestataireFormType;
use App\Form\Type\UserFormType;
24
use App\Form\Type\PrestataireProductFamilyFormType;
25
use Doctrine\ORM\Query;
Julien Jorry committed
26 27 28 29 30 31
use FOS\CKEditorBundle\Form\Type\CKEditorType;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\Model\UserManagerInterface;
use Knp\Menu\ItemInterface as MenuItemInterface;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\AdminInterface;
32
use Sonata\AdminBundle\Datagrid\DatagridInterface;
Julien Jorry committed
33 34
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
35
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
Julien Jorry committed
36 37 38
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Object\Metadata;
use Sonata\AdminBundle\Route\RouteCollection;
39
use Sonata\DoctrineORMAdminBundle\Datagrid\OrderByToSelectWalker;
Julien Jorry committed
40
use Sonata\DoctrineORMAdminBundle\Filter\CallbackFilter;
41
use Sonata\Form\Type\DateTimeRangePickerType;
Julien Jorry committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
use Sonata\MediaBundle\Form\Type\MediaType;
use Sonata\MediaBundle\Provider\MediaProviderInterface;
use Sonata\MediaBundle\Provider\Pool;
use SpecShaper\GdprBundle\Form\Type\PersonalDataType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\PercentType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;

/**
 * Administration des prestataires.
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 *
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class PrestataireAdmin extends AbstractAdmin
{
    protected $baseRouteName = 'prestataire';
    protected $baseRoutePattern = 'prestataire';
    protected $security;
    protected $eventDispatcher;
    protected $pool;
    protected $datagridValues = [
        // reverse order (default = 'ASC')
        '_sort_order' => 'DESC',
        // name of the ordered field (default = the model's id field, if any)
        '_sort_by' => 'raison',
        // '_page' => 1,
        // '_per_page' => 32
    ];

    public function setSecurity(Security $security)
    {
        $this->security = $security;
    }

    public function setPool(Pool $pool)
    {
        $this->pool = $pool;
    }

    public function configure()
    {
        parent::configure();
    }

    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * {@inheritdoc}
     */
    public function createQuery($context = 'list')
    {
        $user = $this->security->getUser();
        $query = parent::createQuery($context);

111 112 113 114 115 116 117 118 119 120 121 122 123 124
        // if ($user && ($this->security->isGranted('ROLE_GESTION_GROUPE') || $this->security->isGranted('ROLE_CONTACT') || $this->security->isGranted('ROLE_TRESORIER'))) {
        //     if ($this->hasRequest()) {
        //         if (empty($this->getRequest()->getSession()->get('_groupegere'))) {
        //             if (!$this->security->isGranted('ROLE_TRESORIER')) {
        //                 $query->andWhere('false = true');
        //             }
        //         } else {
        //             $query
        //                 ->andWhere($query->getRootAliases()[0] . '.groupe = :group')
        //                 ->setParameter('group', $this->getRequest()->getSession()->get('_groupegere'))
        //             ;
        //         }
        //     }
        // }
Julien Jorry committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

        return $query;
    }

    protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
    {
        if (!$childAdmin && !in_array($action, ['edit', 'show'])) {
            return;
        }
        $user = $this->security->getUser();
        $admin = $this->isChild() ? $this->getParent() : $this;
        $id = $admin->getRequest()->get('id');

        $presta = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Prestataire::class)->findOneById($id);
        $users = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(User::class)->findByPrestataire($id);

        if ($this->isGranted('EDIT') && !empty($users)) {
            // @TODO : si plusieurs utilisateurs, mettre un lien par user pour modifier celui-ci ?
            // $menu->addChild("Modifier l'utilisateur", [
            //     'uri' => $this->getConfigurationPool ()->getContainer()->get('router')->generate('admin_app_user_edit', ['id' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL)
            // ]);
        }
        // Le prestataire "Monnaie Locale" représentant l'asso recevant les cotisations n'a pas de cotisations lui même !
148
        if (!$presta->isMlc() && !$this->getConfigurationPool()->getContainer()->getParameter('tav_env')) {
Julien Jorry committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
            $menu->addChild('Ajouter une cotisation', [
                'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('cotisation_prestataire_create', ['expediteur' => $id], UrlGeneratorInterface::ABSOLUTE_URL),
            ]);
            $menu->addChild('Voir les cotisations', [
                'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('cotisation_prestataire_list', ['filter' => ['expediteur' => ['value' => $id]]], UrlGeneratorInterface::ABSOLUTE_URL),
            ]);
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper): void
    {
        // Initialize prestataire
        $presta = $this->getSubject();
        // $user = $this->security->getUser();
        $now = new \DateTime();
        $cotisation = null;

        // get the current Image instance
        $imageHelp = null;
        if (!empty($presta) && !empty($presta->getMedia())) {
            $image = $presta->getMedia();
            if ($image && ($webPath = $image->getWebPath())) {
                // get the container so the full path to the image can be set
                $container = $this->getConfigurationPool()->getContainer();
                $fullPath = $container->get('request_stack')->getCurrentRequest()->getBasePath() . '/' . $webPath;
                // add a 'help' option containing the preview's img tag
                $imageHelp = '<img src="' . $fullPath . '" class="admin-preview" />';
            }
        }

        $formMapper
            ->tab('Prestataire')
                ->with('Prestataire', ['class' => 'col-md-6'])
                    ->add('typeprestataire', null, [
                        'label' => 'Type :',
                        'required' => true,
                        'expanded' => true,
                    ])
                    ->add('groupe', ChoiceType::class, [
                        'required' => false,
                        'label' => 'Groupe local :',
193
                        'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Groupe::class)->findBy(['enabled' => true], ['name' => 'ASC']),
Julien Jorry committed
194 195 196 197 198 199 200 201
                        'choice_label' => 'name',
                        'placeholder' => 'Choisir un groupe',
                    ])
                    ->add('raison', TextType::class, [
                        'label' => 'Raison :',
                        'required' => true,
                    ])
                    ->add('statut', TextType::class, [
202
                        'label' => 'Activité :',
Julien Jorry committed
203 204 205 206 207 208
                        'required' => false,
                    ])
                    ->add('siret', TextType::class, [
                        'label' => 'SIRET :',
                        'required' => false,
                    ])
Yvon committed
209
                    //bic is new field in kohinos-ssa (I think it's OK to add it for non-tav env as well)
Yvon committed
210 211 212 213
                    ->add('bic', TextType::class, [
                        'label' => 'BIC :',
                        'required' => false,
                    ])
Julien Jorry committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
                    ->add('iban', PersonalDataType::class, [
                        'label' => 'IBAN :',
                        'required' => false,
                        'attr' => [
                            'placeholder' => 'Entrez un IBAN valide',
                        ],
                    ])
                    ->add('responsable', TextType::class, [
                        'label' => 'Responsable :',
                        'required' => false,
                    ])
                    ->add('metier', TextType::class, [
                        'label' => 'Métier responsable :',
                        'required' => false,
                    ])
                    ->add('horaires', TextType::class, [
                        'label' => 'Horaires',
                        'required' => false,
                    ])
                    ->add('web', UrlType::class, [
                        'label' => 'Site Web',
                        'required' => false,
                    ])
                    ->add('description', CKEditorType::class, [
                        'label' => 'Description',
                        'required' => false,
                    ])
241 242 243 244
                    ->add('comments', CKEditorType::class, [
                        'label' => 'Observations (privé)',
                        'required' => false,
                    ])
Julien Jorry committed
245 246 247
                    ->add('tauxreconversion', PercentType::class, [
                        'label' => 'Taux de reconversion',
                        'required' => false,
248
                        'scale' => 2,
Julien Jorry committed
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
                        'type' => 'integer',
                        'help' => 'Si la valeur est nulle, par défaut le taux de reconversion sera de ' . $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(GlobalParameter::class)->val(GlobalParameter::RECONVERSION_PRESTATAIRE) . ' %',
                    ])
                    ->add('acceptemlc', null, [
                        'label' => 'Accepte la monnaie électronique ?',
                        'required' => false,
                    ])
                    ->add('enabled', null, [
                        'label' => 'Activé ?',
                        'required' => false,
                    ])
                ->end()
                ->with('Contact(s)', ['class' => 'col-md-6'])
                    ->add('contacts', CollectionType::class, [
                        'entry_type' => ContactEntityFormType::class,
                        'entry_options' => ['label' => false, 'data_class' => ContactPrestataire::class],
                        'allow_add' => true,
                        'allow_delete' => true,
                        'by_reference' => false,
                        'label' => false,
                    ])
                ->end()
                ->with('Adresse(s)', ['class' => 'col-md-6'])
                    ->add('geolocs', CollectionType::class, [
                        'entry_type' => GeolocPrestataireFormType::class,
                        'entry_options' => ['label' => false],
                        'allow_add' => true,
                        'allow_delete' => true,
                        'by_reference' => false,
                        'label' => false,
                    ])
                ->end()
                ->with('Classification', ['class' => 'col-md-6'])
                    ->add('etats', EntityType::class, [
                        'class' => EtatPrestataire::class,
                        'multiple' => true,
                        'required' => false,
                        'by_reference' => false,
                        'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(EtatPrestataire::class)->findBy([]),
                        'label' => 'Tags',
                    ])
                    ->add('rubriques', EntityType::class, [
                        'class' => Rubrique::class,
                        'multiple' => true,
                        'required' => false,
                        'by_reference' => false,
                        'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Rubrique::class)->findBy(['enabled' => true]),
                        'label' => 'Rubriques',
                    ])
                ->end()
                ->with('Image', ['class' => 'col-md-6'])
                    ->add('media', MediaType::class, [
                        'provider' => 'sonata.media.provider.image',
                        'context' => 'prestataire',
                        'help' => $imageHelp,
                        'required' => false,
                    ])
                ->end()
                ->with('Gestionnaire(s)', ['class' => 'col-md-6'])
                    ->add('users', EntityType::class, [
                        // 'mapped' => false,
                        'class' => User::class,
                        'multiple' => true,
                        'required' => false,
                        'label' => 'Associer à un(des) utilisateur(s) existant :',
314 315 316 317
                        'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(User::class)->findOrderByName(),
                        'choice_label' => function ($user) {
                            return $user->getLastname() . ' ' . $user->getFirstname() . ' (' . $user->getEmail() . ')';
                        },
Julien Jorry committed
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
                        'placeholder' => 'Choisir un utilisateur',
                    ])
                    ->add('newusers', CollectionType::class, [
                        'mapped' => false,
                        'required' => false,
                        'label' => 'Nouvel Utilisateur/Adhérent',
                        'entry_type' => UserFormType::class,
                        'entry_options' => [
                            'required' => false,
                            'label' => false, ],
                        'by_reference' => false,
                        'allow_add' => true,
                        'allow_delete' => true,
                    ])
                ->end()
                ->with('Caissier(s)', ['class' => 'col-md-6'])
                    ->add('caissiers', EntityType::class, [
                        // 'mapped' => false,
                        'class' => User::class,
                        'multiple' => true,
                        'required' => false,
                        'label' => 'Associer à un(des) utilisateur(s) existant :',
340 341 342 343
                        'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(User::class)->findOrderByName(),
                        'choice_label' => function ($user) {
                            return $user->getLastname() . ' ' . $user->getFirstname() . ' (' . $user->getEmail() . ')';
                        },
Julien Jorry committed
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
                        'placeholder' => 'Choisir un utilisateur',
                    ])
                    ->add('newcaissiers', CollectionType::class, [
                        'mapped' => false,
                        'required' => false,
                        'label' => 'Nouvel Utilisateur/Adhérent',
                        'entry_type' => UserFormType::class,
                        'entry_options' => [
                            'required' => false,
                            'label' => false, ],
                        'by_reference' => false,
                        'allow_add' => true,
                        'allow_delete' => true,
                    ])
                ->end()
            ->end()
        ;
361

362 363 364 365
        /** 
         * In case of prestataire self init and evaluation use case activated,
         * set prestataire disabled by default & add 'conventionnement' field.
         */
366 367 368 369
        if ($this->getConfigurationPool()->getContainer()->getParameter('presta_self_init_and_eval')) {
            $formMapper
                ->tab('Prestataire')
                    ->with('Prestataire', ['class' => 'col-md-6'])
370 371 372 373
                        ->remove('enabled')
                        ->add('enabled', null, [
                            'label' => 'Activé ?',
                            'required' => false,
374 375
                            'data' => $presta && $presta->getRaison() ? $presta->isEnabled() : false, //force false at create time only
                            'attr' => ['autocomplete' => 'off']
376
                        ])
377 378
                        ->add('conventionnement', ChoiceType::class, [
                            'choices' => [
379 380 381
                                '50 %' => '0.50', //using strings (and not floats) seems required
                                '75 %' => '0.75', //to make display work fine
                                '100 %' => '1.00',
382 383
                            ],
                            'required' => false,
384
                            'attr' => ['autocomplete' => 'off'] //avoid non-saved value to be displayed
385 386 387 388 389
                        ])
                    ->end()
                ->end();
        }

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
        if ($this->getConfigurationPool()->getContainer()->getParameter('presta_extra_data')) {
            $formMapper
                ->tab('Prestataire')
                    ->with('Prestataire', ['class' => 'col-md-6'])
                        ->add('prestataireProductFamilies', CollectionType::class, [
                            'label' => 'Produits que le prestataire a renseigné',
                            'entry_type' => PrestataireProductFamilyFormType::class,
                            'required' => false,
                            'disabled' => true,
                            'entry_options' => [
                                'attr' => ['class' => 'prestataire-products-families-row'],
                            ],
                        ])
                    ->end()
                ->end();
        }

Julien Jorry committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
        // @TODO : add tags model transformer if add new from text
        // ->get('etats')
        // ->addModelTransformer(new CallbackTransformer(
        //     function ($tagsAsArray) {
        //         // transform the array to a string
        //         return $tagsAsArray;
        //     },
        //     function ($tagsAsString) {
        //         // transform the string back to an array
        //         return explode(', ', $tagsAsString);
        //     }
        // ))

        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $formMapper->getFormBuilder()->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            $prestataire = $event->getData();
            $users = null;
            /*
                Permet d'ajouter le nouvel utilisateur crée (newusers) aux gestionnaires du presta
                (On crée un compte adhérent en même temps que le prestataire)
             */
            if (null != $event->getForm()->get('users')->getData()) {
                $users = $event->getForm()->get('users')->getData();
                $this->addUsersOrCaissers($users, $prestataire);
            }
            if (null != $event->getForm()->get('caissiers')->getData()) {
                $caissiers = $event->getForm()->get('caissiers')->getData();
                $this->addUsersOrCaissers($caissiers, $prestataire, 'ROLE_CAISSIER');
            }
            if (null != $event->getForm()->get('newusers')->getData()) {
                $newusers = $event->getForm()->get('newusers')->getData();
                $return = $this->addUsersOrCaissers($newusers, $prestataire);
                if (false === $return) {
                    $event->getForm()->get('newusers')->addError(new FormError('Gestionnaires : Courriel(s) déjà utilisé : ' . implode(', ', $return) . '!'));
                }
            }
            if (null != $event->getForm()->get('newcaissiers')->getData()) {
                $newcaissiers = $event->getForm()->get('newcaissiers')->getData();
                $return = $this->addUsersOrCaissers($newcaissiers, $prestataire, 'ROLE_CAISSIER');
                if (count($return) > 0) {
                    $event->getForm()->get('newcaissiers')->addError(new FormError('Caissiers : Courriel(s) déjà utilisé : ' . implode(', ', $return) . '!'));
                }
            }
        });
        parent::configureFormFields($formMapper);
    }

    private function addUsersOrCaissers($users, Prestataire $prestataire, string $role = 'ROLE_PRESTATAIRE')
    {
        $return = [];
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        foreach ($users as $user) {
            $newUser = false;
460
            if (null == $user || null == $user->getId()) {
Julien Jorry committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
                $newUser = true;
                $emailExist = $em->getRepository(User::class)->findBy(['email' => $user->getEmail()]);
                if (count($emailExist) > 0) {
                    $return[] = $emailExist;
                    break;
                }
                $user->setUsername($user->getEmail());
                $adh = new Adherent();
                $user->setAdherent($adh);
                $user->setPassword(md5(random_bytes(10)));
                $groupeAdh = $em->getRepository(Usergroup::class)->findOneByName('Adherent');
                $user->addPossiblegroup($groupeAdh);
            }
            if ('ROLE_PRESTATAIRE' == $role) {
                $prestataire->addUser($user);
                $groupePresta = $em->getRepository(Usergroup::class)->findOneByName('Prestataire');
                if ($newUser) {
                    $this->eventDispatcher->dispatch(MLCEvents::REGISTRATION_PRESTATAIRE, new PrestataireEvent($user, $prestataire, $this->getRequest()));
                }
            } elseif ('ROLE_CAISSIER' == $role) {
                $prestataire->addCaissier($user);
                $groupePresta = $em->getRepository(Usergroup::class)->findOneByName('Caissier');
                if ($newUser) {
                    $this->eventDispatcher->dispatch(MLCEvents::REGISTRATION_CAISSIER, new PrestataireEvent($user, $prestataire, $this->getRequest()));
                }
            }
            $user->addPossiblegroup($groupePresta);
488
            $this->userManager->updateCanonicalFields($user);
Julien Jorry committed
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
            $em->persist($user);
            if ($newUser) {
                $this->eventDispatcher->dispatch(MLCEvents::REGISTRATION_ADHERENT, new UserEvent($user, $this->getRequest()));
            }
            $em->persist($prestataire);
        }
        $em->flush();

        return $return;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        parent::configureDatagridFilters($datagridMapper);
        $datagridMapper
        ->add('full_text', CallbackFilter::class, [
            'callback' => [$this, 'getFullTextFilter'],
            'field_type' => TextType::class,
            'label' => 'Recherche par nom',
            'show_filter' => true,
            'advanced_filter' => false,
        ])
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
        ->add('cotisationajour', CallbackFilter::class, [
            'callback' => [$this, 'getCotisationFilter'],
            'field_type' => ChoiceType::class,
            'field_options' => [
                'choices' => [
                    'Oui' => true,
                    'Non' => false,
                ],
            ],
            'multiple' => false,
            'label' => 'Cotisation à jour ?',
            'show_filter' => true,
            'advanced_filter' => false,
        ])
        ->add('gestionnaireajour', CallbackFilter::class, [
            'callback' => [$this, 'getGestionnaireFilter'],
            'field_type' => ChoiceType::class,
            'field_options' => [
                'choices' => [
                    'Oui' => true,
                    'Non' => false,
                ],
            ],
            'multiple' => false,
            'label' => 'Gestionnaire à jour de sa cotisation ?',
            'show_filter' => true,
            'advanced_filter' => false,
        ])
Julien Jorry committed
542 543 544 545 546 547 548 549 550 551 552
        ->add('groupe', null, [
            'label' => 'Groupe',
            'show_filter' => true,
            'advanced_filter' => false,
        ])
        ->add('etats', null, [
            'label' => 'Tags',
            'show_filter' => true,
            'advanced_filter' => false,
        ], null, ['expanded' => true, 'multiple' => true,
        ])
553 554 555 556 557 558 559 560
        ->add('enabled', null, [
            'label' => 'Activé',
            'advanced_filter' => false,
        ])
        ->add('acceptemlc', null, [
            'label' => 'Accepte e-mlc',
            'advanced_filter' => false,
        ])
561
        ->add('createdAt', 'doctrine_orm_datetime_range', [
562 563
            'field_type' => DateTimeRangePickerType::class,
            'label' => 'Date de création',
564 565
        ])
        ->add('updatedAt', 'doctrine_orm_datetime_range', [
566 567
            'field_type' => DateTimeRangePickerType::class,
            'label' => 'Date de mise à jour',
568
        ])
Julien Jorry committed
569 570 571 572 573
        ->add('typeprestataire', null, [
            'label' => 'Type',
            'advanced_filter' => false,
        ])
        ;
574 575 576 577 578

        if ($this->getConfigurationPool()->getContainer()->getParameter('tav_env')) {
            $datagridMapper->remove('cotisationajour');
            $datagridMapper->remove('gestionnaireajour');
        }
Julien Jorry committed
579 580
    }

581 582 583 584 585 586 587 588 589 590 591
    public function getGestionnaireFilter($queryBuilder, $alias, $field, $value)
    {
        if (null === $value['value']) {
            return false;
        }

        $container = $this->getConfigurationPool()->getContainer();
        $em = $container->get('doctrine.orm.entity_manager');
        $expr = $em->getExpressionBuilder();

        $a = $em->getRepository(CotisationAdherent::class)
592 593 594 595 596
            ->createQueryBuilder('ca')
            ->select('aa.id')
            ->leftJoin('ca.expediteur', 'aa')
            ->leftJoin('ca.cotisationInfos', 'ii')
            ->where('ii.fin > :now')
597 598 599 600 601
            ->getQuery()
            ->getDQL();

        if (true === $value['value']) {
            $queryBuilder
602 603
                ->leftJoin($alias . '.users', 'uu')
                ->leftJoin('uu.adherent', 'dd')
604 605
                ->andWhere(
                    $expr->in(
606
                        'dd.id',
607 608 609 610 611
                        $a
                    )
            );
        } else {
            $queryBuilder
612 613
                ->leftJoin($alias . '.users', 'uu')
                ->leftJoin('uu.adherent', 'dd')
614 615
                ->andWhere(
                    $expr->notIn(
616
                        'dd.id',
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
                        $a
                    )
            );
        }
        $queryBuilder->setParameter('now', new \DateTime('now'));

        return true;
    }

    public function getCotisationFilter($queryBuilder, $alias, $field, $value)
    {
        if (null === $value['value']) {
            return false;
        }

        $container = $this->getConfigurationPool()->getContainer();
        $em = $container->get('doctrine.orm.entity_manager');
        $expr = $em->getExpressionBuilder();

        $a = $em->getRepository(CotisationPrestataire::class)
            ->createQueryBuilder('c')
            ->select('a.id')
            ->leftJoin('c.expediteur', 'a')
            ->leftJoin('c.cotisationInfos', 'i')
            ->where('i.fin > :now')
            ->getQuery()
            ->getDQL();

        if (true === $value['value']) {
            $queryBuilder->andWhere(
                $expr->in(
                    $alias . '.id',
                    $a
                )
            );
        } else {
            $queryBuilder->andWhere(
                $expr->notIn(
                    $alias . '.id',
                    $a
                )
            );
        }
        $queryBuilder->setParameter('now', new \DateTime('now'));

        return true;
    }

Julien Jorry committed
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
    public function getFullTextFilter($queryBuilder, $alias, $field, $value)
    {
        if (!$value['value']) {
            return;
        }

        // Use `andWhere` instead of `where` to prevent overriding existing `where` conditions
        $queryBuilder->andWhere($queryBuilder->expr()->orX(
            $queryBuilder->expr()->like($alias . '.raison', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
            $queryBuilder->expr()->like($alias . '.statut', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
            $queryBuilder->expr()->like($alias . '.description', $queryBuilder->expr()->literal('%' . $value['value'] . '%'))
        ));

        return true;
    }

    public function getTemplate($name)
    {
        if ('edit' == $name) {
            return '@kohinos/presta/block/base_edit_prestataires.html.twig';
        }

        return parent::getTemplate($name);
    }

    /**
     * @param UserManagerInterface $userManager
     */
    public function setUserManager(UserManagerInterface $userManager): void
    {
        $this->userManager = $userManager;
    }

    /**
     * @return UserManagerInterface
     */
    public function getUserManager()
    {
        return $this->userManager;
    }

    public function getRouteShowOnFront($object)
    {
        return $this->routeGenerator->generate('show_prestataire', ['slug' => $object->getSlug()]);
    }

    protected function configureListFields(ListMapper $listMapper): void
    {
        unset($this->listModes['mosaic']);
        $isWordpressActivated = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_WORDPRESS);
        if ('false' == $isWordpressActivated) {
            $actions = [
                'show' => ['template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list__action_showonfront.html.twig'],
                'edit' => [
                    // You may add custom link parameters used to generate the action url
                    'link_parameters' => [
                        'full' => true,
                    ],
723 724
                ],
            ];
725
            if (($this->security->isGranted('ROLE_GESTION_GROUPE') || $this->security->isGranted('ROLE_SUPER_ADMIN')) && $this->getConfigurationPool()->getContainer()->getParameter('presta_self_init_and_eval')) {
726
                $actions['reviewPrestaQuiz'] = [
727
                    'template' => '@kohinos/tav/prestaquiz/review.html.twig'
728 729
                ];
            }
730 731 732 733
            if (null != $this->security->getUser() && ($this->security->isGranted('ROLE_SUPER_ADMIN') || $this->security->isGranted('ROLE_ADMIN_PRESTATAIRE_COTISATIONS_ALL') || $this->security->isGranted('ROLE_ADMIN_PRESTATAIRE_COTISATIONS_CREATE'))) {
                $actions['addfreecotisationpresta'] = [
                    'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list__action_addfreecotisationpresta.html.twig',
                ];
734 735 736
                $actions['addfreecotisationadh'] = [
                    'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list__action_addfreecotisationadh.html.twig',
                ];
737
            }
Julien Jorry committed
738 739 740 741 742 743 744
        } else {
            $actions = [
                'edit' => [
                    // You may add custom link parameters used to generate the action url
                    'link_parameters' => [
                        'full' => true,
                    ],
745 746 747 748 749 750
                ],
            ];
            if (null != $this->security->getUser() && ($this->security->isGranted('ROLE_SUPER_ADMIN') || $this->security->isGranted('ROLE_ADMIN_PRESTATAIRE_COTISATIONS_ALL') || $this->security->isGranted('ROLE_ADMIN_PRESTATAIRE_COTISATIONS_CREATE'))) {
                $actions['addfreecotisationpresta'] = [
                    'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list__action_addfreecotisationpresta.html.twig',
                ];
751 752 753
                $actions['addfreecotisationadh'] = [
                    'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list__action_addfreecotisationadh.html.twig',
                ];
754
            }
Julien Jorry committed
755
        }
756
        // listmappers for each environment (pro & tav_env)
757
        $listMapper
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
            ->addIdentifier('raisonAndIdmlc', 'html', [
                'label' => 'Raison',
            ])
            ->add('groupe', null, [
                'label' => 'Groupe',
                'sortable' => true,
                'sort_field_mapping' => ['fieldName' => 'name'],
                'sort_parent_association_mappings' => [['fieldName' => 'groupe']],
            ])
            // ->addIdentifier('users', null, array('label' => 'Gestionnaires'))
            ->add('rubriques', null)
            ->add('etats', null, [
                'label' => 'Tags',
                // 'editable' => true,
                // 'class' => EtatPrestataire::class,
                // 'multiple' => true,
                // // 'required' => false,
                // // 'by_reference' => false,
                // 'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(EtatPrestataire::class)->findBy(array('enabled' => true))
            ])
            ->add(
                'cotisation',
                null,
                [
                    'label' => 'Cotisation à jour',
                    'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list_presta_cotisation.html.twig',
                ]
            )
            ->add('users', null, [
                'label' => 'Gestionnaires [Cotisation à jour]',
                'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list_presta_gestionnaires.html.twig',
            ])
            ->add('enabled', null, [
                'label' => 'Activé',
                'editable' => true,
            ])
            ->add('acceptemlc', null, [
                'label' => 'Accepte e-mlc',
                'editable' => true,
            ])
            ->add('createdAt', 'date', [
                'pattern' => 'dd/MM/YYYY HH:mm',
                'label' => 'Crée le',
            ])
            ->add('updatedAt', 'date', [
                'pattern' => 'dd/MM/YYYY HH:mm',
                'label' => 'Mis à jour le',
            ])
            // You may also specify the actions you want to be displayed in the list
            ->add('_action', null, [
                'actions' => $actions,
            ])
810 811 812 813 814
        ;

        if ($this->getConfigurationPool()->getContainer()->getParameter('tav_env')) {
            $listMapper->remove('cotisation');
            $listMapper->remove('users');
815
        }
Julien Jorry committed
816 817 818 819 820
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        $collection->remove('delete');
821
        $collection
822 823
            ->add('addfreecotisationpresta', $this->getRouterIdParameter() . '/addfreecotisationpresta')
            ->add('addfreecotisationadh', $this->getRouterIdParameter() . '/addfreecotisationadh')
824
            ->add('reviewprestaquiz', $this->getRouterIdParameter() . '/reviewprestaquiz')
825
        ;
Julien Jorry committed
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
    }

    public function getObjectMetadata($object)
    {
        if (null != $object->getMedia()) {
            $provider = $this->pool->getProvider($object->getMedia()->getProviderName());

            $url = $provider->generatePublicUrl(
                $object->getMedia(),
                $provider->getFormatName($object->getMedia(), MediaProviderInterface::FORMAT_ADMIN)
            );

            return new Metadata($object->getRaison(), strip_tags($object->getDescription()), $url);
        }

        return new Metadata($object->getRaison(), strip_tags($object->getDescription()));
    }

    public function getBatchActions()
    {
        $actions = parent::getBatchActions();
        unset($actions['delete']);

        return $actions;
    }

    public function preUpdate($prestataire)
    {
        $this->prePersist($prestataire);
    }

    public function prePersist($prestataire)
    {
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();

        $account = $em->getRepository(AccountPrestataire::class)->findOneBy(['prestataire' => $prestataire, 'currency' => CurrencyEnum::CURRENCY_EMLC]);
        if (null == $account) {
            $account = new AccountPrestataire();
            $account
                ->setCurrency(CurrencyEnum::CURRENCY_EMLC)
            ;
            $prestataire->addAccount($account);
            $em->persist($account);
        }
        $em->persist($prestataire);
        $em->flush();
    }

    public function getExportFields()
    {
        return [
            'Id' => 'id',
878
            'Activé ?' => 'enabled',
Julien Jorry committed
879
            'Raison' => 'raison',
880
            'Groupe local' => 'groupe.name',
Julien Jorry committed
881 882
            'Rubriques' => 'rubriquesString',
            'Gestionnaires' => 'usersString',
883
            'Gestionnaires emails' => 'gestionnairesEmailsString',
Julien Jorry committed
884
            'Tags' => 'etatsString',
885 886
            'Crée le' => 'createdAt',
            'Mise à jour le' => 'updatedAt',
Julien Jorry committed
887 888
        ];
    }
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918

    public function getDataSourceIterator()
    {
        $datagrid = $this->getDatagrid();
        $datagrid->buildPager();

        $fields = [];

        foreach ($this->getExportFields() as $key => $field) {
            // NEXT_MAJOR: Remove the following code in favor of the commented one.
            $label = $this->getTranslationLabel($field, 'export', 'label');
            $transLabel = $this->getTranslator()->trans($label, [], $this->getTranslationDomain());
            if ($transLabel === $label) {
                $fields[$key] = $field;
            } else {
                $fields[$transLabel] = $field;
            }
        }

        return $this->getModelDataSourceIterator($datagrid, $fields);
    }

    /**
     * @return DoctrineORMQuerySourceIterator
     */
    public function getModelDataSourceIterator(DatagridInterface $datagrid, array $fields, $firstResult = null, $maxResult = null)
    {
        $datagrid->buildPager();
        $query = $datagrid->getQuery();

919
        $query->select('DISTINCT ' . current($query->getRootAliases()));
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
        $query->setFirstResult($firstResult);
        $query->setMaxResults($maxResult);

        if ($query instanceof ProxyQueryInterface) {
            $sortBy = $query->getSortBy();

            if (!empty($sortBy)) {
                $query->addOrderBy($sortBy, $query->getSortOrder());
                $query = $query->getQuery();
                $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [OrderByToSelectWalker::class]);
            } else {
                $query = $query->getQuery();
            }
        }

935 936 937
        $container = $this->getConfigurationPool()->getContainer();
        $em = $container->get('doctrine')->getManager();
        $cotisationUtils = $container->get('app.utils.cotisations');
938

939
        $iterator = new CustomDoctrineORMQuerySourceIterator($cotisationUtils, $em, $container, $query, $fields);
940 941 942 943
        $iterator->setDateTimeFormat('d/m/Y H:i:s'); //change this to suit your needs

        return $iterator;
    }
Julien Jorry committed
944
}