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

namespace App\Admin;

use App\Admin\UserAdmin;
Julien Jorry committed
6
use App\Entity\Adherent;
7
use App\Entity\ContactPrestataire;
8
use App\Entity\Cotisation;
9
use App\Entity\CotisationPrestataire;
Julien Jorry committed
10
use App\Entity\EtatPrestataire;
11
use App\Entity\Geoloc;
12
use App\Entity\GlobalParameter;
13
use App\Entity\Groupe;
14
use App\Entity\Prestataire;
Julien Jorry committed
15
use App\Entity\Rubrique;
16
use App\Entity\User;
17
use App\Entity\Usergroup;
18
use App\Enum\MoyenEnum;
19
use App\Form\Type\ContactEntityFormType;
20
use App\Form\Type\CotisationFormType;
Julien Jorry committed
21
use App\Form\Type\GeolocPrestataireFormType;
Julien Jorry committed
22
use App\Form\Type\UserFormType;
Julien Jorry committed
23
use App\Form\Type\UserInfosFormType;
24
use Doctrine\ORM\Query;
25
use FOS\CKEditorBundle\Form\Type\CKEditorType;
Julien Jorry committed
26
use FOS\UserBundle\Model\UserManagerInterface;
27 28 29
use Knp\Menu\ItemInterface as MenuItemInterface;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\AdminInterface;
30
use Sonata\AdminBundle\Datagrid\DatagridMapper;
Julien Jorry committed
31 32
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
Julien Jorry committed
33
use Sonata\AdminBundle\Route\RouteCollection;
Julien Jorry committed
34
use Sonata\AdminBundle\Show\ShowMapper;
Julien Jorry committed
35
use Sonata\DoctrineORMAdminBundle\Filter\CallbackFilter;
Julien Jorry committed
36
use Sonata\MediaBundle\Form\Type\MediaType;
Julien Jorry committed
37 38 39
use Sonata\MediaBundle\Provider\Pool;
use Sonata\MediaBundle\Provider\MediaProviderInterface;
use Sonata\AdminBundle\Object\Metadata;
Julien Jorry committed
40
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
41
use Symfony\Component\Form\CallbackTransformer;
42 43
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
44
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
45
use Symfony\Component\Form\Extension\Core\Type\DateType;
46
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
47
use Symfony\Component\Form\Extension\Core\Type\PercentType;
Julien Jorry committed
48
use Symfony\Component\Form\Extension\Core\Type\TextType;
49
use Symfony\Component\Form\Extension\Core\Type\UrlType;
50
use Symfony\Component\Form\FormError;
Julien Jorry committed
51 52
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
53
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
54
use Symfony\Component\Security\Core\Security;
Julien Jorry committed
55

56 57 58
/**
 * Administration des prestataires
 *
Julien Jorry committed
59
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
60 61
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
62
class PrestataireAdmin extends AbstractAdmin
Julien Jorry committed
63
{
Julien Jorry committed
64 65
    protected $baseRouteName = 'prestataire';
    protected $baseRoutePattern = 'prestataire';
66
    protected $security;
Julien Jorry committed
67
    protected $pool;
68 69 70 71
    protected $datagridValues = [
        // reverse order (default = 'ASC')
        '_sort_order' => 'DESC',
        // name of the ordered field (default = the model's id field, if any)
72
        '_sort_by' => 'raison',
73 74 75 76
        // '_page' => 1,
        // '_per_page' => 32
    ];

77
    public function setSecurity(Security $security)
78
    {
79
        $this->security = $security;
80 81
    }

Julien Jorry committed
82 83 84 85 86
    public function setPool(Pool $pool)
    {
        $this->pool = $pool;
    }

Julien Jorry committed
87 88 89 90 91
    public function configure()
    {
        parent::configure();
    }

Julien Jorry committed
92 93 94 95 96 97 98
    /**
    * {@inheritdoc}
    */
    public function createQuery($context = 'list')
    {
        $user = $this->security->getUser();
        $query = parent::createQuery($context);
99

100
        if ($user->hasRole('ROLE_GESTION_GROUPE') || $user->hasRole('ROLE_CONTACT') || $user->isGranted('ROLE_TRESORIER')) {
Julien Jorry committed
101
            if (empty($this->getRequest()->getSession()->get('_groupegere'))) {
102
                $query->andWhere('false = true');
Julien Jorry committed
103 104
            } else {
                $query
Julien Jorry committed
105 106
                    ->andWhere($query->getRootAliases()[0].'.groupe = :group')
                    ->setParameter('group', $this->getRequest()->getSession()->get('_groupegere'))
Julien Jorry committed
107 108 109 110 111 112
                ;
            }
        }
        return $query;
    }

113 114 115 116 117
    protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
    {
        if (!$childAdmin && !in_array($action, ['edit', 'show'])) {
            return;
        }
118
        $user = $this->security->getUser();
119 120 121
        $admin = $this->isChild() ? $this->getParent() : $this;
        $id = $admin->getRequest()->get('id');

Julien Jorry committed
122 123 124 125
        $presta = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Prestataire::class)->findOneById($id);
        $users = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(User::class)->findByPrestataire($id);

        if ($this->isGranted('EDIT') && !empty($users)) {
126
            // @TODO : si plusieurs utilisateurs, mettre un lien par user pour modifier celui-ci ?
Julien Jorry committed
127 128 129 130 131 132 133 134 135 136 137
            // $menu->addChild("Modifier l'utilisateur", [
            //     'uri' => $this->getConfigurationPool ()->getContainer()->get('router')->generate('admin_app_user_edit', ['id' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL)
            // ]);
        }
        // Le prestataire "Monnaie Locale" représentant l'asso recevant les cotisations n'a pas de cotisations lui même !
        if (!$presta->isMlc()) {
            $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)
138 139 140 141
            ]);
        }
    }

Julien Jorry committed
142 143 144 145 146
    /**
    * {@inheritdoc}
    */
    protected function configureFormFields(FormMapper $formMapper): void
    {
147
        // Initialize prestataire
148
        $presta = $this->getSubject();
Julien Jorry committed
149
        // $user = $this->security->getUser();
150
        $now = new \DateTime();
151
        $cotisation = null;
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')
Julien Jorry committed
168
                ->with('Prestataire', ['class' => 'col-md-6'])
169 170 171 172 173
                    ->add('typeprestataire', null, array(
                        'label' => 'Type :',
                        'required' => true,
                        'expanded' => true
                    ))
174 175 176 177 178 179 180
                    ->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',
                    ))
181
                    ->add('raison', TextType::class, array(
Julien Jorry committed
182 183 184
                        'label' => 'Raison :',
                        'required' => true
                    ))
185
                    ->add('statut', TextType::class, array(
Julien Jorry committed
186 187 188
                        'label' => 'Statut :',
                        'required' => false
                    ))
189
                    ->add('siret', TextType::class, array(
Julien Jorry committed
190
                        'label' => 'SIRET :',
191
                        'required' => true
Julien Jorry committed
192
                    ))
193
                    ->add('iban', TextType::class, array(
Julien Jorry committed
194
                        'label' => 'IBAN :',
Julien Jorry committed
195
                        'required' => false
Julien Jorry committed
196
                    ))
197
                    ->add('responsable', TextType::class, array(
Julien Jorry committed
198 199 200
                        'label' => 'Responsable :',
                        'required' => false
                    ))
201 202
                    ->add('metier', TextType::class, array(
                        'label' => 'Métier responsable :',
203 204 205 206 207 208
                        'required' => false
                    ))
                    ->add('horaires', TextType::class, array(
                        'label' => 'Horaires',
                        'required' => false
                    ))
209 210 211 212
                    ->add('web', UrlType::class, array(
                        'label' => 'Site Web',
                        'required' => false
                    ))
213 214
                    ->add('description', CKEditorType::class, array(
                        'label' => 'Description',
215 216
                        'required' => false
                    ))
217 218 219 220 221 222 223 224 225
                    ->add('tauxreconversion', PercentType::class, array(
                        'label' => 'Taux de reconversion',
                        'required' => false,
                        'type' => 'integer',
                        'help' => 'Si la valeur est nulle, par défaut le taux de reconversion sera de '.$this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(GlobalParameter::class)->val(GlobalParameter::RECONVERSION_PRESTATAIRE).' %'
                    ))
                    ->add('enabled', CheckboxType::class, array(
                        'label' => 'Activé ?'
                    ))
Julien Jorry committed
226
                ->end()
Julien Jorry committed
227 228
                ->with('Contact(s)', ['class' => 'col-md-6'])
                    ->add('contacts', CollectionType::class, array(
229 230
                        'entry_type' => ContactEntityFormType::class,
                        'entry_options' => array('label' => false, 'data_class' => ContactPrestataire::class),
Julien Jorry committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244
                        'allow_add' => true,
                        'allow_delete' => true,
                        'by_reference' => false,
                        'label' => false
                    ))
                ->end()
                ->with('Adresse(s)', ['class' => 'col-md-6'])
                    ->add('geolocs', CollectionType::class, array(
                        'entry_type' => GeolocPrestataireFormType::class,
                        'entry_options' => array('label' => false),
                        'allow_add' => true,
                        'allow_delete' => true,
                        'by_reference' => false,
                        'label' => false
Julien Jorry committed
245 246
                    ))
                ->end()
Julien Jorry committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
                ->with('Classification', ['class' => 'col-md-6'])
                    ->add('etats', EntityType::class, array(
                        'class' => EtatPrestataire::class,
                        'multiple' => true,
                        'required' => false,
                        'by_reference' => false,
                        'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(EtatPrestataire::class)->findBy(array('enabled' => true)),
                        'label' => 'Tags'
                    ))
                    ->add('rubriques', EntityType::class, array(
                        'class' => Rubrique::class,
                        'multiple' => true,
                        'required' => false,
                        'by_reference' => false,
                        'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Rubrique::class)->findBy(array('enabled' => true)),
                        'label' => 'Rubriques'
                    ))
                ->end()
                ->with('Image', ['class' => 'col-md-6'])
Julien Jorry committed
266 267 268 269 270 271 272
                    ->add('media', MediaType::class, array(
                        'provider' => 'sonata.media.provider.image',
                        'context' => 'prestataire',
                        'help' => $imageHelp,
                        'required' => false
                    ))
                ->end()
Julien Jorry committed
273 274 275 276
                ->with('Gestionnaire(s)', ['class' => 'col-md-6'])
                    ->add('users', EntityType::class, array(
                        // 'mapped' => false,
                        'class' => User::class,
Julien Jorry committed
277
                        'multiple' => true,
Julien Jorry committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
                        'required' => false,
                        'label' => 'Associer à un(des) utilisateur(s) existant :',
                        'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(User::class)->findAll(),
                        'choice_label' => 'username',
                        'placeholder' => 'Choisir un utilisateur',
                    ))
                    ->add('newusers', CollectionType::class, array(
                        'mapped' => false,
                        'required' => false,
                        'label' => 'Nouvel Utilisateur/Adhérent',
                        'entry_type' => UserFormType::class,
                        'entry_options' => array(
                            'required' => false,
                            'label' => false),
                        'by_reference' => false,
                        'allow_add' => true,
                        'allow_delete' => true
Julien Jorry committed
295 296
                    ))
                ->end()
297 298 299 300 301 302 303 304 305 306 307 308
            ->end()
        ;
        // @TODO : add tags model transformer if add new from text
        // ->get('etats')
        // ->addModelTransformer(new CallbackTransformer(
        //     function ($tagsAsArray) {
        //         // transform the array to a string
        //         return $tagsAsArray;
        //     },
        //     function ($tagsAsString) {
        //         // transform the string back to an array
        //         return explode(', ', $tagsAsString);
309
        //     }
310
        // ))
311 312 313 314

        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $formMapper->getFormBuilder()->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($em) {
            $prestataire = $event->getData();
Julien Jorry committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
            $users = null;
            /* Permet d'ajouter le nouvel utilisateur crée (newusers) aux gestionnaires du presta */
            if ($event->getForm()->get('users')->getData() != null) {
                $users = $event->getForm()->get('users')->getData();
            }
            if ($event->getForm()->get('newusers')->getData() != null) {
                $users = array_merge($users, $event->getForm()->get('newusers')->getData());
            }
            if ($users != null) {
                // On crée un compte adhérent en même temps que le prestataire
                foreach ($users as $user) {
                    if ($user->getId() == null) {
                        $emailExist = $em->getRepository(User::class)->findBy(array('email' => $user->getEmail()));
                        if (count($emailExist) > 0) {
                            $event->getForm()->get('newusers')->addError(new FormError('Courriel déjà utilisé !'));
                            break;
                        }
                        $user->setUsername($user->getEmail());
                        $adh = new Adherent();
                        $user->setAdherent($adh);
                        $groupeAdh = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Adherent');
                        $groupePresta = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Prestataire');
337 338
                        $user->addPossiblegroup($groupeAdh);
                        $user->addPossiblegroup($groupePresta);
Julien Jorry committed
339 340 341 342 343
                        $this->userManager->updateUser($user);
                        // $user->addRole('ROLE_PRESTATAIRE');
                        // $user->addRole('ROLE_ADHERENT');
                    }
                    $prestataire->addUser($user);
344
                }
Julien Jorry committed
345 346
            } else {
                $event->getForm()->get('users')->addError(new FormError('Veuillez séléctionner un utilisateur ou en créer un nouveau !'));
347 348
            }
        });
Julien Jorry committed
349
        parent::configureFormFields($formMapper);
Julien Jorry committed
350 351
    }

352 353 354 355 356 357 358
    /**
    * {@inheritdoc}
    */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        parent::configureDatagridFilters($datagridMapper);
        $datagridMapper
Julien Jorry committed
359 360 361 362 363 364 365 366 367 368 369 370
            ->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
            ])
Julien Jorry committed
371 372 373 374
            ->add('etats', null, [
                'label' => "Tags",
                'show_filter' => true,
                'advanced_filter' => false
375
                ], null, ['expanded' => true, 'multiple' => true
Julien Jorry committed
376
            ])
Julien Jorry committed
377
            ->add('typeprestataire', null, [
Julien Jorry committed
378 379
                'label' => "Type",
                'advanced_filter' => false
Julien Jorry committed
380
            ])
381 382 383
        ;
    }

Julien Jorry committed
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    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($alias.'.raison', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
            $queryBuilder->expr()->like($alias.'.statut', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
            $queryBuilder->expr()->like($alias.'.description', $queryBuilder->expr()->literal('%' . $value['value'] . '%'))
        ));

        return true;
    }
399 400 401 402 403 404 405 406 407
    public function getTemplate($name)
    {
        if ($name == 'edit') {
            return 'presta/block/base_edit_prestataires.html.twig';
        }

        return parent::getTemplate($name);
    }

Julien Jorry committed
408 409 410 411 412 413 414 415 416 417 418 419 420 421
    /**
     * @param UserManagerInterface $userManager
     */
    public function setUserManager(UserManagerInterface $userManager): void
    {
        $this->userManager = $userManager;
    }

    /**
     * @return UserManagerInterface
     */
    public function getUserManager()
    {
        return $this->userManager;
Julien Jorry committed
422 423
    }

424 425 426 427 428
    public function getRouteShowOnFront($object)
    {
        return $this->routeGenerator->generate('show_prestataire', array('slug' => $object->getSlug()));
    }

Julien Jorry committed
429 430
    protected function configureListFields(ListMapper $listMapper): void
    {
Julien Jorry committed
431
        unset($this->listModes['mosaic']);
432
        $user = $this->security->getUser();
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
        $isWordpressActivated = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_WORDPRESS);
        if ($isWordpressActivated == 'false') {
            $actions = [
            'show' => ['template' => '@SonataAdmin/CRUD/list__action_showonfront.html.twig'],
            'edit' => [
                // You may add custom link parameters used to generate the action url
                'link_parameters' => [
                    'full' => true,
                ]
            ]];
        } else {
            $actions = [
                'edit' => [
                    // You may add custom link parameters used to generate the action url
                    'link_parameters' => [
                        'full' => true,
                    ]
            ]];
        }
Julien Jorry committed
452
        $listMapper
453
            ->addIdentifier('raison')
454
            ->add('groupe', null, array(
455 456 457 458 459
                'label' => 'Groupe',
                'sortable' => true,
                'sort_field_mapping' => array('fieldName' => 'name'),
                'sort_parent_association_mappings' => array(array('fieldName' => 'groupe'))
            ))
460 461 462 463 464 465 466 467 468 469 470 471
            // ->addIdentifier('users', null, array('label' => 'Gestionnaires'))
            ->add('rubriques', null)
            ->add('etats', null, array(
                'label' => 'Tags',
                // 'editable' => true,
                // 'class' => EtatPrestataire::class,
                // 'multiple' => true,
                // // 'required' => false,
                // // 'by_reference' => false,
                // 'choices' => $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(EtatPrestataire::class)->findBy(array('enabled' => true))
            ))
            ->add('enabled', null, array(
Julien Jorry committed
472
                'label' => 'Activé',
473
                'editable' => true
Julien Jorry committed
474
            ))
475 476 477 478 479
            ->add('updatedAt', null, array(
                'label' => 'Mis à jour'
            ))
            // You may also specify the actions you want to be displayed in the list
            ->add('_action', null, [
480
                'actions' => $actions
481
            ])
482
        ;
Julien Jorry committed
483 484 485 486 487 488 489
    }

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

Julien Jorry committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    public function getObjectMetadata($object)
    {
        if ($object->getMedia() != null) {
            $provider = $this->pool->getProvider($object->getMedia()->getProviderName());

            $url = $provider->generatePublicUrl(
                $object->getMedia(),
                $provider->getFormatName($object->getMedia(), MediaProviderInterface::FORMAT_ADMIN)
            );

            return new Metadata($object->getRaison(), strip_tags($object->getDescription()), $url);
        }
        return new Metadata($object->getRaison(), strip_tags($object->getDescription()));
    }

505 506 507 508 509 510 511
    public function getBatchActions()
    {
        $actions = parent::getBatchActions();
        unset($actions['delete']);

        return $actions;
    }
Julien Jorry committed
512 513 514 515 516 517

    /* @TODO : définir champ à exporter */
    public function getExportFields()
    {
        return [
            'Id'                     => 'id',
Julien Jorry committed
518
            'Raison'                 => 'raison',
Julien Jorry committed
519
            'Groupe'                 => 'groupe.name',
Julien Jorry committed
520 521 522 523
            'E-compte'               => 'ecompte',
            'Rubriques'              => 'rubriquesString',
            'Gestionnaires'          => 'usersString',
            'Tags'                   => 'etatsString'
Julien Jorry committed
524 525
        ];
    }
Julien Jorry committed
526
}