AdherentAdmin.php 22.7 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6
<?php

namespace App\Admin;

use App\Entity\AccountAdherent;
use App\Entity\Adherent;
7
use App\Entity\CotisationAdherent;
Julien Jorry committed
8
use App\Entity\Geoloc;
Félicie committed
9
use App\Entity\GlobalParameter;
Julien Jorry committed
10 11 12
use App\Entity\Groupe;
use App\Entity\User;
use App\Entity\Usergroup;
13
use App\Entity\ProfilDeCotisation;
Julien Jorry committed
14 15
use App\Enum\CurrencyEnum;
use App\Events\MLCEvents;
16
use App\Exporter\CustomDoctrineORMQuerySourceIterator;
Julien Jorry committed
17 18
use App\Form\Type\GeolocFormType;
use App\Form\Type\UserFormType;
19
use Doctrine\ORM\Query;
Julien Jorry committed
20 21 22 23
use FOS\UserBundle\Event\UserEvent;
use Knp\Menu\ItemInterface as MenuItemInterface;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\AdminInterface;
24
use Sonata\AdminBundle\Datagrid\DatagridInterface;
Julien Jorry committed
25 26 27 28 29
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
Félicie committed
30
use Sonata\AdminBundle\Show\ShowMapper;
31
use Sonata\DoctrineORMAdminBundle\Datagrid\OrderByToSelectWalker;
Julien Jorry committed
32
use Sonata\DoctrineORMAdminBundle\Filter\CallbackFilter;
33
use Sonata\Form\Type\DateTimeRangePickerType;
Julien Jorry committed
34 35
use Sonata\UserBundle\Model\UserManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
36
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
Julien Jorry committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
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 adhérents.
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 *
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class AdherentAdmin extends AbstractAdmin
{
    protected $baseRouteName = 'adherent';
    protected $baseRoutePattern = 'adherent';
    protected $security;

    protected $datagridValues = [
        // reverse order (default = 'ASC')
        '_sort_order' => 'DESC',
        // name of the ordered field (default = the model's id field, if any)
62
        '_sort_by' => 'createdAt',
Julien Jorry committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        // '_page' => 1,
        // '_per_page' => 32
    ];

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

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

    protected function configureQuery(ProxyQueryInterface $query): ProxyQueryInterface
    {
        $user = $this->security->getUser();
        $query = parent::configureQuery($query);
        $query
            ->innerJoin($query->getRootAliases()[0] . '.user', 'u')
            ->addSelect('u')
        ;
85 86 87 88 89 90 91 92 93 94 95 96
        // if ($this->hasRequest()) {
        //     if (empty($this->getRequest()->getSession()->get('_groupegere'))) {
        //         if ($this->security->isGranted('ROLE_GESTION_GROUPE') || $this->security->isGranted('ROLE_CONTACT')) {
        //             $query->andWhere('false = true');
        //         }
        //     } else {
        //         $query
        //             ->andWhere($query->getRootAliases()[0] . '.groupe = :groupe')
        //             ->setParameter('groupe', $this->getRequest()->getSession()->get('_groupegere'))
        //         ;
        //     }
        // }
Julien Jorry committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

        return $query;
    }

    protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
    {
        if (!$childAdmin && !in_array($action, ['edit', 'show'])) {
            return;
        }

        $admin = $this->isChild() ? $this->getParent() : $this;
        $id = $admin->getRequest()->get('id');
        $user = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(User::class)->findOneBy(['adherent' => $id]);

        if ($this->isGranted('EDIT') && null != $user) {
            $menu->addChild("Modifier l'utilisateur", [
                'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('admin_app_user_edit', ['id' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
            ]);
        }
Félicie committed
116 117 118 119 120 121 122 123
        if (!$this->getConfigurationPool()->getContainer()->getParameter('tav_env')) {
            $menu->addChild('Ajouter une cotisation', [
                'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('cotisation_adherent_create', ['expediteur' => $id], UrlGeneratorInterface::ABSOLUTE_URL),
            ]);
            $menu->addChild('Voir les cotisations', [
                'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('cotisation_adherent_list', ['filter' => ['expediteur' => ['value' => $id]]], UrlGeneratorInterface::ABSOLUTE_URL),
            ]);
        }
Julien Jorry committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 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
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper): void
    {
        // Initialize adherent
        $adherent = $this->getSubject();
        $now = new \DateTime();
        if ($this->isCurrentRoute('create')) {
            $user = $this->userManager->createUser();
            $groupe = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Adherent');
            $user->setEnabled(true);
            $user->addPossiblegroup($groupe);
            $user->setGroups([$groupe]);
            $adherent->setEcompte(0);
            $user->setAdherent($adherent);
            $adherent->setUser($user);
        }
        if (null == $adherent->getGeoloc()) {
            $adherent->setGeoloc(new Geoloc());
        }
        $formMapper
            ->tab('General')
                ->with('Identité', ['class' => 'col-md-7'])
                    ->add('user', UserFormType::class, [
                        'label' => false,
                    ])
                ->end()
                ->with('Adresse', ['class' => 'col-md-5'])
                    ->add('geoloc', GeolocFormType::class, [
                        'label' => false,
                        'required' => true,
                        'with_geoloc' => false,
                        'with_latlon' => false,
                    ])
                ->end()
                ->with('Groupe', ['class' => 'col-md-5'])
                    ->add('groupe', ChoiceType::class, [
                        'required' => true,
                        'label' => 'Groupe local :',
                        'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Groupe::class)->findAll(),
                        'choice_label' => 'name',
                        'placeholder' => 'Choisir un groupe',
                    ])
                ->end()
            ->end()
        ;

174
        if ($this->getConfigurationPool()->getContainer()->getParameter('tav_env')) {
175 176 177 178 179 180 181 182 183 184 185 186 187 188
            // For Comptoir role in edit mode, hide profile choice
            $displayProfilChoice = true;
            $isComptoirOnly = 
                $this->security->isGranted('ROLE_COMPTOIR')
                && !$this->isGranted('ROLE_ADMIN')
                && !$this->isGranted('ROLE_SUPER_ADMIN')
                && !$this->isGranted('ROLE_ADMIN_SIEGE');

            if ($isComptoirOnly && $this->isCurrentRoute('edit')) {
                $displayProfilChoice = false;
            }

            if ($displayProfilChoice) {
                $formMapper
189
                ->tab('General')
190
                    ->with('Informations de cotisation', ['class' => 'col-md-5'])
191
                        ->add('profilDeCotisation', ChoiceType::class, [
192
                            'required' => true,
Damien Moulard committed
193
                            'label' => 'Choix du profil de cotisation :',
194
                            'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(ProfilDeCotisation::class)->findBy([], ['montant' => 'ASC']),
195
                            'empty_data' => null,
196
                            'placeholder' => 'Choisir un profil',
197 198
                            'choice_label' => function ($choice, $key, $value) {
                                if (null === $choice) {
199
                                    return '';
200 201 202 203 204
                                }
                        
                                return $choice->__toString();
                            }
                        ])
205 206 207 208 209 210 211
                    ->end()
                ->end();
            }

            $formMapper
                ->tab('General')
                    ->with('Informations de cotisation', ['class' => 'col-md-5'])
212 213 214 215 216 217 218 219 220 221 222 223 224
                        ->add('moyenDePaiement', ChoiceType::class, [
                            'required' => true,
                            'label' => 'Moyen de paiement :',
                            'choices' => [
                                "CB" => "CB",
                                "espèces" => "espèces",
                                "chèque" => "chèque",
                                "prélèvement" => "prélèvement"
                            ],
                            'empty_data' => null,
                            'placeholder' => 'Choisir un moyen de paiement'
                        ])
                        ->add('jourPrelevement', ChoiceType::class, [
Yvon committed
225
                            'required' => false,
226 227 228 229 230 231 232 233 234 235
                            'label' => 'Jour de prélèvement :',
                            'choices' => $this->daysOfMonth(),
                            'empty_data' => null,
                            'placeholder' => 'Choisir un jour de prélèvement'
                        ])
                        ->add('mailRappelCotisation', CheckboxType::class, [
                            'required' => false,
                            'label' => 'Recevoir un rappel du paiement de ma cotisation par mail',
                        ])
                        ->add('jourMailRappelCotisation', ChoiceType::class, [
Yvon committed
236
                            'required' => false,
237 238 239 240 241
                            'label' => 'Jour de l\'envoi du mail de rappel :',
                            'choices' => $this->daysOfMonth(),
                            'empty_data' => null,
                            'placeholder' => 'Choisir un jour pour l\'envoi du mail de rappel'
                        ])
242 243
                    ->end()
                ->end();
Félicie committed
244 245
    
            if (!empty($adherent) && !empty($adherent->getEmlcAccount()) ) {
Félicie committed
246
                $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
Félicie committed
247
                $balance = $adherent->getEmlcAccount()->getBalance();
Félicie committed
248
                $mlc = $em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_SYMBOL);
Félicie committed
249 250
                $formMapper
                    ->tab('General')
251
                        ->with('Informations de cotisation')
Félicie committed
252 253
                            ->add('idmlc', TextType::class, [
                                'disabled' => true,
254
                                'required' => false,
Félicie committed
255
                                'label' => 'Solde e-' . $mlc . ' :',
256 257
                                'data' => $balance . ' ' . $mlc
                            ])
Félicie committed
258 259 260
                        ->end()
                    ->end();
            }
261 262
        }

Julien Jorry committed
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
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $formMapper->getFormBuilder()->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($em) {
            $adherent = $event->getData();
            $user = $adherent->getUser();
            if (!$user || null === $user->getId()) {
                $repo = $em->getRepository(User::class);
                $emailExist = $repo->findBy(['email' => $user->getEmail()]);
                if (count($emailExist) > 0) {
                    $event->getForm()->get('user')->get('email')->addError(new FormError('Courriel déjà utilisé !'));
                } else {
                    $user->setUsername($user->getEmail());
                }
            }
        });
        parent::configureFormFields($formMapper);
    }

    public function preUpdate($adherent)
    {
        $this->updateAdherent($adherent);
    }

    public function prePersist($adherent)
    {
        $this->updateAdherent($adherent);
        $this->eventDispatcher->dispatch(MLCEvents::REGISTRATION_ADHERENT, new UserEvent($adherent->getUser(), $this->getRequest()));
    }

    private function updateAdherent($adherent)
    {
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();

        if (empty($adherent->getUser()->getUsername())) {
            $adherent->getUser()->setUsername($adherent->getUser()->getEmail());
        }
        if (empty($adherent->getUser()->getPassword())) {
            // @TODO : generate password with tokengenerator
            // $tokenGenerator = $this->getConfigurationPool()->getContainer()->get('fos_user.util.token_generator');
            // $password = substr($tokenGenerator->generateToken(), 0, 12);
            $bytes = random_bytes(64);
            $password = rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
            $adherent->getUser()->setPassword($password);
        }
306
        $this->userManager->updateCanonicalFields($adherent->getUser());
Julien Jorry committed
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
        $adherent->getUser()->createEmailToken();
        $account = $em->getRepository(AccountAdherent::class)->findOneBy(['adherent' => $adherent, 'currency' => CurrencyEnum::CURRENCY_EMLC]);
        if (null == $account) {
            $account = new AccountAdherent();
            $account
                ->setCurrency(CurrencyEnum::CURRENCY_EMLC)
            ;
            $adherent->addAccount($account);
            $em->persist($account);
        }
        $em->persist($adherent->getUser());
        $em->persist($adherent);
        $em->flush();
    }

    /**
     * {@inheritdoc}
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        $datagridMapper
            ->add('full_text', CallbackFilter::class, [
                'callback' => [$this, 'getFullTextFilter'],
                'field_type' => TextType::class,
                'label' => 'Recherche par Nom / Prenom / Courriel',
                'show_filter' => true,
                'advanced_filter' => false,
            ])
335 336 337 338 339 340 341 342 343 344 345 346 347 348
            ->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,
            ])
Julien Jorry committed
349 350 351 352 353
            ->add('groupe', null, [
                'label' => 'Groupe',
                'show_filter' => true,
                'advanced_filter' => false,
            ])
354
            ->add('createdAt', 'doctrine_orm_datetime_range', [
355 356
                'field_type' => DateTimeRangePickerType::class,
                'label' => 'Date de création',
357 358
            ])
            ->add('updatedAt', 'doctrine_orm_datetime_range', [
359 360
                'field_type' => DateTimeRangePickerType::class,
                'label' => 'Date de mise à jour',
361
            ])
Julien Jorry committed
362
        ;
363 364 365 366

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

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    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(CotisationAdherent::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
408 409 410
    public function getFullTextFilter($queryBuilder, $alias, $field, $value)
    {
        if (!$value['value']) {
411
            return false;
Julien Jorry committed
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 460 461 462 463
        }

        // Use `andWhere` instead of `where` to prevent overriding existing `where` conditions
        $queryBuilder->andWhere($queryBuilder->expr()->orX(
            $queryBuilder->expr()->like('u.username', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
            $queryBuilder->expr()->like('u.email', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
            $queryBuilder->expr()->like('u.firstname', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
            $queryBuilder->expr()->like('u.lastname', $queryBuilder->expr()->literal('%' . $value['value'] . '%'))
        ));

        return true;
    }

    /**
     * @param EventDispatcherInterface $userManager
     */
    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * @return EventDispatcherInterface
     */
    public function getEventDispatcher()
    {
        return $this->eventDispatcher;
    }

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

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

    protected function configureListFields(ListMapper $listMapper): void
    {
        unset($this->listModes['mosaic']);
        $listMapper
            ->addIdentifier('user.lastname', null, ['label' => 'Nom'])
            ->addIdentifier('user.firstname', null, ['label' => 'Prénom'])
            ->addIdentifier('user.email', null, ['label' => 'Email'])
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
        ;

        if (!$this->getConfigurationPool()->getContainer()->getParameter('tav_env')) {
            $listMapper
                ->add(
                    'cotisation',
                    null,
                    [
                        'label' => 'Cotisation à jour',
                        'template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list_user_cotisation.html.twig',
                    ]
                );
        } else {
            $listMapper
                ->add(
                    'cotisation',
                    null,
                    [
                        'label' => 'Dernière cotisation',
                        'template' => '@kohinos/tav/list_user_tav_cotisation.html.twig',
                    ]
                );
        }

        $listMapper
Julien Jorry committed
489 490 491 492 493 494 495 496 497 498
            ->addIdentifier('groupe', null, [
                'label' => 'Groupe',
                'sortable' => true,
                'sort_field_mapping' => ['fieldName' => 'name'],
                'sort_parent_association_mappings' => [['fieldName' => 'groupe']],
            ])
            ->add('user.enabled', null, [
                'label' => 'Activé',
                'editable' => true,
            ])
499 500 501 502 503 504 505 506 507 508 509
            ->add('user.createdAt', 'date', [
                'pattern' => 'dd/MM/YYYY HH:mm',
                'label' => 'Crée le',
            ])
            ->add('user.updatedAt', 'date', [
                'pattern' => 'dd/MM/YYYY HH:mm',
                'label' => 'Mis à jour le',
            ])
            ->add('_action', null, [
                'actions' => ['edit' => []],
            ])
Julien Jorry committed
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
        ;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        parent::configureRoutes($collection);
        $collection->remove('delete');
    }

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

        return $actions;
    }

    public function getExportFields()
    {
        return [
            'Id' => 'id',
            'Nom' => 'user.lastname',
            'Prénom' => 'user.firstname',
            'username' => 'user.username',
            'Email' => 'user.email',
            'Groupe' => 'groupe.name',
            'Téléphone' => 'user.phone',
            'Mobile' => 'user.mobile',
538 539
            'Crée le' => 'createdAt',
            'Mise à jour le' => 'updatedAt',
Julien Jorry committed
540 541
        ];
    }
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571

    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();

572
        $query->select('DISTINCT ' . current($query->getRootAliases()));
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
        $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();
            }
        }

588 589 590
        $container = $this->getConfigurationPool()->getContainer();
        $em = $container->get('doctrine')->getManager();
        $cotisationUtils = $container->get('app.utils.cotisations');
591

592
        $iterator = new CustomDoctrineORMQuerySourceIterator($cotisationUtils, $em, $container, $query, $fields);
593 594 595 596
        $iterator->setDateTimeFormat('d/m/Y H:i:s'); //change this to suit your needs

        return $iterator;
    }
597 598 599 600 601 602 603 604 605

    private function daysOfMonth()
    {
        $res = [];
        for($i = 1 ; $i < 29 ; $i++) {
            $res[$i] = $i;
        }
        return $res;
    }
Julien Jorry committed
606
}
Félicie committed
607