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

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

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

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

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

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

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

Julien Jorry committed
116 117 118 119 120
    /**
    * {@inheritdoc}
    */
    protected function configureFormFields(FormMapper $formMapper): void
    {
121
        // Initialize adherent
122 123
        $adherent = $this->getSubject();
        $now = new \DateTime();
124 125 126 127
        if ($this->isCurrentRoute('create')) {
            $user = $this->userManager->createUser();
            $groupe = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Adherent');
            $user->setEnabled(true);
128 129
            $user->addPossiblegroup($groupe);
            $user->setGroups([$groupe]);
130 131 132 133 134 135 136 137
            $user->addRole('ROLE_ADHERENT');
            $adherent->setEcompte('0');
            $user->setAdherent($adherent);
            $adherent->setUser($user);
        }
        if ($adherent->getGeoloc() == null) {
            $adherent->setGeoloc(new Geoloc());
        }
138 139 140
        $formMapper
            ->tab('General')
                ->with('Identité', ['class' => 'col-md-7'])
Julien Jorry committed
141 142
                    ->add('user', UserFormType::class, array(
                        'label' => false
143
                    ))
Julien Jorry committed
144
                ->end()
Julien Jorry committed
145
                ->with('Adresse', ['class' => 'col-md-5'])
Julien Jorry committed
146 147
                    ->add('geoloc', GeolocFormType::class, array(
                        'label' => false,
148 149 150
                        'required' => true,
                        'with_geoloc' => false,
                        'with_latlon' => false
151
                    ))
Julien Jorry committed
152 153 154 155
                ->end()
            ->end()
        ;

156 157 158 159 160 161 162 163
        $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) {
164
                    $event->getForm()->get('user')->get('email')->addError(new FormError('Courriel déjà utilisé !'));
165 166 167 168 169
                } else {
                    $user->setUsername($user->getEmail());
                }
            }
        });
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        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())) {
186
            // @TODO : generate password with tokengenerator
187 188 189 190 191 192 193 194 195 196 197
            // $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);
        }
        $this->userManager->updateUser($adherent->getUser());
        $adherent->getUser()->createEmailToken();
        $em->persist($adherent->getUser());
        $em->persist($adherent);
        $em->flush();
198
        $this->eventDispatcher->dispatch(MLCEvents::REGISTRATION_ADHERENT, new UserEvent($adherent->getUser(), $this->getRequest()));
199 200 201 202 203 204 205
    }

    /**
    * {@inheritdoc}
    */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
206
        $datagridMapper
Julien Jorry committed
207 208 209 210 211 212 213 214 215 216 217 218 219
            ->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
220 221
                'label' => "Email",
                'advanced_filter' => false
Julien Jorry committed
222
            ])
223 224 225
        ;
    }

Julien Jorry committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    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;
    }

242 243 244 245 246 247 248 249 250 251 252 253 254 255
    /**
     * @param EventDispatcherInterface $userManager
     */
    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
    {
        $this->eventDispatcher = $eventDispatcher;
    }

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

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    /**
     * @param UserManagerInterface $userManager
     */
    public function setUserManager(UserManagerInterface $userManager): void
    {
        $this->userManager = $userManager;
    }

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

Julien Jorry committed
274 275
    protected function configureListFields(ListMapper $listMapper): void
    {
Julien Jorry committed
276 277
        unset($this->listModes['mosaic']);
        $listMapper
278 279 280
            ->addIdentifier('user.username', null, array('label' => 'Login'))
            ->addIdentifier('user.email', null, array('label' => 'Email'))
            ->addIdentifier('ecompte', null, array('label' => 'Ecompte'))
281 282 283 284 285 286
            ->addIdentifier('groupe', null, array(
                'label' => 'Groupe',
                'sortable' => true,
                'sort_field_mapping' => array('fieldName' => 'name'),
                'sort_parent_association_mappings' => array(array('fieldName' => 'groupe'))
            ))
287 288 289 290
            ->add('user.enabled', null, array(
                'label' => 'Activé',
                'editable' => true
            ))
291
            ->addIdentifier('user.updatedAt', null, array('label' => 'Mis à jour'))
Julien Jorry committed
292 293 294 295 296
        ;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
297
        parent::configureRoutes($collection);
298
        $collection->remove('delete');
Julien Jorry committed
299 300
    }

301 302 303 304 305 306 307
    public function getBatchActions()
    {
        $actions = parent::getBatchActions();
        unset($actions['delete']);

        return $actions;
    }
Julien Jorry committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

    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
323
}