AdherentAdmin.php 33.8 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;
43
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
Julien Jorry committed
44
use Symfony\Component\Form\Extension\Core\Type\TextType;
45
use Symfony\Component\Form\Extension\Core\Type\NumberType;
Julien Jorry committed
46 47 48 49 50
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;
51
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
Julien Jorry committed
52 53 54 55 56 57 58 59 60 61 62 63 64

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

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

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

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

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

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

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

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

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

195 196 197 198 199 200 201
        /**
         * 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) {
202 203 204
                $formMapper
                    ->tab('General')
                        ->with('Foyer', ['class' => 'col-md-7'])
205 206 207 208 209 210 211 212 213 214 215 216
                            ->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",
                            ])
217 218 219 220 221 222 223 224 225 226
                            ->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
                                ]
                            ])
227 228
                            ->add('dependentChildren', CollectionType::class, [
                                'entry_type' => DependentChildFormType::class,
229 230 231 232 233
                                'entry_options' => [
                                    'label' => true,
                                    'data_class' => DependentChild::class,
                                    'attr' => ['class' => 'border pl-3 pr-3 pt-2']
                                ],
234 235 236
                                'allow_add' => true,
                                'allow_delete' => true,
                                'by_reference' => false,
237
                                'label' => "Enfant(s) à charge (pour calculer l'allocation)"
238 239 240
                            ])
                        ->end()
                    ->end();
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 295
                // 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();
                }
    
296
                $formMapper
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 342
                    ->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();
343
            }
Félicie committed
344 345
    
            if (!empty($adherent) && !empty($adherent->getEmlcAccount()) ) {
Félicie committed
346
                $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
Félicie committed
347
                $balance = $adherent->getEmlcAccount()->getBalance();
Félicie committed
348
                $mlc = $em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_SYMBOL);
Félicie committed
349 350
                $formMapper
                    ->tab('General')
351
                        ->with('Informations de cotisation')
Félicie committed
352 353
                            ->add('idmlc', TextType::class, [
                                'disabled' => true,
354
                                'required' => false,
Félicie committed
355
                                'label' => 'Solde e-' . $mlc . ' :',
356 357 358 359
                                'data' => $balance . ' ' . $mlc,
                                'attr' => [
                                    'autocomplete' => 'off'
                                ]
360
                            ])
Félicie committed
361 362
                        ->end()
                    ->end();
363 364 365 366 367 368 369 370 371 372 373
                //Add form part allowing super admin to fix balance
                if($this->getConfigurationPool()->getContainer()->getParameter('household_based_allowance')
                    && $this->security->isGranted('ROLE_SUPER_ADMIN')) {
                    $formMapper
                        ->tab('General')
                            ->with('Informations de cotisation')
                                ->add('fixedBalance', TextType::class, [
                                    'label' => "Corriger le solde suite à une erreur de cotisation",
                                    'mapped' => false,
                                    'required' => false,
                                    'attr' => [
374 375
                                        'autocomplete' => 'off',
                                        'class' => 'fixBalanceAdherentFormPart'
376 377 378 379 380 381
                                    ]
                                ])
                                ->add('justification', TextType::class, [
                                    'mapped' => false,
                                    'required' => false,
                                    'attr' => [
382 383
                                        'autocomplete' => 'off',
                                        'class' => 'fixBalanceAdherentFormPart'
384 385 386 387 388 389 390 391
                                    ]
                                ])
                                ->add('password', PasswordType::class, [
                                    'label' => 'Mot de passe pour corriger le solde',
                                    'mapped' => false,
                                    'required' => false,
                                    'data' => "",
                                    'attr' => [
392 393
                                        'autocomplete' => 'off',
                                        'class' => 'fixBalanceAdherentFormPart'
394 395 396 397 398
                                    ]
                                ])
                            ->end()
                        ->end();
                }
Félicie committed
399
            }
400 401
        }

Julien Jorry committed
402 403 404
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $formMapper->getFormBuilder()->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($em) {
            $adherent = $event->getData();
405 406

            // Check user email
Julien Jorry committed
407 408 409 410 411 412 413 414 415 416
            $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());
                }
            }
417 418

            if ($this->getConfigurationPool()->getContainer()->getParameter('household_based_allowance')) {
419
                // check cotisation amount
420 421 422 423 424 425 426
                $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)'));
                }
427 428 429 430 431 432

                // try to fix balance if required
                if($this->security->isGranted('ROLE_SUPER_ADMIN')
                    && $event->getForm()->has('fixedBalance')
                    && $event->getForm()->get('fixedBalance')->getData()
                    && $event->getForm()->get('fixedBalance')->getData() >= 0) {
433
                    $password = $this->getConfigurationPool()->getContainer()->getParameter('fix_balance_adherent_password');
434 435 436 437 438 439 440 441 442 443 444 445 446
                    //this password purpose is to be an additional warning for super admin and
                    //is not intended to be securely stored as only super admin can use this feature
                    if ($event->getForm()->get('password')->getData() !== $password) {
                        $event->getForm()->get('password')->addError(new FormError('Mot de passe incorrect.'));
                    } elseif(!$event->getForm()->get('justification')->getData()) {
                        $event->getForm()->get('justification')->addError(new FormError('Merci de justifier cette opération sensible.'));
                    } else {
                        $this->tavCotisationUtils->fixBalance(
                            $adherent, $event->getForm()->get('fixedBalance')->getData(), $event->getForm()->get('justification')->getData()
                        );
                        $em->flush();
                    }
                }
447
            }
Julien Jorry committed
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        });
        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);
        }
478
        $this->userManager->updateCanonicalFields($adherent->getUser());
Julien Jorry committed
479 480 481 482 483 484 485 486 487 488 489
        $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);
        }

490 491 492
        if ($this->getConfigurationPool()->getContainer()->getParameter('household_based_allowance')) {
            $this->tavCotisationUtils->calculateAllowanceAccordingToHousehold($adherent);
        }
493 494 495 496

        $em->persist($adherent->getUser());
        $em->persist($adherent);
        $em->flush();
497 498
    }

Julien Jorry committed
499 500 501 502 503 504 505 506 507 508 509 510 511
    /**
     * {@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,
            ])
512 513 514 515 516 517 518 519 520 521 522 523 524 525
            ->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
526 527 528 529 530
            ->add('groupe', null, [
                'label' => 'Groupe',
                'show_filter' => true,
                'advanced_filter' => false,
            ])
531
            ->add('createdAt', 'doctrine_orm_datetime_range', [
532 533
                'field_type' => DateTimeRangePickerType::class,
                'label' => 'Date de création',
534 535
            ])
            ->add('updatedAt', 'doctrine_orm_datetime_range', [
536 537
                'field_type' => DateTimeRangePickerType::class,
                'label' => 'Date de mise à jour',
538
            ])
Julien Jorry committed
539
        ;
540 541 542 543

        if ($this->getConfigurationPool()->getContainer()->getParameter('tav_env')) {
            $datagridMapper->remove('cotisationajour');
        }
Julien Jorry committed
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 584
    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
585 586 587
    public function getFullTextFilter($queryBuilder, $alias, $field, $value)
    {
        if (!$value['value']) {
588
            return false;
Julien Jorry committed
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
        }

        // 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'])
641 642
        ;

643 644 645 646 647
        if ($this->security->isGranted('ROLE_TRESORIER')) {
            $actions = [];
        } else {
            $actions = ['edit' => []];
        }
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
        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',
                    ]
                );
668 669 670 671 672 673 674 675
            if(
                $this->getConfigurationPool()->getContainer()->getParameter('household_based_allowance')
                && (
                    $this->security->isGranted('ROLE_SUPER_ADMIN') 
                    || $this->security->isGranted('ROLE_ADMIN_SIEGE')
                    || $this->security->isGranted('ROLE_TRESORIER')
                )
            ) {
676 677 678 679 680 681 682 683 684 685 686 687 688
                $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'
                ];
            }
689 690 691
        }

        $listMapper
Julien Jorry committed
692 693 694 695 696 697 698 699 700 701
            ->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,
            ])
702 703 704 705 706 707 708 709 710
            ->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, [
711
                'actions' => $actions,
712
            ])
Julien Jorry committed
713 714 715 716 717 718
        ;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        parent::configureRoutes($collection);
719 720 721
        $collection
            ->remove('delete')
            ->add('withdrawDownToTheCeiling', $this->getRouterIdParameter() . '/withdrawDownToTheCeiling');
Julien Jorry committed
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
    }

    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',
743 744
            'Crée le' => 'createdAt',
            'Mise à jour le' => 'updatedAt',
Julien Jorry committed
745 746
        ];
    }
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776

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

777
        $query->select('DISTINCT ' . current($query->getRootAliases()));
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
        $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();
            }
        }

793 794 795
        $container = $this->getConfigurationPool()->getContainer();
        $em = $container->get('doctrine')->getManager();
        $cotisationUtils = $container->get('app.utils.cotisations');
796

797
        $iterator = new CustomDoctrineORMQuerySourceIterator($cotisationUtils, $em, $container, $query, $fields);
798 799 800 801
        $iterator->setDateTimeFormat('d/m/Y H:i:s'); //change this to suit your needs

        return $iterator;
    }
802 803 804 805 806 807 808 809 810

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