UserAdmin.php 15.5 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php

declare(strict_types=1);

/*
 * This file is part of the Sonata Project package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Application\Sonata\UserBundle\Admin;

use App\Entity\Adherent;
use App\Entity\Geoloc;
use App\Entity\Groupe;
19 20
use App\Events\MLCEvents;
use FOS\UserBundle\Event\UserEvent;
Julien Jorry committed
21 22 23 24 25 26 27
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Form\Type\ModelType;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\CoreBundle\Form\Type\DatePickerType;
28
use Sonata\Form\Type\DateTimeRangePickerType;
Julien Jorry committed
29 30 31
use Sonata\UserBundle\Admin\Model\UserAdmin as BaseUserAdmin;
use Sonata\UserBundle\Form\Type\SecurityRolesType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
32
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
Julien Jorry committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
use Symfony\Component\Form\Extension\Core\Type\LocaleType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TimezoneType;
use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\Form\FormTypeInterface;

class UserAdmin extends BaseUserAdmin
{
    public function configure()
    {
        parent::configure();
        $this->setTemplate('edit', '@kohinos/bundles/SonataAdminBundle/base_edit.html.twig');
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        if ($this->isChild()) {
            $collection->remove('delete');

            return;
        }

        // This is the route configuration as a parent
        $collection->remove('delete');
    }

    /**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $listMapper): void
    {
        $listMapper
            ->addIdentifier('username')
            ->add('email')
            ->add('possiblegroups', null, [
                'label' => 'Rôles',
            ])
            ->add('enabled', null, [
                'label' => 'Activé',
                'editable' => true,
            ])
            ->add('createdAt')
77
            ->add('lastLogin')
Julien Jorry committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
            ->add('_action', null, [
                'label' => 'Actions',
                'actions' => [
                    'edit' => [],
                ],
            ])
        ;

        if ('dev' == $_ENV['APP_ENV'] && $this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
            $listMapper
                ->add('impersonating', 'string', ['template' => '@SonataUser/Admin/Field/impersonating.html.twig'])
            ;
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function configureDatagridFilters(DatagridMapper $filterMapper): void
    {
        $filterMapper
            ->add('id')
            ->add('username')
            ->add('email')
            ->add('groups')
103 104 105 106 107 108 109 110
            ->add('createdAt', 'doctrine_orm_datetime_range', [
                'field_type'=> DateTimeRangePickerType::class,
                'label' => 'Date de création'
            ])
            ->add('lastLogin', 'doctrine_orm_datetime_range', [
                'field_type'=> DateTimeRangePickerType::class,
                'label' => 'Date de dernière connexion'
            ])
Julien Jorry committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureShowFields(ShowMapper $showMapper): void
    {
        $showMapper
            ->with('General')
                ->add('username')
                ->add('email')
            ->end()
            ->with('Groups')
                ->add('possiblegroups')
            ->end()
            ->with('Profile')
                // ->add('dateOfBirth')
                ->add('firstname')
                ->add('lastname')
                // ->add('website')
                // ->add('biography')
                // ->add('gender')
                // ->add('locale')
                // ->add('timezone')
                ->add('phone')
            ->end()
            // ->with('Social')
            //     ->add('facebookUid')
            //     ->add('facebookName')
            //     ->add('twitterUid')
            //     ->add('twitterName')
            //     ->add('gplusUid')
            //     ->add('gplusName')
            // ->end()
            // ->with('Security')
            //     ->add('token')
            //     ->add('twoStepVerificationCode')
            // ->end()
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper): void
    {
        $subject = $this->getSubject();
        // define group zoning
        $formMapper
            ->tab('User')
                ->with('Profile', ['class' => 'col-md-6'])->end()
                ->with('General', ['class' => 'col-md-6'])->end()
                // ->with('Social', ['class' => 'col-md-6'])->end()
            ->end();
        if (($this->isGranted('ROLE_SUPER_ADMIN') || $this->isGranted('ROLE_ADMIN_SIEGE'))) {
            $formMapper
                ->tab('Security')
                ->with('Groups', ['class' => 'col-md-8'])->end()
                ->with('Status', ['class' => 'col-md-4'])->end()
                // ->with('Keys', ['class' => 'col-md-4'])->end()
                // ->with('Roles', ['class' => 'col-md-12'])->end()
                ->end()
            ;
        }

        $now = new \DateTime();

        $genderOptions = [
            'choices' => call_user_func([$this->getUserManager()->getClass(), 'getGenderList']),
            'required' => true,
            'translation_domain' => $this->getTranslationDomain(),
        ];

        // w: Remove this when dropping support for SF 2.8
        if (method_exists(FormTypeInterface::class, 'setDefaultOptions')) {
            $genderOptions['choices_as_values'] = true;
        }

        // $formMapper->removeGroup('Social');
        $formMapper
            ->tab('User')
                ->with('General')
                    ->add('username')
                    ->add('email')
        ;
        if ('dev' == $_ENV['APP_ENV'] && $this->isGranted('ROLE_SUPER_ADMIN')) {
            $formMapper
                ->add('plainPassword', RepeatedType::class, array(
                    'type' => PasswordType::class,
                    'options' => array('translation_domain' => 'FOSUserBundle'),
                    'first_options' => array('label' => 'form.password'),
                    'second_options' => array('label' => 'form.password_confirmation'),
                    'translation_domain' => 'FOSUserBundle',
                    'invalid_message' => 'fos_user.password.mismatch',
                    'required' => (!$this->getSubject() || null === $this->getSubject()->getId()),
                ))
            ;
209 210 211 212 213 214 215 216
        } else {
            $formMapper
                ->add('plainPassword', HiddenType::class, [
                    'data' => random_bytes(10),
                    'required' => false,
                    'validation_groups' => false
                ])
            ;
Julien Jorry committed
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 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 296 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 343 344 345 346 347 348 349 350 351
        }
        $formMapper->end()
                ->with('Profile')
                    // ->add('dateOfBirth', DatePickerType::class, [
                    //     'years' => range(1900, $now->format('Y')),
                    //     'dp_min_date' => '1-1-1900',
                    //     'dp_max_date' => $now->format('c'),
                    //     'required' => false,
                    // ])
                    ->add('firstname', null, ['required' => false])
                    ->add('lastname', null, ['required' => false])
                    // ->add('website', UrlType::class, ['required' => false])
                    // ->add('biography', TextType::class, ['required' => false])
                    // ->add('gender', ChoiceType::class, $genderOptions)
                    // ->add('locale', LocaleType::class, ['required' => false])
                    // ->add('timezone', TimezoneType::class, ['required' => false])
                    ->add('phone', null, ['required' => false])
                ->end()
                // ->with('Social')
                //     ->add('facebookUid', null, ['required' => false])
                //     ->add('facebookName', null, ['required' => false])
                //     ->add('twitterUid', null, ['required' => false])
                //     ->add('twitterName', null, ['required' => false])
                //     ->add('gplusUid', null, ['required' => false])
                //     ->add('gplusName', null, ['required' => false])
                // ->end()
            ->end();

        if (($this->isGranted('ROLE_SUPER_ADMIN') || $this->isGranted('ROLE_ADMIN_SIEGE'))) {
            $formMapper
                ->tab('Security')
                    ->with('Status')
                        ->add('enabled', null, ['required' => false])
                        ->add('canValidateAchat', null, [
                            'label' => "Peut valider les demandes d'achat de e-mlc (Admin Siege ou Trésorier)",
                            'required' => false,
                        ])
                    ->end()
            ;
            $hideOrShowGroupe = ['class' => 'groupesgeres_select hide'];
            $hideOrShowComptoir = ['class' => 'comptoirsgeres_select hide'];
            $possiblegroups = $subject->getPossiblegroups();
            foreach ($possiblegroups as $group) {
                if ($group->hasRole('ROLE_GESTION_GROUPE') || $group->hasRole('ROLE_CONTACT') || $group->hasRole('ROLE_TRESORIER')) {
                    $hideOrShowGroupe = ['class' => 'groupesgeres_select'];
                }
                if ($group->hasRole('ROLE_COMPTOIR')) {
                    $hideOrShowComptoir = ['class' => 'comptoirsgeres_select'];
                }
            }
            $formMapper
                    ->with('Groups')
                        ->add('possiblegroups', ModelType::class, [
                            'label' => 'Groupes de rôles possibles',
                            'required' => false,
                            'expanded' => true,
                            'multiple' => true,
                            'attr' => ['class' => 'possible_group_cblist'],
                        ])
                        // @TODO : Si on veut voir le groupe choisit par l'utilisateur
                        // ->add('groups', null, [
                        //     'label' => 'Rôle actuel',
                        //     'required' => false,
                        //     'disabled' => true
                        // ])
                        ->add('groupesgeres', null, [
                            'required' => false,
                            'label' => 'Groupe local géré (obligatoire)',
                            'attr' => $hideOrShowGroupe,
                            'label_attr' => $hideOrShowGroupe,
                            'multiple' => true,
                            'by_reference' => false,
                        ])
                        ->add('comptoirsgeres', null, [
                            'required' => false,
                            'label' => 'Comptoir géré (obligatoire)',
                            'attr' => $hideOrShowComptoir,
                            'label_attr' => $hideOrShowComptoir,
                            'multiple' => true,
                            'by_reference' => false,
                        ])
                    ->end()
                    // ->with('Roles')
                    //     ->add('realRoles', SecurityRolesType::class, [
                    //         'label' => 'form.label_roles',
                    //         'expanded' => true,
                    //         'multiple' => true,
                    //         'required' => false,
                    //     ])
                    // ->end()
                ->end()
            ;
        }
        // ->with('Keys')
        //     ->add('token', null, ['required' => false])
        //     ->add('twoStepVerificationCode', null, ['required' => false])
        // ->end()
    }

    public function getBatchActions()
    {
        $actions = parent::getBatchActions();
        unset($actions['delete']);

        return $actions;
    }

    public function getDashboardActions()
    {
        $actions = parent::getDashboardActions();
        unset($actions['list']);

        return $actions;
    }

    public function preUpdate($user): void
    {
        parent::preUpdate($user);
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();

        /* ON EMPECHE ICI DE DESACTIVER LES ROLES SUPER ADMIN OU ADMIN SIEGE */
        if ($user->hasRole('ROLE_SUPER_ADMIN') || $user->hasRole('ROLE_ADMIN_SIEGE')) {
            if (!$user->isEnabled()) {
                $user->setEnabled(1);
                $em->persist($user);
                $em->flush();
            }
        }
    }

    public function postUpdate($user): void
    {
        $this->postPersist($user);
    }

352 353 354 355 356 357 358 359

    public function prePersist($user)
    {
        if ($user->isEnabled()) {
            $this->getConfigurationPool()->getContainer()->get('event_dispatcher')->dispatch(MLCEvents::REGISTRATION_USER, new UserEvent($user, $this->getRequest()));
        }
    }

Julien Jorry committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    public function postPersist($user): void
    {
        // On empeche d'enregistrer des comptoirs/groupes gérés si la case correspondante n'est pas cochée dans le choix des possiblegroups
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();

        $possiblegroups = $user->getPossiblegroups();

        $groupesgeres = $user->getGroupesgeres();
        $comptoirsgeres = $user->getComptoirsgeres();

        $isComptoir = false;
        $isGroup = false;
        foreach ($possiblegroups as $possiblegroup) {
            if ('Comptoir' == $possiblegroup->getName()) {
                $isComptoir = true;
            } elseif ('Gestionnaire de Groupe' == $possiblegroup->getName()) {
                $isGroup = true;
            } elseif ('Adherent' == $possiblegroup->getName() && null == $user->getAdherent()) {
                $groupeByDefault = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Groupe::class)->findAll()[0];
                // On crée l'entité Adhérent si on coche la case Adhérent et que l'utilisateur ne l'est pas encore
                $adherent = new Adherent();
                $adherent->setUser($user);
                $user->setAdherent($adherent);
                $adherent->setGeoloc(new Geoloc());
                $adherent->setGroupe($groupeByDefault);
                $adherent->setEcompte(0);
                $em->persist($adherent);
                $flashbag = $this->getRequest()->getSession()->getFlashBag();
                $flashbag->get('sonata_flash_success');
                $flashbag->set(
                    'sonata_flash_success',
                    $this->trans("L'utilisateur est désormais Adhérent et rattaché au premier groupe local par défaut, vous pouvez le changer dans l'édition de l'adhérent !")
                );
            }
        }

        if (!$isComptoir && !$comptoirsgeres->isEmpty()) {
            foreach ($comptoirsgeres as $comptoir) {
                $user->removeComptoirsgere($comptoir);
            }
        }

        if (!$isGroup && !$groupesgeres->isEmpty()) {
            foreach ($groupesgeres as $group) {
                $user->removeGroupesgere($group);
            }
        }

        $em->persist($user);
        $em->flush();
    }
}