AdherentAdmin.php 30.1 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;
8
use App\Entity\DependentChild;
Julien Jorry committed
9
use App\Entity\Geoloc;
Félicie committed
10
use App\Entity\GlobalParameter;
Julien Jorry committed
11 12 13
use App\Entity\Groupe;
use App\Entity\User;
use App\Entity\Usergroup;
14
use App\Entity\ProfilDeCotisation;
Julien Jorry committed
15 16
use App\Enum\CurrencyEnum;
use App\Events\MLCEvents;
17
use App\Exporter\CustomDoctrineORMQuerySourceIterator;
18
use App\Form\Type\DependentChildFormType;
Julien Jorry committed
19 20
use App\Form\Type\GeolocFormType;
use App\Form\Type\UserFormType;
21
use App\Utils\TAVCotisationUtils;
22
use Doctrine\ORM\Query;
Julien Jorry committed
23 24 25 26
use FOS\UserBundle\Event\UserEvent;
use Knp\Menu\ItemInterface as MenuItemInterface;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\AdminInterface;
27
use Sonata\AdminBundle\Datagrid\DatagridInterface;
Julien Jorry committed
28 29 30 31 32
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
33
use Sonata\AdminBundle\Show\ShowMapper;
34
use Sonata\DoctrineORMAdminBundle\Datagrid\OrderByToSelectWalker;
Julien Jorry committed
35
use Sonata\DoctrineORMAdminBundle\Filter\CallbackFilter;
36
use Sonata\Form\Type\DateTimeRangePickerType;
Julien Jorry committed
37 38
use Sonata\UserBundle\Model\UserManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
39
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
Julien Jorry committed
40
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
41
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
42
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
Julien Jorry committed
43
use Symfony\Component\Form\Extension\Core\Type\TextType;
44
use Symfony\Component\Form\Extension\Core\Type\NumberType;
Julien Jorry committed
45 46 47 48 49
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;
50
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
Julien Jorry committed
51 52 53 54 55 56 57 58 59 60 61 62 63

/**
 * 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;
64
    protected $tavCotisationUtils;
Julien Jorry committed
65 66 67 68 69

    protected $datagridValues = [
        // reverse order (default = 'ASC')
        '_sort_order' => 'DESC',
        // name of the ordered field (default = the model's id field, if any)
70
        '_sort_by' => 'createdAt',
Julien Jorry committed
71 72 73 74 75 76 77 78 79
        // '_page' => 1,
        // '_per_page' => 32
    ];

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

80 81 82 83 84
    public function setTavCotisationUtils(TAVCotisationUtils $tavCotisationUtils)
    {
        $this->tavCotisationUtils = $tavCotisationUtils;
    }

Julien Jorry committed
85 86 87 88 89 90 91 92 93 94 95 96 97
    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')
        ;
98 99 100 101 102 103 104 105 106 107 108 109
        // 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
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

        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
129 130 131 132 133 134 135 136
        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
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    }

    /**
     * {@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());
        }
160 161 162 163 164

        // params
        $tav_env = $this->getConfigurationPool()->getContainer()->getParameter('tav_env');
        $household_based_allowance = $this->getConfigurationPool()->getContainer()->getParameter('household_based_allowance');

Julien Jorry committed
165 166 167 168 169 170 171 172 173 174 175 176 177
        $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,
178 179
                        'with_subterritory' => $tav_env && $household_based_allowance,
                        'with_quartier' => $tav_env && $household_based_allowance
Julien Jorry committed
180 181 182 183 184 185 186 187 188 189 190 191 192 193
                    ])
                ->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()
        ;

194 195 196 197 198 199 200
        /**
         * In TAV env, 2 allowance processes possible:
         * - household based (if param set)
         * - cotisation profile and rate based (default)
         */
        if ($tav_env) {
            if ($household_based_allowance) {
201 202 203
                $formMapper
                    ->tab('General')
                        ->with('Foyer', ['class' => 'col-md-7'])
204 205 206 207 208 209 210 211 212 213 214 215
                            ->add('householdComposition',ChoiceType::class, [
                                'choices' => [
                                    "Personne seule" => "Personne seule",
                                    "Couple sans enfant à charge" => "Couple sans enfant à charge",
                                    "Famille mono-parentale" => "Famille mono-parentale",
                                    "Couple avec enfant(s) à charge" => "Couple avec enfant(s) à charge",
                                    "Autre" => "Autre"
                                ],
                                'label' => "Composition du foyer (pour information)",
                                'required' => true,
                                'placeholder' => "Choix de la composition du foyer",
                            ])
216 217 218 219 220 221 222 223 224 225
                            ->add('householdAdultCount',IntegerType::class, [
                                'label' => "Nombre total d'adultes dans le foyer (pour calculer l'allocation)",
                                'constraints' => [
                                    new GreaterThanOrEqual(['value' => 0]),
                                ],
                                'required' => true,
                                'attr' => [
                                    'autocomplete' => false
                                ]
                            ])
226 227
                            ->add('dependentChildren', CollectionType::class, [
                                'entry_type' => DependentChildFormType::class,
228 229 230 231 232
                                'entry_options' => [
                                    'label' => true,
                                    'data_class' => DependentChild::class,
                                    'attr' => ['class' => 'border pl-3 pr-3 pt-2']
                                ],
233 234 235
                                'allow_add' => true,
                                'allow_delete' => true,
                                'by_reference' => false,
236
                                'label' => "Enfant(s) à charge (pour calculer l'allocation)"
237 238 239
                            ])
                        ->end()
                    ->end();
240

241 242 243 244 245 246 247 248 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
                // Add cotisation info
                $formMapper
                    ->tab('General')
                        ->with('Informations de cotisation', ['class' => 'col-md-5'])
                            ->add('cotisationAmount', NumberType::class, [
                                'label' => 'Montant de la cotisation (en €)',
                                'help' => 'Montant minimum : 10€ par foyer + 5€/personne supplémentaire du foyer'
                            ])
                            ->add('allocationAmount', NumberType::class, [
                                'label' => 'Montant d\'allocation prévu en fonction du foyer (en MonA)',
                                'disabled' => true,
                                'required' => false,
                                'help' => 'Le montant de l\'allocation sera calculé automatiquement en fonction des informations du foyer une fois les informations sauvegardées.'
                            ])
                        ->end()
                    ->end();
            } else {
                // 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
                    ->tab('General')
                        ->with('Informations de cotisation', ['class' => 'col-md-5'])
                            ->add('profilDeCotisation', ChoiceType::class, [
                                'required' => true,
                                'label' => 'Choix du profil de cotisation :',
                                'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(ProfilDeCotisation::class)->findBy([], ['montant' => 'ASC']),
                                'empty_data' => null,
                                'placeholder' => 'Choisir un profil',
                                'choice_label' => function ($choice, $key, $value) {
                                    if (null === $choice) {
                                        return '';
                                    }
                            
                                    return $choice->__toString();
                                },
                                'attr' => [
                                    'autocomplete' => 'off'
                                ]
                            ])
                        ->end()
                    ->end();
                }
    
295
                $formMapper
296 297 298 299 300 301 302 303 304 305 306 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 335 336 337 338 339 340 341
                    ->tab('General')
                        ->with('Informations de cotisation', ['class' => 'col-md-5'])
                            ->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',
                                'attr' => [
                                    'autocomplete' => 'off'
                                ]
                            ])
                            ->add('jourPrelevement', ChoiceType::class, [
                                'required' => false,
                                'label' => 'Jour de prélèvement :',
                                'choices' => $this->daysOfMonth(),
                                'empty_data' => null,
                                'placeholder' => 'Choisir un jour de prélèvement',
                                'attr' => [
                                    'autocomplete' => 'off'
                                ]
                            ])
                            ->add('mailRappelCotisation', CheckboxType::class, [
                                'required' => false,
                                'label' => 'Recevoir un rappel du paiement de ma cotisation par mail',
                                'attr' => [
                                    'autocomplete' => 'off'
                                ]
                            ])
                            ->add('jourMailRappelCotisation', ChoiceType::class, [
                                'required' => false,
                                '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',
                                'attr' => [
                                    'autocomplete' => 'off'
                                ]
                            ])
                        ->end()
                    ->end();
342
            }
Félicie committed
343 344
    
            if (!empty($adherent) && !empty($adherent->getEmlcAccount()) ) {
Félicie committed
345
                $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
Félicie committed
346
                $balance = $adherent->getEmlcAccount()->getBalance();
Félicie committed
347
                $mlc = $em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_SYMBOL);
Félicie committed
348 349
                $formMapper
                    ->tab('General')
350
                        ->with('Informations de cotisation')
Félicie committed
351 352
                            ->add('idmlc', TextType::class, [
                                'disabled' => true,
353
                                'required' => false,
Félicie committed
354
                                'label' => 'Solde e-' . $mlc . ' :',
355 356 357 358
                                'data' => $balance . ' ' . $mlc,
                                'attr' => [
                                    'autocomplete' => 'off'
                                ]
359
                            ])
Félicie committed
360 361 362
                        ->end()
                    ->end();
            }
363 364
        }

Julien Jorry committed
365 366 367
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $formMapper->getFormBuilder()->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($em) {
            $adherent = $event->getData();
368 369

            // Check user email
Julien Jorry committed
370 371 372 373 374 375 376 377 378 379
            $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());
                }
            }
380 381 382 383 384 385 386 387 388 389 390

            // check cotisation amount 
            if ($this->getConfigurationPool()->getContainer()->getParameter('household_based_allowance')) {
                $adultsCount = $adherent->getHouseholdAdultCount();
                $dependentChildrenCount = count($adherent->getDependentChildren());
                $minCotisationAmount = 10 + 5 * ( $adultsCount - 1 ) + 5 * $dependentChildrenCount;

                if ($adherent->getCotisationAmount() < $minCotisationAmount) {
                    $event->getForm()->get('cotisationAmount')->addError(new FormError('Le montant minimum est de ' . $minCotisationAmount . '€ (selon les données du foyer indiquées)'));
                }
            }
Julien Jorry committed
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
        });
        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);
        }
421
        $this->userManager->updateCanonicalFields($adherent->getUser());
Julien Jorry committed
422 423 424 425 426 427 428 429 430 431 432
        $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);
        }

433 434 435
        if ($this->getConfigurationPool()->getContainer()->getParameter('household_based_allowance')) {
            $this->tavCotisationUtils->calculateAllowanceAccordingToHousehold($adherent);
        }
436 437 438 439

        $em->persist($adherent->getUser());
        $em->persist($adherent);
        $em->flush();
440 441
    }

Julien Jorry committed
442 443 444 445 446 447 448 449 450 451 452 453 454
    /**
     * {@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,
            ])
455 456 457 458 459 460 461 462 463 464 465 466 467 468
            ->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
469 470 471 472 473
            ->add('groupe', null, [
                'label' => 'Groupe',
                'show_filter' => true,
                'advanced_filter' => false,
            ])
474
            ->add('createdAt', 'doctrine_orm_datetime_range', [
475 476
                'field_type' => DateTimeRangePickerType::class,
                'label' => 'Date de création',
477 478
            ])
            ->add('updatedAt', 'doctrine_orm_datetime_range', [
479 480
                'field_type' => DateTimeRangePickerType::class,
                'label' => 'Date de mise à jour',
481
            ])
Julien Jorry committed
482
        ;
483 484 485 486

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

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 514 515 516 517 518 519 520 521 522 523 524 525 526 527
    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
528 529 530
    public function getFullTextFilter($queryBuilder, $alias, $field, $value)
    {
        if (!$value['value']) {
531
            return false;
Julien Jorry committed
532 533 534 535 536 537 538 539 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 572 573 574 575 576 577 578 579 580 581 582 583
        }

        // 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'])
584 585
        ;

586
        $actions = ['edit' => []];
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
        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',
                    ]
                );
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
            if($this->getConfigurationPool()->getContainer()->getParameter('household_based_allowance')
                && $this->security->isGranted('ROLE_SUPER_ADMIN') || $this->security->isGranted('ROLE_ADMIN_SIEGE')) {
                $listMapper
                    ->add(
                        'ceiling',
                        null,
                        [
                            'label' => 'Solde & plafond',
                            'template' => '@kohinos/tav/list_user_ssa_ceiling.html.twig',
                        ]
                    );
                $actions['withdrawDownToTheCeiling'] = [
                    'template' => '@kohinos/tav/adherent_action_withdraw_down_to_the_ceiling.html.twig'
                ];
            }
622 623 624
        }

        $listMapper
Julien Jorry committed
625 626 627 628 629 630 631 632 633 634
            ->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,
            ])
635 636 637 638 639 640 641 642 643
            ->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, [
644
                'actions' => $actions,
645
            ])
Julien Jorry committed
646 647 648 649 650 651
        ;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        parent::configureRoutes($collection);
652 653 654
        $collection
            ->remove('delete')
            ->add('withdrawDownToTheCeiling', $this->getRouterIdParameter() . '/withdrawDownToTheCeiling');
Julien Jorry committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
    }

    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',
676 677
            'Crée le' => 'createdAt',
            'Mise à jour le' => 'updatedAt',
Julien Jorry committed
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

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

710
        $query->select('DISTINCT ' . current($query->getRootAliases()));
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
        $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();
            }
        }

726 727 728
        $container = $this->getConfigurationPool()->getContainer();
        $em = $container->get('doctrine')->getManager();
        $cotisationUtils = $container->get('app.utils.cotisations');
729

730
        $iterator = new CustomDoctrineORMQuerySourceIterator($cotisationUtils, $em, $container, $query, $fields);
731 732 733 734
        $iterator->setDateTimeFormat('d/m/Y H:i:s'); //change this to suit your needs

        return $iterator;
    }
735 736 737 738 739 740 741 742 743

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