AdherentAdmin.php 15.6 KB
Newer Older
Julien Jorry committed
1 2 3 4
<?php

namespace App\Admin;

5
use App\Entity\Adherent;
6
use App\Entity\Cotisation;
7
use App\Entity\Geoloc;
8
use App\Entity\Groupe;
9
use App\Entity\User;
10
use App\Entity\Usergroup;
11
use App\Enum\MoyenEnum;
Julien Jorry committed
12 13
use App\Form\Type\UserFormType;
use App\Form\Type\GeolocFormType;
14 15 16
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\FOSUserEvents;
use Knp\Menu\ItemInterface as MenuItemInterface;
Julien Jorry committed
17 18
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\AdminInterface;
19
use Sonata\AdminBundle\Datagrid\DatagridMapper;
Julien Jorry committed
20 21
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
Julien Jorry committed
22
use Sonata\AdminBundle\Route\RouteCollection;
Julien Jorry committed
23
use Sonata\DoctrineORMAdminBundle\Filter\CallbackFilter;
24
use Sonata\UserBundle\Model\UserManagerInterface;
Julien Jorry committed
25
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
26 27 28
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
Julien Jorry committed
29
use Symfony\Component\Form\Extension\Core\Type\TextType;
30
use Symfony\Component\Form\FormError;
Julien Jorry committed
31 32
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
33
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
34
use Symfony\Component\Security\Core\Security;
35
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
Julien Jorry committed
36

37 38 39
/**
 * Administration des adhérents
 *
Julien Jorry committed
40
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
41 42
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
43
class AdherentAdmin extends AbstractAdmin
Julien Jorry committed
44
{
Julien Jorry committed
45 46
    protected $baseRouteName = 'adherent';
    protected $baseRoutePattern = 'adherent';
47
    protected $security;
Julien Jorry committed
48

49 50
    protected $datagridValues = [
        // reverse order (default = 'ASC')
51
        '_sort_order' => 'DESC',
52
        // name of the ordered field (default = the model's id field, if any)
53
        '_sort_by' => 'updatedAt',
54 55 56 57
        // '_page' => 1,
        // '_per_page' => 32
    ];

58
    public function setSecurity(Security $security)
59
    {
60
        $this->security = $security;
61 62
    }

Julien Jorry committed
63 64 65 66 67
    public function configure()
    {
        parent::configure();
    }

68 69 70 71 72
    /**
    * {@inheritdoc}
    */
    public function createQuery($context = 'list')
    {
73
        $user = $this->security->getUser();
74 75 76 77 78
        $query = parent::createQuery($context);
        $query
            ->innerJoin($query->getRootAliases()[0] .'.user', 'u')
            ->addSelect('u')
        ;
Julien Jorry committed
79 80
        if (empty($this->getRequest()->getSession()->get('_groupegere'))) {
            if ($user->isGranted('ROLE_GESTION_GROUPE') || $user->isGranted('ROLE_CONTACT')) {
81 82
                $query->andWhere('false');
            }
Julien Jorry committed
83 84 85 86 87
        } else {
            $query
                ->andWhere($query->getRootAliases()[0].'.groupe = :groupe')
                ->setParameter('groupe', $this->getRequest()->getSession()->get('_groupegere'))
            ;
88 89 90 91
        }
        return $query;
    }

92 93 94 95 96 97 98 99 100 101 102
    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(array('adherent' => $id));

        if ($this->isGranted('EDIT') && $user != null) {
103
            $menu->addChild("Modifier l'utilisateur", [
104 105 106
                'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('admin_app_user_edit', ['id' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL)
            ]);
        }
107 108 109 110 111 112
        $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' => array('expediteur' => array('value' => $id))], UrlGeneratorInterface::ABSOLUTE_URL)
        ]);
113 114
    }

Julien Jorry committed
115 116 117 118 119
    /**
    * {@inheritdoc}
    */
    protected function configureFormFields(FormMapper $formMapper): void
    {
120
        // Initialize adherent
121 122
        $adherent = $this->getSubject();
        $now = new \DateTime();
123 124 125 126 127 128 129 130 131 132
        if ($this->isCurrentRoute('create')) {
            $user = $this->userManager->createUser();
            $groupe = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Adherent');
            $user->setEnabled(true);
            $user->addGroup($groupe);
            $user->addRole('ROLE_ADHERENT');
            $adherent->setEcompte('0');
            $user->setAdherent($adherent);
            $adherent->setUser($user);
        }
133 134 135 136 137 138 139 140
        // if (count($adherent->getUser()->getCotisations()) <= 0) {
        //     $cotisation = new Cotisation();
        //     $cotisation->setOperateur($adherent->getUser());
        //     $cotisation->setExpediteur($adherent);
        //     $cotisation->setDebut($now);
        //     $cotisation->setFin(new \DateTime('+ 1 year'));
        //     $adherent->getUser()->addCotisation($cotisation);
        // }
141 142 143
        if ($adherent->getGeoloc() == null) {
            $adherent->setGeoloc(new Geoloc());
        }
144 145 146 147
        //nom, prénom, adresse, tel, mail et cotisation en une seule fois et générer un mdp
        $formMapper
            ->tab('General')
                ->with('Identité', ['class' => 'col-md-7'])
Julien Jorry committed
148 149
                    ->add('user', UserFormType::class, array(
                        'label' => false
150
                    ))
Julien Jorry committed
151
                ->end()
Julien Jorry committed
152
                ->with('Adresse', ['class' => 'col-md-5'])
Julien Jorry committed
153 154
                    ->add('geoloc', GeolocFormType::class, array(
                        'label' => false,
155
                        'required' => false
156
                    ))
Julien Jorry committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
                ->end()
            ->end()
        ;
        // ->with('Identité', ['class' => 'col-md-7'])
        //     ->add('user.firstname', TextType::class, array(
        //         'label' => 'Prénom :',
        //         'required' => true
        //     ))
        //     ->add('user.lastname', TextType::class, array(
        //         'label' => 'Nom :',
        //         'required' => true
        //     ));
        // if (!$this->isCurrentRoute('create')) {
        //     $formMapper
        //         ->add('user.username', TextType::class, array(
        //             'label' => 'Username :',
        //             'required' => true,
        //             'disabled' => true
        //         ));
        // }
        // $formMapper
        //             ->add('user.phone', TextType::class, array(
        //                 'label' => 'Téléphone :',
        //                 'required' => false
        //             ))
        //             ->add('user.email', TextType::class, array(
        //                 'label' => 'Email :',
        //                 'required' => true
        //             ))
        //             ->add('groupe', ChoiceType::class, array(
        //                 'required' => true,
        //                 'label' => 'Groupe local :',
        //                 'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Groupe::class)->findAll(),
        //                 'choice_label' => 'name',
        //                 'placeholder' => 'Choisir un groupe',
        //             ))
        //         ->end();
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
        //         ->with('Cotisation', ['class' => 'col-md-5'])
        //         //@TODO : géré une ou plusieurs cotisations
        //             ->add('user.cotisations.first.cotisationInfos.annee', TextType::class, array('label' => 'Année', 'data' => $now->format('Y')))
        //             ->add('user.cotisations.first.montant', TextType::class, array('label' => 'Montant'))
        //             ->add('user.cotisations.first.moyen', ChoiceType::class, array(
        //                 'required' => true,
        //                 'label' => 'Moyen :',
        //                 'choices' => MoyenEnum::getAvailableTypes(),
        //                 'choice_label' => function ($choice) {
        //                     return MoyenEnum::getTypeName($choice);
        //                 },
        //             ));
        // if ($this->security->getUser()->isGranted('ROLE_TRESORIER')) {
        //     $formMapper
        //         ->add('user.cotisations.first.cotisationInfos.recu', CheckboxType::class, array('label' => 'Reçu'));
        // }
        // $formMapper->end();
        // if (!$this->isCurrentRoute('create')) {
        //     $formMapper
        //         ->with('Date', ['class' => 'col-md-5'])
        //             ->add('user.cotisations.first.cotisationInfos.debut', DateType::class, array(
        //                 'label' => 'Date de début',
        //                 'data' => new \DateTime(),
        //                 'widget' => 'single_text',
        //                 'html5' => false,
        //                 'attr' => ['class' => 'js-datepicker'],
        //             ))
        //             ->add('user.cotisations.first.cotisationInfos.fin', DateType::class, array(
        //                 'label' => 'Date de fin',
        //                 'data' => new \DateTime('+ 1 year'),
        //                 'widget' => 'single_text',
        //                 'html5' => false,
        //                 'attr' => ['class' => 'js-datepicker'],
        //             ))
        //         ->end();
        // }
Julien Jorry committed
230

231 232 233 234 235 236 237 238 239 240 241 242 243 244
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $formMapper->getFormBuilder()->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($em) {
            $adherent = $event->getData();
            $user = $adherent->getUser();
            if (!$user || null === $user->getId()) {
                $repo = $em->getRepository(User::class);
                $emailExist = $repo->findBy(array('email' => $user->getEmail()));
                if (count($emailExist) > 0) {
                    $event->getForm()->get('user__email')->addError(new FormError('Courriel déjà utilisé !'));
                } else {
                    $user->setUsername($user->getEmail());
                }
            }
        });
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        parent::configureFormFields($formMapper);
    }

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

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

        if (empty($adherent->getUser()->getUsername())) {
            $adherent->getUser()->setUsername($adherent->getUser()->getEmail());
        }
        if (empty($adherent->getUser()->getPassword())) {
            // $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);
266
            // @TODO : send email to user
267 268 269 270 271 272
        }
        $this->userManager->updateUser($adherent->getUser());
        $adherent->getUser()->createEmailToken();
        $em->persist($adherent->getUser());
        $em->persist($adherent);
        $em->flush();
273
        // @TODO : envoyer un mail au nouvel utilisateur avec l'emailtoken via le dispatch d'un event
274
        // $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($adherent->getUser(), $this->getRequest(), $response));
275 276 277 278 279 280 281
    }

    /**
    * {@inheritdoc}
    */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
282
        $datagridMapper
Julien Jorry committed
283 284 285 286 287 288 289 290 291 292 293 294 295
            ->add('full_text', CallbackFilter::class, [
                'callback' => [$this, 'getFullTextFilter'],
                'field_type' => TextType::class,
                'label' => "Recherche par nom",
                'show_filter' => true,
                'advanced_filter' => false
            ])
            ->add('groupe', null, [
                'label' => "Groupe",
                'show_filter' => true,
                'advanced_filter' => false
            ])
            ->add('user.email', null, [
Julien Jorry committed
296 297
                'label' => "Email",
                'advanced_filter' => false
Julien Jorry committed
298
            ])
299 300 301
        ;
    }

Julien Jorry committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
    public function getFullTextFilter($queryBuilder, $alias, $field, $value)
    {
        if (!$value['value']) {
            return;
        }

        // Use `andWhere` instead of `where` to prevent overriding existing `where` conditions
        $queryBuilder->andWhere($queryBuilder->expr()->orX(
            $queryBuilder->expr()->like('u.username', $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;
    }

318 319 320 321 322 323 324 325 326 327 328 329 330 331
    /**
     * @param EventDispatcherInterface $userManager
     */
    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * @return EventDispatcherInterface
     */
    public function getEventDispatcher()
    {
        return $this->eventDispatcher;
Julien Jorry committed
332 333
    }

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
    /**
     * @param UserManagerInterface $userManager
     */
    public function setUserManager(UserManagerInterface $userManager): void
    {
        $this->userManager = $userManager;
    }

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

Julien Jorry committed
350 351
    protected function configureListFields(ListMapper $listMapper): void
    {
Julien Jorry committed
352 353
        unset($this->listModes['mosaic']);
        $listMapper
354 355 356
            ->addIdentifier('user.username', null, array('label' => 'Login'))
            ->addIdentifier('user.email', null, array('label' => 'Email'))
            ->addIdentifier('ecompte', null, array('label' => 'Ecompte'))
357 358 359 360 361 362
            ->addIdentifier('groupe', null, array(
                'label' => 'Groupe',
                'sortable' => true,
                'sort_field_mapping' => array('fieldName' => 'name'),
                'sort_parent_association_mappings' => array(array('fieldName' => 'groupe'))
            ))
363
            ->addIdentifier('user.enabled', null, array('label' => 'Activé', 'datatype' => 'App.User', 'template' => '@SonataAdmin/Boolean/editable_boolean.html.twig'))
364
            ->addIdentifier('user.updatedAt', null, array('label' => 'Mis à jour'))
Julien Jorry committed
365 366 367 368 369
        ;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
370
        parent::configureRoutes($collection);
371
        $collection->remove('delete');
Julien Jorry committed
372 373
    }

374 375 376 377 378 379 380
    public function getBatchActions()
    {
        $actions = parent::getBatchActions();
        unset($actions['delete']);

        return $actions;
    }
Julien Jorry committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395

    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',
            'E-compte'               => 'ecompte'
        ];
    }
Julien Jorry committed
396
}