AdherentAdmin.php 13.9 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 12 13 14
use App\Enum\MoyenEnum;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\FOSUserEvents;
use Knp\Menu\ItemInterface as MenuItemInterface;
Julien Jorry committed
15 16
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\AdminInterface;
17
use Sonata\AdminBundle\Datagrid\DatagridMapper;
Julien Jorry committed
18 19
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
Julien Jorry committed
20
use Sonata\AdminBundle\Route\RouteCollection;
21
use Sonata\UserBundle\Model\UserManagerInterface;
Julien Jorry committed
22
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
23 24 25
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
26
use Symfony\Component\Form\Extension\Core\Type\TextType;
27
use Symfony\Component\Form\FormError;
Julien Jorry committed
28 29
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
30
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
31
use Symfony\Component\Security\Core\Security;
Julien Jorry committed
32

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

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

54
    public function setSecurity(Security $security)
55
    {
56
        $this->security = $security;
57 58
    }

Julien Jorry committed
59 60 61 62 63
    public function configure()
    {
        parent::configure();
    }

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

89 90 91 92 93 94 95 96 97 98 99
    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) {
100
            $menu->addChild("Modifier l'utilisateur", [
101 102 103
                'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('admin_app_user_edit', ['id' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL)
            ]);
        }
104 105 106 107 108 109
        $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)
        ]);
110 111
    }

Julien Jorry committed
112 113 114 115 116
    /**
    * {@inheritdoc}
    */
    protected function configureFormFields(FormMapper $formMapper): void
    {
117
        // Initialize adherent
118 119
        $adherent = $this->getSubject();
        $now = new \DateTime();
120 121 122 123 124 125 126 127 128 129
        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);
        }
130 131 132 133 134 135 136 137
        // 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);
        // }
138 139 140
        if ($adherent->getGeoloc() == null) {
            $adherent->setGeoloc(new Geoloc());
        }
141 142 143 144 145 146 147 148 149 150 151
        //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'])
                    ->add('user.firstname', TextType::class, array(
                        'label' => 'Prénom :',
                        'required' => true
                    ))
                    ->add('user.lastname', TextType::class, array(
                        'label' => 'Nom :',
                        'required' => true
152 153 154 155 156 157 158 159 160 161
                    ));
        if (!$this->isCurrentRoute('create')) {
            $formMapper
                ->add('user.username', TextType::class, array(
                    'label' => 'Username :',
                    'required' => true,
                    'disabled' => true
                ));
        }
                $formMapper
162 163
                    ->add('user.phone', TextType::class, array(
                        'label' => 'Téléphone :',
164
                        'required' => false
165 166 167 168 169
                    ))
                    ->add('user.email', TextType::class, array(
                        'label' => 'Email :',
                        'required' => true
                    ))
170 171 172 173 174 175 176 177
                    ->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();
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
        //         ->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();
        // }
214
            $formMapper
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
                ->with('Addresse', ['class' => 'col-md-7'])
                    ->add('geoloc.adresse', TextType::class, array(
                        'label' => 'Addresse :',
                        'required' => true
                    ))
                    ->add('geoloc.cpostal', TextType::class, array(
                        'label' => 'Code postal :',
                        'required' => true
                    ))
                    ->add('geoloc.ville', TextType::class, array(
                        'label' => 'Ville :',
                        'required' => true
                    ))
                ->end()
            ->end()
        ;
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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        $datagridMapper
            ->add('user.username', null, array('label' => 'Login'))
            ->add('user.email', null, array('label' => 'Email'))
        ;
    }

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

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

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    /**
     * @param UserManagerInterface $userManager
     */
    public function setUserManager(UserManagerInterface $userManager): void
    {
        $this->userManager = $userManager;
    }

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

Julien Jorry committed
320 321
    protected function configureListFields(ListMapper $listMapper): void
    {
Julien Jorry committed
322 323
        unset($this->listModes['mosaic']);
        $listMapper
324 325 326
            ->addIdentifier('user.username', null, array('label' => 'Login'))
            ->addIdentifier('user.email', null, array('label' => 'Email'))
            ->addIdentifier('ecompte', null, array('label' => 'Ecompte'))
327 328 329 330 331 332
            ->addIdentifier('groupe', null, array(
                'label' => 'Groupe',
                'sortable' => true,
                'sort_field_mapping' => array('fieldName' => 'name'),
                'sort_parent_association_mappings' => array(array('fieldName' => 'groupe'))
            ))
333
            ->addIdentifier('user.enabled', null, array('label' => 'Activé', 'datatype' => 'App.User', 'template' => '@SonataAdmin/Boolean/editable_boolean.html.twig'))
334
            ->addIdentifier('user.updatedAt', null, array('label' => 'Mis à jour'))
Julien Jorry committed
335 336 337 338 339
        ;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
340
        parent::configureRoutes($collection);
341
        $collection->remove('delete');
Julien Jorry committed
342 343
    }

344 345 346 347 348 349 350
    public function getBatchActions()
    {
        $actions = parent::getBatchActions();
        unset($actions['delete']);

        return $actions;
    }
Julien Jorry committed
351
}