CotisationAdmin.php 10.7 KB
Newer Older
Julien Jorry committed
1 2 3 4 5
<?php

namespace App\Admin;

use App\Entity\Flux;
6
use App\Entity\Groupe;
Julien Jorry committed
7 8 9
use App\Entity\Prestataire;
use App\Entity\User;
use App\Enum\MoyenEnum;
10 11
use App\Exception\BalanceInsufficientException;
use App\Utils\OperationUtils;
Julien Jorry committed
12 13 14 15 16 17 18 19 20 21 22 23
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 Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Validator\Constraints\Regex;
24
use Symfony\Component\HttpFoundation\RedirectResponse;
Julien Jorry committed
25 26 27 28 29 30 31 32 33 34 35 36 37

/**
 * Administration des cotisations.
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 *
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class CotisationAdmin extends AbstractAdmin
{
    protected $baseRouteName = 'cotisation';
    protected $baseRoutePattern = 'cotisation';
    protected $security;
38
    protected $operationUtils;
Julien Jorry committed
39 40 41 42 43

    protected $translator;
    protected $datagridValues = [
        '_sort_order' => 'DESC',
        '_sort_by' => 'createdAt',
44
        '_per_page' => 250,
Julien Jorry committed
45
    ];
46 47
    protected $maxPerPage = 250;
    protected $perPageOptions = [50, 100, 250, 500, 1000];
Julien Jorry committed
48

49 50 51 52 53
    public function setOperationUtils(OperationUtils $operationUtils)
    {
        $this->operationUtils = $operationUtils;
    }

Julien Jorry committed
54 55 56 57 58 59 60 61 62 63
    public function setSecurity(Security $security)
    {
        $this->security = $security;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
64
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
Julien Jorry committed
65 66 67
        $datagridMapper
            ->add('cotisationInfos.annee', null, ['label' => 'Année'])
            ->add('montant', null, ['label' => 'Montant'])
68 69 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
            ->add('groupe', 'doctrine_orm_callback', [
                'label' => 'Groupe local',
                'callback' => function ($queryBuilder, $alias, $field, $value) {
                    if (!$value['value']) {
                        return;
                    }
                    $queryBuilder
                        ->leftJoin('App\Entity\CotisationPrestataire', 'c', 'WITH', $alias . '.id = c.id')
                        ->leftJoin('App\Entity\CotisationAdherent', 'ca', 'WITH', $alias . '.id = ca.id')
                        ->leftJoin('c.expediteur', 'e')
                        ->leftJoin('ca.expediteur', 'f')
                        ->andWhere('e.groupe = :groupe OR f.groupe = :groupe')
                        ->setParameter('groupe', $value['value']);

                    return true;
                },
                'advanced_filter' => false,
                'show_filter' => true,
                'field_type' => ChoiceType::class,
                'field_options' => [
                    'choices' => $em->getRepository(Groupe::class)->findBy(['enabled' => true], ['name' => 'ASC']),
                    'choice_label' => 'name',
                    'placeholder' => 'Indifférent',
                    'expanded' => false,
                    'multiple' => false,
                ],
            ])
Julien Jorry committed
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
            ->add('cotisationInfos.recu', null, [
                'label' => 'Recu ?',
                'show_filter' => true,
                'advanced_filter' => false,
            ])
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $cotisation = $this->getSubject();
        $now = new \DateTime();
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        $formMapper
            ->with('Cotisation', ['class' => 'col-md-8'])
                ->add('parenttype', HiddenType::class, [
                    'data' => Flux::TYPE_COTISATION,
                ])
                ->add('operateur', HiddenType::class, [
                    'data' => $this->security->getUser(),
                    'data_class' => null,
                    'entity_class' => User::class,
                    'em' => $em,
                ])
                ->add('montant', MoneyType::class, [
                    'label' => 'Montant en euro(s)',
                    'scale' => 2,
                    'required' => true,
                    'constraints' => [
                        new Regex(['pattern' => '/[0-9]{1,}(\.[0-9]{1,2})?/']),
                    ],
                    'empty_data' => (float) 0.0,
                ])
                ->add('role', HiddenType::class, [
                    'data' => $this->security->getUser() ? $this->security->getUser()->getGroups()[0]->__toString() : '',
                ])
                ->add('destinataire', HiddenType::class, [
                    'data' => $em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]),
                    'data_class' => null,
                    'entity_class' => Prestataire::class,
                    'em' => $em,
                ])
                ->add('moyen', ChoiceType::class, [
                    'required' => true,
                    'choices' => MoyenEnum::getAvailableTypes(),
                    'choice_label' => function ($choice) {
                        return MoyenEnum::getTypeName($choice);
                    },
                ])
        ;
148
        if (null != $this->security->getUser() && ($this->security->isGranted('ROLE_SUPER_ADMIN') || $this->security->isGranted('ROLE_TRESORIER'))) {
Julien Jorry committed
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
            $formMapper
                ->add('cotisationInfos.recu', CheckboxType::class, [
                    'label' => 'Paiement bien reçu',
                    'required' => false,
                ]);
        }
        $formMapper->end()
            ->with('Date', ['class' => 'col-md-4'])
                ->add('cotisationInfos.annee', null, [
                    'label' => 'Année',
                    'required' => false,
                ])
                ->add('cotisationInfos.debut', DateType::class, [
                    'label' => 'Date de début',
                    'widget' => 'single_text',
                    'required' => true,
                    // 'html5' => false,
                    'format' => 'yyyy-MM-dd',
                    'attr' => ['class' => 'js-datepicker'],
                ])
                ->add('cotisationInfos.fin', DateType::class, [
                    'label' => 'Date de fin',
                    'widget' => 'single_text',
                    // 'html5' => false,
                    'format' => 'yyyy-MM-dd',
                    'attr' => ['class' => 'js-datepicker'],
                ])
            ->end()
        ;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        $collection->remove('delete');
183
        if (null != $this->security->getUser() && !($this->security->isGranted('ROLE_TRESORIER') || $this->security->isGranted('ROLE_SUPER_ADMIN') || $this->security->isGranted('ROLE_COMPTOIR'))) {
Julien Jorry committed
184 185 186 187 188 189 190 191 192
            $collection->clearExcept(['list', 'export']);
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $listMapper)
    {
193 194 195 196 197 198 199 200
        // In TAV env, block access to standard cotisations admin.
        // TODO: find a better way (eg. block access with App\EventListener\MenuBuilderListener?)
        if ($this->getConfigurationPool()->getContainer()->getParameter('tav_env')) {
            $url = $this->getConfigurationPool()->getContainer()->get( 'router' )->generate( 'sonata_admin_dashboard' );
            $redirection = new RedirectResponse( $url );
            $redirection->send();
        }

Julien Jorry committed
201 202 203 204 205
        unset($this->listModes['mosaic']);
        $listMapper
            ->add('id', 'text', [
                'template' => '@kohinos/bundles/SonataAdminBundle/Block/cotisation_obj.html.twig',
            ])
206 207 208
            ->add('expediteur.groupe.name', null, [
                'label' => 'Groupe',
            ])
Julien Jorry committed
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
            ->add('cotisationInfos.annee', null, [
                'label' => 'Année',
            ])
            ->add('montant', 'decimal', [
                'label' => 'Montant',
                'attributes' => ['fraction_digits' => 2],
            ])
            ->add('moyen', null, [
                'label' => 'Moyen',
            ])
            ->add('cotisationInfos.debut', null, [
                'label' => 'Crée le',
            ])
            ->add('cotisationInfos.fin', null, [
                'label' => 'Expire le',
            ])
            ->add('cotisationInfos.recu', null, [
                'label' => 'Paiement bien reçu ?',
                'editable' => true,
            ])
            ->add('operateurAndRole', null, [
                'label' => 'Opérateur',
            ])
            ->add('_action', null, [
                'actions' => [
                    'edit' => [],
                ],
            ])
        ;
    }
239 240 241 242 243 244 245 246 247

    public function getDataSourceIterator()
    {
        $iterator = parent::getDataSourceIterator();
        $iterator->setDateTimeFormat('d/m/Y H:i:s'); //change this to suit your needs

        return $iterator;
    }

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
    public function prePersist($cotisation)
    {
        try {
            if ($cotisation->getCotisationInfos()->isRecu()) {
                $this->operationUtils->executeOperations($cotisation);
            }
        } catch (\Exception $e) {
            throw new BalanceInsufficientException($e->getMessage());
        }
    }

    /** Overwrite create methode to catch custom error */
    public function create($object)
    {
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
        try {
            $em->beginTransaction();
            $res = parent::create($object);
            $em->getConnection()->commit();

            return $res;
        } catch (BalanceInsufficientException $e) {
            $em->getConnection()->rollBack();

            $this->getConfigurationPool()->getContainer()->get('session')->getFlashBag()->add('error', $e->getMessage());
273

274 275 276 277
            return null;
        }
    }

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    public function getExportFields()
    {
        return [
            'Id' => 'expediteur',
            'Groupe' => 'expediteur.groupe.name',
            'Annee' => 'cotisationInfos.annee',
            'Type' => 'type',
            'Montant' => 'montant',
            'Moyen' => 'moyen',
            'Crée le' => 'cotisationInfos.debut',
            'Expire le' => 'cotisationInfos.fin',
            'Reçu ?' => 'cotisationInfos.recu',
            'Operateur' => 'operateurAndRole',
            'Reference' => 'reference',
            'Date' => 'created_at',
        ];
    }
Julien Jorry committed
295
}