PrestataireAdmin.php 21.4 KB
Newer Older
Julien Jorry committed
1 2 3 4 5
<?php

namespace App\Admin;

use App\Admin\UserAdmin;
6
use App\Entity\Cotisation;
7
use App\Entity\CotisationPrestataire;
8
use App\Entity\Geoloc;
9
use App\Entity\Groupe;
10
use App\Entity\Prestataire;
11
use App\Entity\User;
12
use App\Entity\Usergroup;
13
use App\Enum\MoyenEnum;
14
use App\Form\Type\CotisationFormType;
15
use Doctrine\ORM\Query;
16
use FOS\CKEditorBundle\Form\Type\CKEditorType;
Julien Jorry committed
17
use FOS\UserBundle\Model\UserManagerInterface;
18 19 20
use Knp\Menu\ItemInterface as MenuItemInterface;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\AdminInterface;
21
use Sonata\AdminBundle\Datagrid\DatagridMapper;
Julien Jorry committed
22 23
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
Julien Jorry committed
24
use Sonata\AdminBundle\Route\RouteCollection;
Julien Jorry committed
25
use Sonata\AdminBundle\Show\ShowMapper;
Julien Jorry committed
26
use Sonata\MediaBundle\Form\Type\MediaType;
Julien Jorry committed
27
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
28 29
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
30
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
31
use Symfony\Component\Form\Extension\Core\Type\DateType;
32
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
Julien Jorry committed
33
use Symfony\Component\Form\Extension\Core\Type\TextType;
34
use Symfony\Component\Form\FormError;
Julien Jorry committed
35 36
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
37
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
38
use Symfony\Component\Security\Core\Security;
Julien Jorry committed
39

40 41 42 43 44 45
/**
 * Administration des prestataires
 *
 * LOCO : Outil de gestion de Monnaie Locale Complémentaire
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
46
class PrestataireAdmin extends AbstractAdmin
Julien Jorry committed
47
{
Julien Jorry committed
48 49
    protected $baseRouteName = 'prestataire';
    protected $baseRoutePattern = 'prestataire';
50
    protected $security;
51 52 53 54 55 56 57 58 59
    protected $datagridValues = [
        // reverse order (default = 'ASC')
        '_sort_order' => 'DESC',
        // name of the ordered field (default = the model's id field, if any)
        '_sort_by' => 'updatedAt',
        // '_page' => 1,
        // '_per_page' => 32
    ];

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

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

Julien Jorry committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    /**
    * {@inheritdoc}
    */
    public function createQuery($context = 'list')
    {
        $user = $this->security->getUser();
        $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;
    }

95 96 97 98 99
    protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
    {
        if (!$childAdmin && !in_array($action, ['edit', 'show'])) {
            return;
        }
100
        $user = $this->security->getUser();
101 102 103 104 105
        $admin = $this->isChild() ? $this->getParent() : $this;
        $id = $admin->getRequest()->get('id');
        $user = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(User::class)->findOneBy(array('prestataire' => $id));

        if ($this->isGranted('EDIT') && $user != null) {
106
            $menu->addChild("Modifier l'utilisateur", [
107 108 109
                'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('admin_app_user_edit', ['id' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL)
            ]);
        }
110 111 112 113 114 115
        $menu->addChild("Ajouter une cotisation", [
            'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('cotisation_prestataire_create', ['expediteur' => $id], UrlGeneratorInterface::ABSOLUTE_URL)
        ]);
        $menu->addChild("Voir les cotisations", [
            'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('cotisation_prestataire_list', ['filter' => array('expediteur' => array('value' => $id))], UrlGeneratorInterface::ABSOLUTE_URL)
        ]);
116 117
    }

Julien Jorry committed
118 119 120 121 122
    /**
    * {@inheritdoc}
    */
    protected function configureFormFields(FormMapper $formMapper): void
    {
123
        // Initialize prestataire
124
        $presta = $this->getSubject();
125
        $user = $this->security->getUser();
126
        $now = new \DateTime();
127
        $cotisation = null;
128
        if ($this->isCurrentRoute('create')) {
129 130 131 132 133
            if ($user->isGranted('ROLE_CONTACT') or $user->isGranted('ROLE_COMPTOIR')) {
                $user->setEnabled(false);
            } else {
                $user->setEnabled(true);
            }
134 135 136 137 138 139 140
            $user = $this->userManager->createUser();
            $groupe = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Prestataire');
            $user->addGroup($groupe);
            $user->addRole('ROLE_PRESTATAIRE');
            $user->setPrestataire($presta);
            $presta->setUser($user);
        }
141 142 143 144 145 146 147 148
        // if (count($presta->getUser()->getCotisations()) <= 0) {
        //     $cotisation = new Cotisation();
        //     $cotisation->setOperateur($presta->getUser());
        //     $cotisation->setExpediteur($presta);
        //     $cotisation->setDebut($now);
        //     $cotisation->setFin(new \DateTime('+ 1 year'));
        //     $presta->getUser()->addCotisation($cotisation);
        // }
149 150 151
        if ($presta->getGeoloc() == null) {
            $presta->setGeoloc(new Geoloc());
        }
152 153

        // get the current Image instance
154
        $imageHelp = null;
155 156
        if (!empty($presta) && !empty($presta->getMedia())) {
            $image = $presta->getMedia();
157 158 159 160 161 162 163 164 165
            if ($image && ($webPath = $image->getWebPath())) {
                // get the container so the full path to the image can be set
                $container = $this->getConfigurationPool()->getContainer();
                $fullPath = $container->get('request_stack')->getCurrentRequest()->getBasePath().'/'.$webPath;
                // add a 'help' option containing the preview's img tag
                $imageHelp = '<img src="'.$fullPath.'" class="admin-preview" />';
            }
        }

Julien Jorry committed
166 167
        $formMapper
            ->tab('Prestataire')
168
                ->with('Identité', ['class' => 'col-md-7'])
169 170 171 172 173
                    ->add('typeprestataire', null, array(
                        'label' => 'Type :',
                        'required' => true,
                        'expanded' => true
                    ))
174 175
                    ->add('user.firstname', TextType::class, array(
                        'label' => 'Prénom :',
176
                        'required' => false
177 178 179
                    ))
                    ->add('user.lastname', TextType::class, array(
                        'label' => 'Nom :',
180
                        'required' => false
181 182 183 184 185
                    ));
        if (!$this->isCurrentRoute('create')) {
            $formMapper
                ->add('user.username', TextType::class, array(
                    'label' => 'Username :',
186
                    'required' => false,
187 188 189
                    'disabled' => true
                ));
        }
190
        $formMapper
191 192
                    ->add('user.phone', TextType::class, array(
                        'label' => 'Téléphone :',
193
                        'required' => false
194 195 196 197 198
                    ))
                    ->add('user.email', TextType::class, array(
                        'label' => 'Email :',
                        'required' => true
                    ))
199 200 201 202 203 204 205
                    ->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',
                    ))
206
                ->end()
207 208 209 210
                ->with('Addresse', ['class' => 'col-md-5'])
                    ->add('geoloc.adresse', TextType::class, array(
                        'label' => 'Addresse :',
                        'required' => false
211
                    ))
212 213 214
                    ->add('geoloc.cpostal', TextType::class, array(
                        'label' => 'Code postal :',
                        'required' => false
215
                    ))
216 217 218
                    ->add('geoloc.ville', TextType::class, array(
                        'label' => 'Ville :',
                        'required' => false
219
                    ))
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
                    // ->add('geoloc.lat', TextType::class, array(
                    //     'label' => 'Latitude :',
                    //     'required' => false
                    // ))
                    // ->add('geoloc.lon', TextType::class, array(
                    //     'label' => 'Longitude :',
                    //     'required' => false
                    // ))
                ->end()
                ->with('Image', ['class' => 'col-md-5'])
                    ->add('media', MediaType::class, array(
                        'provider' => 'sonata.media.provider.image',
                        'context' => 'prestataire',
                        'help' => $imageHelp,
                        'required' => false
                    ))
                ->end()
237 238
                ->with('Société', ['class' => 'col-md-7'])
                    ->add('raison', TextType::class, array(
Julien Jorry committed
239 240 241
                        'label' => 'Raison :',
                        'required' => true
                    ))
242
                    ->add('statut', TextType::class, array(
Julien Jorry committed
243 244 245
                        'label' => 'Statut :',
                        'required' => false
                    ))
246
                    ->add('siret', TextType::class, array(
Julien Jorry committed
247
                        'label' => 'SIRET :',
248
                        'required' => true
Julien Jorry committed
249
                    ))
250
                    ->add('iban', TextType::class, array(
Julien Jorry committed
251
                        'label' => 'IBAN :',
252
                        'required' => true
Julien Jorry committed
253
                    ))
254
                    ->add('responsable', TextType::class, array(
Julien Jorry committed
255 256 257
                        'label' => 'Responsable :',
                        'required' => false
                    ))
258 259
                    ->add('metier', TextType::class, array(
                        'label' => 'Métier responsable :',
260 261 262 263 264 265
                        'required' => false
                    ))
                    ->add('horaires', TextType::class, array(
                        'label' => 'Horaires',
                        'required' => false
                    ))
266 267
                    ->add('description', CKEditorType::class, array(
                        'label' => 'Description',
268 269
                        'required' => false
                    ))
270
                ->end();
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
        // if ($cotisation != null) {
        //     //@TODO : cotisationS
        //     $formMapper
        //         ->with('Cotisation', ['class' => 'col-md-5'])
        //             ->add('user.cotisations.last.cotisationInfos.annee', TextType::class, array('label' => 'Année', 'data' => intval($now->format('Y'))))
        //             ->add('user.cotisations.last.montant', MoneyType::class, array(
        //                 'label' => 'Montant',
        //                 'empty_data' => floatval($this->getConfigurationPool()->getContainer()->getParameter('app.cotisation_montant'))
        //             ))
        //             ->add('user.cotisations.last.moyen', ChoiceType::class, array(
        //                 'required' => true,
        //                 'label' => 'Moyen :',
        //                 'choices' => MoyenEnum::getAvailableTypes(),
        //                 'choice_label' => function ($choice) {
        //                     return MoyenEnum::getTypeName($choice);
        //                 },
        //             ))
        //             ->add('user.cotisations.last.cotisationInfos.recu', CheckboxType::class, array(
        //                 'label' => 'Reçu',
        //                 'required' => false
        //             ))
        //         ->end();
        //     if (!$this->isCurrentRoute('create')) {
        //         $formMapper
        //             ->with('Date', ['class' => 'col-md-5'])
        //                 ->add('user.cotisations.last.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.last.cotisationInfos.fin', DateType::class, array(
        //                     'label' => 'Date de fin',
        //                     'data' => new \DateTime('+ 1 year'),
        //                     'widget' => 'single_text',
        //                     'html5' => false,
        //                     'attr' => ['class' => 'js-datepicker'],
        //                 ))
        //             ->end();
        //     }
        // } else {
        // if (count($presta->getUser()->getCotisations()) > 0) {
        //     $formMapper
        //         ->end()
        //         ->tab('Cotisation')
        //             ->with('Cotisations', ['class' => 'col-md-12'])
        //                 ->add('user.cotisations', CollectionType::class, array(
        //                     'entry_type' => CotisationFormType::class,
        //                     // 'data' => $presta->getUser()->getCotisations(),
        //                     // 'entry_options' => array(
        //                     // //     'class' => Cotisation::class,
        //                     // //     'choices' =>  $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(CotisationPrestataire::class)->findBy(array('expediteur' => $presta)),
        //                     // //     'choice_label' => 'reference',
        //                     // //     'placeholder' => 'Cotisation',
        //                     // //     'required' => false,
        //                     //     'label' => false
        //                     // ),
        //                     'by_reference' => false,
        //                     'allow_add' => false,
        //                     'allow_delete' => false,
        //                     'disabled' => true,
        //                 ), array(
        //                     'admin_code' => 'admin.prestataire.cotisations'
        //                 ))
        //             ->end()
        //     ;
        // }
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
            // $formMapper
            //     ->tab('Cotisation '.$cotisation->getAnnee())
            //         ->with('Cotisation', ['class' => 'col-md-5'])
            //             ->add('user.cotisations.get('.$cnt.').cotisationInfos.annee', TextType::class, array('label' => 'Année', 'data' => $now->format('Y')))
            //             ->add('user.cotisations.get('.$cnt.').montant', TextType::class, array('label' => 'Montant'))
            //             ->add('user.cotisations.get('.$cnt.').moyen', ChoiceType::class, array(
            //                 'required' => true,
            //                 'label' => 'Moyen :',
            //                 'choices' => MoyenEnum::getAvailableTypes(),
            //                 'choice_label' => function ($choice) {
            //                     return MoyenEnum::getTypeName($choice);
            //                 },
            //             ))
            //             ->add('user.cotisations.get('.$cnt.').cotisationInfos.recu', CheckboxType::class, array('label' => 'Reçu'))
            //         ->end()
            //         ->with('Date', ['class' => 'col-md-5'])
            //             ->add('user.cotisations.get('.$cnt.').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.get('.$cnt.').cotisationInfos.fin', DateType::class, array(
            //                 'label' => 'Date de fin',
            //                 'data' => new \DateTime('+ 1 year'),
            //                 'widget' => 'single_text',
            //                 'html5' => false,
            //                 'attr' => ['class' => 'js-datepicker'],
            //             ))
            //         ->end()
            // ;
371

372
        $formMapper->end();
373 374 375 376 377 378 379 380 381 382 383 384 385 386
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $formMapper->getFormBuilder()->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($em) {
            $prestataire = $event->getData();
            $user = $prestataire->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());
                }
            }
        });
Julien Jorry committed
387
        parent::configureFormFields($formMapper);
Julien Jorry committed
388 389
    }

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    public function preUpdate($prestataire)
    {
        $this->prePersist($prestataire);
    }

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

        if (empty($prestataire->getUser()->getUsername())) {
            $prestataire->getUser()->setUsername($prestataire->getUser()->getEmail());
        }
        if (empty($prestataire->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), '+/', '-_'), '=');
            $prestataire->getUser()->setPassword($password);
408
            // TODO : send email to user
409 410 411 412 413 414 415 416 417 418
        }
        $this->userManager->updateUser($prestataire->getUser());
        $prestataire->getUser()->createEmailToken();
        $em->persist($prestataire->getUser());
        $em->persist($prestataire);
        $em->flush();
        // TODO : envoyer un mail au nouvel utilisateur avec l'emailtoken via le dispatch d'un event
        // $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($adherent->getUser(), $this->getRequest(), $response));
    }

419 420 421 422 423 424 425
    /**
    * {@inheritdoc}
    */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        parent::configureDatagridFilters($datagridMapper);
        $datagridMapper
426
            ->add('typeprestataire')
427 428
            ->add('raison')
            ->add('statut')
429 430 431
        ;
    }

432 433 434 435 436 437 438 439 440
    public function getTemplate($name)
    {
        if ($name == 'edit') {
            return 'presta/block/base_edit_prestataires.html.twig';
        }

        return parent::getTemplate($name);
    }

Julien Jorry committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454
    /**
     * @param UserManagerInterface $userManager
     */
    public function setUserManager(UserManagerInterface $userManager): void
    {
        $this->userManager = $userManager;
    }

    /**
     * @return UserManagerInterface
     */
    public function getUserManager()
    {
        return $this->userManager;
Julien Jorry committed
455 456 457 458
    }

    protected function configureListFields(ListMapper $listMapper): void
    {
Julien Jorry committed
459
        unset($this->listModes['mosaic']);
460
        $user = $this->security->getUser();
Julien Jorry committed
461
        $listMapper
462 463 464
            ->addIdentifier('user.username')
            ->addIdentifier('user.email')
            ->addIdentifier('raison')
465 466 467 468 469 470
            ->addIdentifier('groupe', null, array(
                'label' => 'Groupe',
                'sortable' => true,
                'sort_field_mapping' => array('fieldName' => 'name'),
                'sort_parent_association_mappings' => array(array('fieldName' => 'groupe'))
            ))
471 472 473 474 475 476 477
        ;
        if ($user->isGranted('ROLE_GESTION_GROUPE')) {
            $listMapper
                ->addIdentifier('user.enabled', null, array('label' => 'Activé', 'datatype' => 'App.User', 'template' => '@SonataAdmin/Boolean/editable_boolean.html.twig'))
            ;
        }
        $listMapper
478
            ->addIdentifier('user.createdAt')
Julien Jorry committed
479 480
        ;

481 482 483 484 485
        // if ($this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
        //     $listMapper
        //         ->addIdentifier('user.impersonating', 'string', ['template' => '@SonataUser/Admin/Field/impersonating.html.twig'])
        //     ;
        // }
Julien Jorry committed
486 487 488 489 490 491 492
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        $collection->remove('delete');
    }

493 494 495 496 497 498 499
    public function getBatchActions()
    {
        $actions = parent::getBatchActions();
        unset($actions['delete']);

        return $actions;
    }
Julien Jorry committed
500
}