ComptoirAdmin.php 10.1 KB
Newer Older
Damien Moulard committed
1 2
<?php

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * kohinos_cooperatic
 * Copyright (C) 2019-2020  ADML63
 * Copyright (C) 2020- Cooperatic
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
Damien Moulard committed
22 23 24 25 26 27 28 29 30 31 32 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
namespace App\Admin;

use App\Entity\ContactComptoir;
use App\Entity\Geoloc;
use App\Entity\GlobalParameter;
use App\Entity\Groupe;
use App\Form\Type\ContactEntityFormType;
use App\Form\Type\GeolocFormType;
use Doctrine\ORM\EntityRepository;
use FOS\CKEditorBundle\Form\Type\CKEditorType;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\DoctrineORMAdminBundle\Filter\CallbackFilter;
use Sonata\MediaBundle\Form\Type\MediaType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Form\Extension\Core\Type\TextType;

/**
 * Administration des comptoirs
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class ComptoirAdmin extends AbstractAdmin
{
    protected $security;
    protected $baseRouteName = 'comptoir';
    protected $baseRoutePattern = 'comptoir';
    protected $datagridValues = [
        '_sort_order' => 'ASC',
        '_sort_by' => 'name',
    ];

    public function setSecurity(Security $security)
    {
        $this->security = $security;
    }

    /**
    * {@inheritdoc}
    */
    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);
        $user = $this->security->getUser();
        if (empty($this->getRequest()->getSession()->get('_groupegere'))) {
75 76 77
            // TODO: Pourquoi empêcher toutes les "requêtes comptoir" pour ces rôles ?
            //if ($user->isGranted('ROLE_GESTION_GROUPE') || $user->isGranted('ROLE_CONTACT') || $user->isGranted('ROLE_TRESORIER')) {
            if ($user->isGranted('ROLE_GESTION_GROUPE') || $user->isGranted('ROLE_CONTACT')) {
Damien Moulard 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 103 104 105 106 107 108 109 110 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 209 210 211 212 213 214 215 216 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
                $query->andWhere('false = true');
            }
        } else {
            $query
                ->andWhere($query->getRootAliases()[0].'.groupe = :groupe')
                ->setParameter('groupe', $this->getRequest()->getSession()->get('_groupegere'))
            ;
        }
        return $query;
    }

    /**
    * {@inheritdoc}
    */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $comptoir = $this->getSubject();
        $user = $this->security->getUser();
        if ($this->isCurrentRoute('create')) {
            $geoloc = new Geoloc();
            $comptoir->setGeoloc($geoloc);
        }
        // get the current Image instance
        $imageHelp = null;
        if (!empty($comptoir) && !empty($comptoir->getMedia())) {
            $image = $comptoir->getMedia();
            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" />';
            }
        }
        $formMapper
            ->with('Comptoir', ['class' => 'col-md-6']);
        if (($user->isGranted('ROLE_GESTION_GROUPE') || $user->isGranted('ROLE_CONTACT')) && !empty($this->getRequest()->getSession()->get('_groupegere'))) {
            $formMapper->add('groupe', null, array(
                    'label' => 'Groupe local',
                    'required' => true,
                    'query_builder' => function (EntityRepository $repo) use ($user) {
                        return $repo->createQueryBuilder('g')
                            ->select('g')
                            ->join('g.gestionnaires', 'c')
                            ->where('c.id = :user')
                            ->setParameter('user', $user->getId());
                    },
                ));
        } else {
            $formMapper->add('groupe', null, array(
                    'label' => 'Groupe local',
                    'required' => true,
                ));
        }
        $formMapper
                ->add('name', null, array(
                    'label' => 'Nom',
                    'required' => true,
                ))
                ->add('content', CKEditorType::class, array(
                    'label' => 'Description :',
                    'required' => false
                ))
                ->add('enabled', null, array('label' => 'Activé ?'))
            ->end()
            ->with('Contact(s)', ['class' => 'col-md-6'])
                ->add('contacts', CollectionType::class, array(
                    'entry_type' => ContactEntityFormType::class,
                    'entry_options' => array('label' => false, 'data_class' => ContactComptoir::class),
                    'allow_add' => true,
                    'allow_delete' => true,
                    'by_reference' => false,
                    'label' => false
                ))
            ->end()
            ->with('Image', ['class' => 'col-md-6'])
                ->add('media', MediaType::class, array(
                    'provider' => 'sonata.media.provider.image',
                    'context' => 'prestataire',
                    'help' => $imageHelp,
                    'required' => false
                ))
            ->end()
            ->with('Geoloc', ['class' => 'col-md-6'])
                ->add('geoloc', GeolocFormType::class, array(
                    'label' => false,
                    'required' => true
                ))
            ->end()
        ;
    }

    /**
    * {@inheritdoc}
    */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        if ($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_SUPER_ADMIN') || $this->isGranted('ROLE_ADMIN_SIEGE')) {
            $datagridMapper
                ->add('groupe', null, [
                    'label' => "Groupe",
                    'show_filter' => true,
                    'advanced_filter' => false
                ])
            ;
        }
        $datagridMapper
            ->add('full_text', CallbackFilter::class, [
                'callback' => [$this, 'getFullTextFilter'],
                'field_type' => TextType::class,
                'label' => "Recherche par nom",
                'show_filter' => true,
                'advanced_filter' => false
            ])
        ;
    }

    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()->like($alias.'.name', $queryBuilder->expr()->literal('%' . $value['value'] . '%'))
        );

        return true;
    }

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

    public function configureActionButtons($action, $object = null)
    {
        $list = parent::configureActionButtons($action, $object);

        $list['test']['template'] = '@SonataAdmin/show_map_comptoir.html.twig';

        return $list;
    }
    
    public function getRouteShowOnFront($object)
    {
        return $this->routeGenerator->generate('show_comptoir', array('slug' => $object->getSlug()));
    }

    public function getRouteShowMap()
    {
        return $this->routeGenerator->generate('comptoirs_carte');
    }

    /**
    * {@inheritdoc}
    */
    protected function configureListFields(ListMapper $listMapper)
    {
        unset($this->listModes['mosaic']);

        $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' => []
            ];
        } else {
            $actions = [
                'edit' => []
            ];
        }

        $listMapper
            ->addIdentifier('name')
            ->addIdentifier('groupe', null, array(
                'label' => 'Groupe',
                'sortable' => true,
                'sort_field_mapping' => array('fieldName' => 'name'),
                'sort_parent_association_mappings' => array(array('fieldName' => 'groupe'))
            ))
            ->add('compte', null, array('label' => 'Solde'))
            ->add('geoloc', null, array('label' => 'Adresse'))
            ->add('enabled', null, array(
                'label' => 'Activé',
                'editable' => true
            ))
            ->add('_action', null, [
                'actions' => $actions
            ])
        ;
    }
272 273 274 275 276 277 278 279 280 281 282
    public function getExportFields()
    {
        return [
            'Id'                   => 'id',
            'Nom du comptoir'      => 'name',
            'Groupe'               => 'groupe',
            'Solde du comptoir'    => 'compte',
            'Adresse'              => 'geoloc',
            'Activé (1=oui)'       => 'enabled'
        ];
    }
Damien Moulard committed
283
}