AdherentAdmin.php 37.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;
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;
52
use Ramsey\Uuid\Uuid;
Julien Jorry committed
53 54 55 56 57 58 59 60 61 62 63 64 65

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

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

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

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

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

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

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

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

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

196
        if ($tav_env) {
197 198 199 200 201 202
            if ($this->getConfigurationPool()->getContainer()->getParameter('ccas_mode')) {
                $formMapper
                    ->tab('General')
                        ->with('Identité')
                            ->add('ccasAccepted', null, [
                                'label' => 'A pris connaissance et accepté la procédure des aides facultatives CCAS',
203
                                'attr' => ['autocomplete' => 'off']
204 205 206
                            ])
                            ->add('ccasEligible', null, [
                                'label' => 'Éligible aux aides facultatives CCAS',
207
                                'attr' => ['autocomplete' => 'off']
208 209 210 211 212 213 214 215 216 217 218
                            ])
                        ->end()
                    ->end()
                ;
            }

            /**
             * In TAV env, 2 allowance processes possible:
             * - household based (if param set)
             * - cotisation profile and rate based (default)
             */
219
            if ($household_based_allowance) {
220 221 222
                $formMapper
                    ->tab('General')
                        ->with('Foyer', ['class' => 'col-md-7'])
223 224 225 226 227 228 229 230 231 232 233 234
                            ->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",
                            ])
235 236 237 238 239 240 241 242 243 244
                            ->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
                                ]
                            ])
245 246
                            ->add('dependentChildren', CollectionType::class, [
                                'entry_type' => DependentChildFormType::class,
247 248 249 250 251
                                'entry_options' => [
                                    'label' => true,
                                    'data_class' => DependentChild::class,
                                    'attr' => ['class' => 'border pl-3 pr-3 pt-2']
                                ],
252 253 254
                                'allow_add' => true,
                                'allow_delete' => true,
                                'by_reference' => false,
255
                                'label' => "Enfant(s) à charge (pour calculer l'allocation)"
256 257 258
                            ])
                        ->end()
                    ->end();
259

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
                // 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();
                }
    
314
                $formMapper
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 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
                    ->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();
361
            }
Félicie committed
362 363
    
            if (!empty($adherent) && !empty($adherent->getEmlcAccount()) ) {
Félicie committed
364
                $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
Félicie committed
365
                $balance = $adherent->getEmlcAccount()->getBalance();
Félicie committed
366
                $mlc = $em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_SYMBOL);
Félicie committed
367 368
                $formMapper
                    ->tab('General')
369
                        ->with('Informations de cotisation')
Félicie committed
370 371
                            ->add('idmlc', TextType::class, [
                                'disabled' => true,
372
                                'required' => false,
Félicie committed
373
                                'label' => 'Solde e-' . $mlc . ' :',
374 375 376 377
                                'data' => $balance . ' ' . $mlc,
                                'attr' => [
                                    'autocomplete' => 'off'
                                ]
378
                            ])
Félicie committed
379 380
                        ->end()
                    ->end();
381 382 383 384 385 386 387 388 389 390 391
                //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' => [
392 393
                                        'autocomplete' => 'off',
                                        'class' => 'fixBalanceAdherentFormPart'
394 395 396 397 398 399
                                    ]
                                ])
                                ->add('justification', TextType::class, [
                                    'mapped' => false,
                                    'required' => false,
                                    'attr' => [
400 401
                                        'autocomplete' => 'off',
                                        'class' => 'fixBalanceAdherentFormPart'
402 403 404 405 406 407 408 409
                                    ]
                                ])
                                ->add('password', PasswordType::class, [
                                    'label' => 'Mot de passe pour corriger le solde',
                                    'mapped' => false,
                                    'required' => false,
                                    'data' => "",
                                    'attr' => [
410 411
                                        'autocomplete' => 'off',
                                        'class' => 'fixBalanceAdherentFormPart'
412 413 414 415 416
                                    ]
                                ])
                            ->end()
                        ->end();
                }
Félicie committed
417
            }
418 419
        }

Julien Jorry committed
420 421 422
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $formMapper->getFormBuilder()->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($em) {
            $adherent = $event->getData();
423 424

            // Check user email
Julien Jorry committed
425 426 427 428 429 430 431 432 433 434
            $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());
                }
            }
435 436

            if ($this->getConfigurationPool()->getContainer()->getParameter('household_based_allowance')) {
437
                // check cotisation amount
438 439 440 441 442 443 444
                $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)'));
                }
445 446 447 448 449 450

                // 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) {
451
                    $password = $this->getConfigurationPool()->getContainer()->getParameter('fix_balance_adherent_password');
452 453 454 455 456 457 458 459 460 461 462 463 464
                    //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();
                    }
                }
465
            }
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491

            if ($this->getConfigurationPool()->getContainer()->getParameter('ccas_mode')) {
                // generate anonymous token if doesn't exist, if ccasAccepted and ccasEligible
                if (
                    is_null($adherent->getAnonymousToken()) 
                    && $adherent->getCcasEligible() 
                    && $adherent->getCcasAccepted()
                ) {
                    $uuid = Uuid::uuid4()->toString();

                    // Get 8 first digits of uuid so unique code is readable for manual treatment
                    $uniqueCode = substr($uuid, 0, 8);

                    // 8 first digits of uuid isn't assured to be unique, so perform a unicity check before saving
                    $codeExists = $em->getRepository(Adherent::class)->findOneBy(['anonymousToken' => $uniqueCode]);
                    while (!is_null($codeExists)) {
                        $uuid = Uuid::uuid4()->toString();
                        $uniqueCode = substr($uuid, 0, 8);
                        $codeExists = $em->getRepository(Adherent::class)->findOneBy(['anonymousToken' => $uniqueCode]);
                    }
                    
                    $adherent->setAnonymousToken($uniqueCode);
                    $em->persist($adherent);
                    $em->flush();
                }
            }
Julien Jorry committed
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
        });
        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);
        }
522
        $this->userManager->updateCanonicalFields($adherent->getUser());
Julien Jorry committed
523 524 525 526 527 528 529 530 531 532 533
        $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);
        }

534 535 536
        if ($this->getConfigurationPool()->getContainer()->getParameter('household_based_allowance')) {
            $this->tavCotisationUtils->calculateAllowanceAccordingToHousehold($adherent);
        }
537 538 539 540

        $em->persist($adherent->getUser());
        $em->persist($adherent);
        $em->flush();
541 542
    }

Julien Jorry committed
543 544 545 546 547 548 549 550 551 552 553 554 555
    /**
     * {@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,
            ])
556 557 558 559 560 561 562 563 564 565 566 567 568 569
            ->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
570 571 572 573 574
            ->add('groupe', null, [
                'label' => 'Groupe',
                'show_filter' => true,
                'advanced_filter' => false,
            ])
575
            ->add('createdAt', 'doctrine_orm_datetime_range', [
576 577
                'field_type' => DateTimeRangePickerType::class,
                'label' => 'Date de création',
578 579
            ])
            ->add('updatedAt', 'doctrine_orm_datetime_range', [
580 581
                'field_type' => DateTimeRangePickerType::class,
                'label' => 'Date de mise à jour',
582
            ])
Julien Jorry committed
583
        ;
584 585

        if ($this->getConfigurationPool()->getContainer()->getParameter('tav_env')) {
586 587 588 589 590 591 592 593 594 595 596 597
            $datagridMapper
                ->remove('cotisationajour');
            if ($this->getConfigurationPool()->getContainer()->getParameter('ccas_mode')) {
                $datagridMapper
                    ->add('anonymoustoken', CallbackFilter::class, [
                        'callback' => [$this, 'getAnynomousTokenFilter'],
                        'field_type' => CheckboxType::class,
                        'label' => 'Avec numéro d\'anonymisation',
                        'show_filter' => true,
                        'advanced_filter' => false,
                    ]);
            }
598
        }
Julien Jorry committed
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
    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
640 641 642
    public function getFullTextFilter($queryBuilder, $alias, $field, $value)
    {
        if (!$value['value']) {
643
            return false;
Julien Jorry committed
644 645 646 647 648 649 650 651 652 653 654 655 656
        }

        // 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;
    }

657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
    public function getAnynomousTokenFilter($queryBuilder, $alias, $field, $value)
    {
        if (!$value['value']) {
            return false;
        }

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

        // Use `andWhere` instead of `where` to prevent overriding existing `where` conditions
        if ($value["value"]) {
            $queryBuilder->andWhere(
                '(' . $alias . '.anonymousToken is not null and ' . $alias . '.anonymousToken != false)'
            );
        }

        return true;
    }

Julien Jorry committed
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
    /**
     * @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'])
716 717
        ;

718 719 720 721 722
        if ($this->security->isGranted('ROLE_TRESORIER')) {
            $actions = [];
        } else {
            $actions = ['edit' => []];
        }
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
        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',
                    ]
                );
743 744 745 746 747 748 749 750
            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')
                )
            ) {
751 752 753 754 755 756 757 758 759 760 761 762 763
                $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'
                ];
            }
764 765 766
        }

        $listMapper
Julien Jorry committed
767 768 769 770 771 772 773 774 775 776
            ->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,
            ])
777 778 779 780 781 782 783 784 785
            ->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, [
786
                'actions' => $actions,
787
            ])
Julien Jorry committed
788 789 790 791 792 793
        ;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        parent::configureRoutes($collection);
794 795 796
        $collection
            ->remove('delete')
            ->add('withdrawDownToTheCeiling', $this->getRouterIdParameter() . '/withdrawDownToTheCeiling');
Julien Jorry committed
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
    }

    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',
818 819
            'Crée le' => 'createdAt',
            'Mise à jour le' => 'updatedAt',
Julien Jorry committed
820 821
        ];
    }
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851

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

852
        $query->select('DISTINCT ' . current($query->getRootAliases()));
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
        $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();
            }
        }

868 869 870
        $container = $this->getConfigurationPool()->getContainer();
        $em = $container->get('doctrine')->getManager();
        $cotisationUtils = $container->get('app.utils.cotisations');
871

872
        $iterator = new CustomDoctrineORMQuerySourceIterator($cotisationUtils, $em, $container, $query, $fields);
873 874 875 876
        $iterator->setDateTimeFormat('d/m/Y H:i:s'); //change this to suit your needs

        return $iterator;
    }
877 878 879 880 881 882 883 884 885

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