Commit 2b4b5cc4 by Julien Jorry

BUG UPDATE BACK OFFICE : adherent / presta / flux / transaction / transfert /…

BUG UPDATE BACK OFFICE : adherent / presta / flux / transaction / transfert / cotisations / roles...
parent ca67eb4f
......@@ -63,6 +63,10 @@ security:
path: fos_user_security_logout
target: fos_user_security_login
anonymous: true
guard:
authenticators:
- App\Security\EmailTokenAuthenticator
provider: fos_userbundle
remember_me:
secret: "%kernel.secret%"
lifetime: 31536000
......
......@@ -132,7 +132,6 @@ sonata_admin:
label: Utilisateurs
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-users"></i>'
roles: [ ROLE_SUPER_ADMIN, ROLE_ADMIN_SIEGE ]
items:
- sonata.user.admin.user
- sonata.user.admin.group
......@@ -141,7 +140,6 @@ sonata_admin:
label: Média
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-image"></i>'
roles: [ ROLE_SUPER_ADMIN, ROLE_ADMIN_SIEGE ]
items:
- sonata.media.admin.media
- sonata.media.admin.gallery
......@@ -150,7 +148,6 @@ sonata_admin:
label: Adhérents
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-address-card"></i>'
roles: [ ROLE_SUPER_ADMIN, ROLE_ADMIN_SIEGE, ROLE_TRESORIER, ROLE_GESTION_GROUPE, ROLE_COMPTOIR, ROLE_CONTACT ]
items:
- admin.adherent.gerer
- admin.adherent.cotisations
......@@ -159,10 +156,8 @@ sonata_admin:
label: Prestataires
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-user-circle-o"></i>'
roles: [ ROLE_SUPER_ADMIN, ROLE_ADMIN_SIEGE, ROLE_TRESORIER, ROLE_GESTION_GROUPE, ROLE_COMPTOIR, ROLE_CONTACT ]
items:
- admin.prestataire.gerer
# - admin.prestataired.gerer
- admin.prestataire.cotisations
- admin.groupepresta.gerer
sonata.admin.group.groupe:
......@@ -170,7 +165,6 @@ sonata_admin:
label: Groupes locaux
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-bandcamp"></i>'
roles: [ ROLE_SUPER_ADMIN, ROLE_ADMIN_SIEGE ]
items:
- admin.groupe.gerer
sonata.admin.group.comptoir:
......@@ -178,7 +172,6 @@ sonata_admin:
label: "Comptoirs"
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-home"></i>'
roles: [ ROLE_SUPER_ADMIN, ROLE_ADMIN_SIEGE ]
items:
- admin.comptoir.gerer
# sonata.admin.group.compta:
......@@ -187,7 +180,6 @@ sonata_admin:
# label: "Comptabilité"
# label_catalogue: SonataAdminBundle
# icon: '<i class="fa fa-list"></i>'
# roles: [ ROLE_SUPER_ADMIN, ROLE_ADMIN_SIEGE, ROLE_TRESORIER ]
# items:
# - admin.flux.gerer
sonata.admin.group.document:
......@@ -196,7 +188,6 @@ sonata_admin:
label: "Documents"
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-file-text"></i>'
roles: [ ROLE_SUPER_ADMIN, ROLE_ADMIN_SIEGE, ROLE_TRESORIER, ROLE_GESTION_GROUPE, ROLE_COMPTOIR, ROLE_CONTACT, ROLE_REDACTEUR ]
items:
- admin.document.gerer
sonata.admin.group.rubrique:
......@@ -205,7 +196,6 @@ sonata_admin:
label: "Rubriques"
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-list"></i>'
roles: [ ROLE_SUPER_ADMIN, ROLE_ADMIN_SIEGE, ROLE_TRESORIER, ROLE_GESTION_GROUPE, ROLE_COMPTOIR, ROLE_CONTACT, ROLE_REDACTEUR ]
items:
- admin.rubrique.gerer
sonata.admin.group.faq:
......@@ -214,7 +204,6 @@ sonata_admin:
label: "FAQ"
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-question"></i>'
roles: [ ROLE_SUPER_ADMIN, ROLE_ADMIN_SIEGE, ROLE_TRESORIER, ROLE_GESTION_GROUPE, ROLE_COMPTOIR, ROLE_CONTACT, ROLE_REDACTEUR ]
items:
- admin.faq.gerer
sonata.admin.group.traduction:
......@@ -223,9 +212,16 @@ sonata_admin:
label: "Traductions"
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-flag"></i>'
roles: [ ROLE_SUPER_ADMIN, ROLE_ADMIN_SIEGE, ROLE_REDACTEUR ]
items:
- admin.traduction.gerer
sonata.admin.group.flux:
keep_open: false
on_top: true
label: "Flux"
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-euro"></i>'
items:
- admin.flux.gerer
# Gérer l'affichage du menu de l'admin en fonction des roles
# groups:
......
......@@ -54,11 +54,12 @@ services:
tags:
- { name: doctrine.event_listener, event: preUpdate }
# Configuration de l'admin
###### Configuration de l'admin ######
admin.adherent.gerer:
class: App\Admin\AdherentAdmin
# arguments: [~, App\Entity\OBJECT, 'PixSortableBehaviorBundle:SortableAdmin']
arguments: [~, App\Entity\User, 'App\Controller\CRUD\CRUDController']
arguments: [~, App\Entity\Adherent, 'App\Controller\CRUD\CRUDController']
tags:
- name: sonata.admin
manager_type: orm
......@@ -81,26 +82,26 @@ services:
label: "Cotisation"
public: true
# admin.prestataire.gerer:
# class: App\Admin\PrestataireoldAdmin
# arguments: [~, App\Entity\User, 'App\Controller\CRUD\CRUDController']
# tags:
# - name: sonata.admin
# manager_type: orm
# group: "Prestataire"
# label: "Gérer"
# public: true
# calls:
# - [ setUserManager, ['@fos_user.user_manager']]
admin.prestataire.gerer:
class: App\Admin\PrestataireAdmin
arguments: [~, App\Entity\User, 'App\Controller\CRUD\CRUDController']
tags:
- name: sonata.admin
manager_type: orm
group: "Prestataire"
label: "Gérer"
public: true
calls:
- [ setUserManager, ['@fos_user.user_manager']]
admin.prestataired.gerer:
class: App\Admin\PrestataireDAdmin
arguments: [~, App\Entity\Prestataire, ~]
tags:
- name: sonata.admin
manager_type: orm
group: "Prestataire"
label: "Gérer 2"
label: "Gérer"
public: true
calls:
- [ setUserManager, ['@fos_user.user_manager']]
......@@ -184,6 +185,16 @@ services:
label: "Traductions"
public: true
admin.flux.gerer:
class: App\Admin\FluxAdmin
arguments: [~, App\Entity\Flux, ~]
tags:
- name: sonata.admin
manager_type: orm
group: "Flux"
label: "Flux"
public: true
# admin.flux.gerer:
# class: App\Admin\FluxAdmin
# arguments: [~, App\Entity\Transaction, ~]
......
......@@ -28,18 +28,18 @@ App\Entity\Comptoir:
geoloc (unique): '@geoloc*'
App\Entity\Groupeprestataire:
grppresta_1:
grppresta1:
name: 'AMAP de test'
horaires: 'Tous les Jeudis<br/>de 12h à 14h'
grppresta_2:
horaires: Tous les Jeudis de 12h à 14h
grppresta2:
name: 'AMAP de test 2'
horaires: 'Tous les Mercredis<br/>de 12h à 14h'
grppresta_3:
horaires: Tous les Mercredis de 12h à 14h
grppresta3:
name: 'Marché de test'
horaires: 'Tous les Dimanches<br/>de 8h à 12h'
grppresta_4:
horaires: Tous les Dimanches de 8h à 12h
grppresta4:
name: 'Marché de test 2'
horaires: 'Tous les 1er Dimanches du mois<br/>de 8h à 12h<br/>et de 18h à 20h'
horaires: Tous les 1er Dimanches du mois de 8h à 12h et de 18h à 20h
App\Entity\TypePrestataire:
typepresta_prestataire:
......@@ -57,7 +57,16 @@ App\Entity\Usergroup:
usergroup_redacteur:
__construct: ['Rédacteur', ['ROLE_REDACTEUR']]
usergroup_tresorier:
__construct: ['Trésorier', ['ROLE_TRESORIER']]
__construct: ['Trésorier', [
'ROLE_TRESORIER',
'ROLE_ADMIN_ADHERENT_GERER_ALL',
'ROLE_ADMIN_ADHERENT_COTISATIONS_ALL',
'ROLE_ADMIN_PRESTATAIRE_GERER_ALL',
'ROLE_ADMIN_PRESTATAIRE_COTISATIONS_ALL',
'ROLE_ADMIN_DOCUMENT_GERER_ALL',
'ROLE_ADMIN_RUBRIQUE_GERER_ALL',
'ROLE_ADMIN_FAQ_GERER_ALL',
'ROLE_ADMIN_FLUX_GERER_ALL']]
usergroup_gestiongroupe:
__construct: ['Gestionnaire de Groupe', ['ROLE_GESTION_GROUPE']]
usergroup_comptoir:
......@@ -65,7 +74,7 @@ App\Entity\Usergroup:
usergroup_contact:
__construct: ['Contact', ['ROLE_CONTACT']]
usergroup_admin:
__construct: ['Admin', ['ROLE_ADMIN']]
__construct: ['Admin', ['ROLE_ADMIN', 'ROLE_SUPER_ADMIN']]
usergroup_superadmin:
__construct: ['Super Admin', ['ROLE_SUPER_ADMIN']]
......@@ -96,7 +105,7 @@ App\Entity\Prestataire:
geoloc (unique): '@geoloc*'
# user (unique): '@user<numberBetween(11,30)>'
typeprestataire: '@typepresta_prestataire*'
groupeprestataires: ['@grppresta_*']
groupeprestataires: ['@grppresta<numberBetween(1, 4)>']
horaires: "<dayOfWeek()> de <time('H')>h à <time('H')>h"
App\Entity\User:
......@@ -169,22 +178,114 @@ App\Entity\User:
email: 'adherent@doume.test'
plainPassword: 'test'
enabled: true
# groups: ['@usergroup_adherent']
groups: ['@usergroup_adherent']
roles: ['ROLE_ADHERENT']
adherent: '@adherent1'
user{1..10}:
usera{2..11}:
username: 'a<userName()>'
email: <email()>
plainPassword: 'test'
enabled: true
# groups: ['@usergroup_adherent']
groups: ['@usergroup_adherent']
roles: ['ROLE_ADHERENT']
adherent (unique): '@adherent<numberBetween(2,11)>'
user{11..30}:
username: 'b<userName()>'
adherent: '@adherent<current()>'
userp{1..32}:
username: 'p<userName()>'
email: <email()>
plainPassword: 'test'
enabled: true
# groups: ['@usergroup_prestataire']
roles: ['ROLE_PRESTATAIRE']
prestataire (unique): '@prestataire<numberBetween(2,21)>'
prestataire (unique): '@prestataire<current()>'
# TEST DE TRANSACTIONS / TRANSFERTS !
App\Entity\TransactionAdherentPrestataire:
tro_adh_pre{2..11}:
operateur: '@usera<current()>'
type: 'adherent_prestataire'
reference: 'test'
montant: '<numberBetween(1,50)>'
expediteur: '@adherent<current()>'
destinataire: '@prestataire*'
createdAt: '<dateTimeBetween("-200 days", "now")>'
parenttype: 'transaction'
App\Entity\TransactionPrestataireAdherent:
tro_pre_adh{1..10}:
operateur: '@userp<current()>'
type: 'prestataire_adherent'
reference: 'test'
montant: '<numberBetween(1,50)>'
expediteur: '@prestataire*'
destinataire: '@adherent<current()>'
createdAt: '<dateTimeBetween("-200 days", "now")>'
parenttype: 'transaction'
App\Entity\TransactionPrestatairePrestataire:
tro_pre_pre{1..10}:
operateur: '@userp<current()>'
type: 'prestataire_prestataire'
reference: 'test'
montant: '<numberBetween(1,50)>'
expediteur: '@prestataire*'
destinataire: '@prestataire*'
createdAt: '<dateTimeBetween("-200 days", "now")>'
parenttype: 'transaction'
App\Entity\TransfertComptoirAdherent:
tre_cpt_adh{1..10}:
operateur: '@usercomptoir'
type: 'comptoir_adherent'
reference: 'test'
montant: '<numberBetween(1,50)>'
expediteur: '@comptoir*'
destinataire: '@adherent<current()>'
createdAt: '<dateTimeBetween("-200 days", "now")>'
parenttype: 'transfert'
App\Entity\TransfertComptoirGroupe:
tre_cpt_grp{1..10}:
operateur: '@usercomptoir'
type: 'comptoir_groupe'
reference: 'test'
montant: '<numberBetween(1,50)>'
expediteur: '@comptoir*'
destinataire: '@groupe*'
createdAt: '<dateTimeBetween("-200 days", "now")>'
parenttype: 'transfert'
App\Entity\TransfertComptoirPrestataire:
tre_cpt_pre{1..10}:
operateur: '@usercomptoir'
type: 'comptoir_prestataire'
reference: 'test'
montant: '<numberBetween(1,50)>'
expediteur: '@comptoir*'
destinataire: '@prestataire*'
createdAt: '<dateTimeBetween("-200 days", "now")>'
parenttype: 'transfert'
App\Entity\TransfertGroupeComptoir:
tre_grp_cpt{1..10}:
operateur: '@usergestiongroupe'
type: 'groupe_comptoir'
reference: 'test'
montant: '<numberBetween(1,50)>'
expediteur: '@groupe*'
destinataire: '@comptoir*'
createdAt: '<dateTimeBetween("-200 days", "now")>'
parenttype: 'transfert'
App\Entity\TransfertPrestataireComptoir:
tre_pre_cpt{1..10}:
operateur: '@userp<current()>'
type: 'prestataire_comptoir'
reference: 'test'
montant: '<numberBetween(1,50)>'
expediteur: '@prestataire*'
destinataire: '@comptoir*'
createdAt: '<dateTimeBetween("-200 days", "now")>'
parenttype: 'transfert'
App\Entity\TransfertSiegeGroupe:
tre_sie_grp{1..10}:
operateur: '@useradminsiege'
type: 'siege_groupe'
reference: 'test'
montant: '<numberBetween(1,50)>'
expediteur: '@siege'
destinataire: '@groupe*'
createdAt: '<dateTimeBetween("-200 days", "now")>'
parenttype: 'transfert'
......@@ -3,8 +3,14 @@
namespace App\Admin;
use App\Entity\Adherent;
use App\Entity\Cotisation;
use App\Entity\Geoloc;
use App\Entity\User;
use App\Entity\Usergroup;
use App\Enum\MoyenEnum;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\FOSUserEvents;
use Knp\Menu\ItemInterface as MenuItemInterface;
use Knp\Menu\ItemInterface;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\AdminInterface;
......@@ -12,21 +18,26 @@ use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\UserBundle\Model\UserManagerInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
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\TextType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class AdherentAdmin extends UserAdmin
class AdherentAdmin extends AbstractAdmin
{
protected $baseRouteName = 'adherent';
protected $baseRoutePattern = 'adherent';
protected $datagridValues = [
// reverse order (default = 'ASC')
'_sort_order' => 'DESC',
'_sort_order' => 'ASC',
// name of the ordered field (default = the model's id field, if any)
'_sort_by' => 'ecompte',
'_sort_by' => 'createdAt',
// '_page' => 1,
// '_per_page' => 32
];
......@@ -36,20 +47,145 @@ class AdherentAdmin extends UserAdmin
parent::configure();
}
protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
{
if (!$childAdmin && !in_array($action, ['edit', 'show'])) {
return;
}
$admin = $this->isChild() ? $this->getParent() : $this;
$id = $admin->getRequest()->get('id');
$user = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(User::class)->findOneBy(array('adherent' => $id));
if ($this->isGranted('EDIT') && $user != null) {
$menu->addChild('Edit User', [
'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('admin_app_user_edit', ['id' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL)
]);
}
}
/**
* {@inheritdoc}
*/
protected function configureFormFields(FormMapper $formMapper): void
{
parent::configureFormFields($formMapper);
// Initialize adherent
$user = $this->getSubject();
$adherent = $this->getSubject();
$user = $this->userManager->createUser();
$groupe = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Adherent');
$user->setEnabled(true);
$user->addGroup($groupe);
$user->addRole('ROLE_ADHERENT');
$adherent = new Adherent();
$adherent->setGeoloc(new Geoloc());
$adherent->setEcompte('0');
$now = new \DateTime();
$cotisation = new Cotisation();
$cotisation->setDebut($now);
$cotisation->setFin(new \DateTime('+ 1 year'));
$user->addCotisation($cotisation);
$user->setAdherent($adherent);
$adherent->setUser($user);
//nom, prénom, adresse, tel, mail et cotisation en une seule fois et générer un mdp
$formMapper
->tab('General')
->with('Identité', ['class' => 'col-md-7'])
->add('user.firstname', TextType::class, array(
'label' => 'Prénom :',
'required' => true
))
->add('user.lastname', TextType::class, array(
'label' => 'Nom :',
'required' => true
))
// ->add('user.username', TextType::class, array(
// 'label' => 'Username :',
// 'required' => true,
// 'disabled' => true
// ))
->add('user.phone', TextType::class, array(
'label' => 'Téléphone :',
'required' => true
))
->add('user.email', TextType::class, array(
'label' => 'Email :',
'required' => true
))
->end()
->with('Cotisation', ['class' => 'col-md-5'])
->add('user.cotisations.first.annee', TextType::class, array('label' => 'Année', 'data' => $now->format('Y')))
->add('user.cotisations.first.montant', TextType::class, array('label' => 'Montant'))
->add('user.cotisations.first.moyen', ChoiceType::class, array(
'required' => true,
'choices' => MoyenEnum::getAvailableTypes(),
'choices_as_values' => true,
'choice_label' => function ($choice) {
return MoyenEnum::getTypeName($choice);
},
))
->add('user.cotisations.first.recu', CheckboxType::class, array('label' => 'Reçu'))
->end()
// ->with('Date', ['class' => 'col-md-5'])
// ->add('user.cotisations.first.debut', DateType::class, array(
// 'label' => 'Date de début',
// 'data' => new \DateTime(),
// 'widget' => 'single_text',
// 'html5' => false,
// 'attr' => ['class' => 'js-datepicker'],
// ))
// ->add('user.cotisations.first.fin', DateType::class, array(
// 'label' => 'Date de fin',
// 'data' => new \DateTime('+ 1 year'),
// 'widget' => 'single_text',
// 'html5' => false,
// 'attr' => ['class' => 'js-datepicker'],
// ))
// ->end()
->with('Addresse', ['class' => 'col-md-7'])
->add('geoloc.adresse', TextType::class, array(
'label' => 'Addresse :',
'required' => true
))
->add('geoloc.cpostal', TextType::class, array(
'label' => 'Code postal :',
'required' => true
))
->add('geoloc.ville', TextType::class, array(
'label' => 'Ville :',
'required' => true
))
->end()
->end()
;
parent::configureFormFields($formMapper);
}
public function preUpdate($adherent)
{
$this->prePersist($adherent);
}
public function prePersist($adherent)
{
$em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
if (empty($adherent->getUser()->getUsername())) {
$adherent->getUser()->setUsername($adherent->getUser()->getEmail());
}
if (empty($adherent->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), '+/', '-_'), '=');
$adherent->getUser()->setPassword($password);
// send email to user
}
$this->userManager->updateUser($adherent->getUser());
$adherent->getUser()->createEmailToken();
$em->persist($adherent->getUser());
$em->persist($adherent);
$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));
}
/**
......@@ -57,32 +193,66 @@ class AdherentAdmin extends UserAdmin
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
{
parent::configureDatagridFilters($datagridMapper);
$datagridMapper
->add('user.username', null, array('label' => 'Login'))
->add('user.email', null, array('label' => 'Email'))
;
}
/**
* @param EventDispatcherInterface $userManager
*/
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->eventDispatcher = $eventDispatcher;
}
/**
* @return EventDispatcherInterface
*/
public function getEventDispatcher()
{
return $this->eventDispatcher;
}
/**
* @param UserManagerInterface $userManager
*/
public function setUserManager(UserManagerInterface $userManager): void
{
$this->userManager = $userManager;
}
/**
* @return UserManagerInterface
*/
public function getUserManager()
{
return $this->userManager;
}
protected function configureListFields(ListMapper $listMapper): void
{
unset($this->listModes['mosaic']);
$listMapper
->addIdentifier('username')
->addIdentifier('email')
->addIdentifier('adherent.ecompte', null, array('label' => 'Ecompte'))
->add('groups')
->addIdentifier('enabled', null, array('label' => 'Activé', 'datatype' => 'App.User', 'template' => '@SonataAdmin/Boolean/editable_boolean.html.twig'))
// ->addIdentifier('createdAt')
->addIdentifier('user.username', null, array('label' => 'Login'))
->addIdentifier('user.email', null, array('label' => 'Email'))
->addIdentifier('ecompte', null, array('label' => 'Ecompte'))
->add('user.groups')
->addIdentifier('user.enabled', null, array('label' => 'Activé', 'datatype' => 'App.User', 'template' => '@SonataAdmin/Boolean/editable_boolean.html.twig'))
->addIdentifier('user.createdAt')
;
if ($this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
$listMapper
->addIdentifier('impersonating', 'string', ['template' => '@SonataUser/Admin/Field/impersonating.html.twig'])
;
}
// if ($this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
// $listMapper
// ->addIdentifier('impersonating', 'string', ['template' => '@SonataUser/Admin/Field/impersonating.html.twig'])
// ;
// }
}
protected function configureRoutes(RouteCollection $collection)
{
// $collection->remove('delete');
$collection->remove('delete');
}
/**
......@@ -91,14 +261,16 @@ class AdherentAdmin extends UserAdmin
public function createQuery($context = 'list')
{
$query = parent::createQuery($context);
$role = 'ROLE_ADHERENT';
// $query->andWhere($query->getRootAliases()[0] . '.adherent IS NOT NULL');
$query->leftJoin($query->getRootAliases()[0] . '.groups', 'g')
->where($query->expr()->orX(
$query->expr()->like($query->getRootAliases()[0] . '.roles', ':roles'),
$query->expr()->like('g.roles', ':roles')
))
->setParameter('roles', '%"'.$role.'"%');
$query->innerJoin($query->getRootAliases()[0] .'.user', 'u')
->addSelect('u');
// $role = 'ROLE_ADHERENT';
// // $query->andWhere($query->getRootAliases()[0] . '.adherent IS NOT NULL');
// $query->leftJoin($query->getRootAliases()[0] . '.groups', 'g')
// ->where($query->expr()->orX(
// $query->expr()->like($query->getRootAliases()[0] . '.roles', ':roles'),
// $query->expr()->like('g.roles', ':roles')
// ))
// ->setParameter('roles', '%"'.$role.'"%');
return $query;
}
}
<?php
namespace App\Admin;
use App\Entity\Adherent;
use App\Entity\Geoloc;
use App\Entity\Usergroup;
use Knp\Menu\ItemInterface;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class AdherentAdminold extends UserAdmin
{
protected $baseRouteName = 'adherento';
protected $baseRoutePattern = 'adherento';
protected $datagridValues = [
// reverse order (default = 'ASC')
'_sort_order' => 'DESC',
// name of the ordered field (default = the model's id field, if any)
'_sort_by' => 'ecompte',
// '_page' => 1,
// '_per_page' => 32
];
public function configure()
{
parent::configure();
}
/**
* {@inheritdoc}
*/
protected function configureFormFields(FormMapper $formMapper): void
{
parent::configureFormFields($formMapper);
// Initialize adherent
$user = $this->getSubject();
$groupe = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Adherent');
$user->setEnabled(true);
$user->addGroup($groupe);
$user->addRole('ROLE_ADHERENT');
$adherent = new Adherent();
$user->setAdherent($adherent);
}
/**
* {@inheritdoc}
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
{
parent::configureDatagridFilters($datagridMapper);
}
protected function configureListFields(ListMapper $listMapper): void
{
unset($this->listModes['mosaic']);
$listMapper
->addIdentifier('username')
->addIdentifier('email')
->addIdentifier('adherent.ecompte', null, array('label' => 'Ecompte'))
->add('groups')
->addIdentifier('enabled', null, array('label' => 'Activé', 'datatype' => 'App.User', 'template' => '@SonataAdmin/Boolean/editable_boolean.html.twig'))
// ->addIdentifier('createdAt')
;
if ($this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
$listMapper
->addIdentifier('impersonating', 'string', ['template' => '@SonataUser/Admin/Field/impersonating.html.twig'])
;
}
}
protected function configureRoutes(RouteCollection $collection)
{
// $collection->remove('delete');
}
/**
* {@inheritdoc}
*/
public function createQuery($context = 'list')
{
$query = parent::createQuery($context);
$role = 'ROLE_ADHERENT';
// $query->andWhere($query->getRootAliases()[0] . '.adherent IS NOT NULL');
$query->leftJoin($query->getRootAliases()[0] . '.groups', 'g')
->where($query->expr()->orX(
$query->expr()->like($query->getRootAliases()[0] . '.roles', ':roles'),
$query->expr()->like('g.roles', ':roles')
))
->setParameter('roles', '%"'.$role.'"%');
return $query;
}
}
......@@ -2,11 +2,14 @@
namespace App\Admin;
use App\Enum\MoyenEnum;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Show\ShowMapper;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
class CotisationAdmin extends AbstractAdmin
{
......@@ -26,14 +29,20 @@ class CotisationAdmin extends AbstractAdmin
protected function configureFormFields(FormMapper $formMapper)
{
$cotisation = $this->getSubject();
$now = new \DateTime();
$formMapper
->with('Cotisation', ['class' => 'col-md-8'])
// ->add('user', null, array('label' => 'Utilisateur'), array('admin_code' => 'admin.adherent.gerer'))
->add('type', null, array('label' => 'Type'))
->add('annee', null, array('label' => 'Année'))
->add('annee', null, array('label' => 'Année', 'data' => $now->format('Y')))
->add('montant', null, array('label' => 'Montant'))
->add('moyen', null, array('label' => 'Moyen'))
->add('recu', null, array('label' => 'Reçu'))
->add('moyen', ChoiceType::class, array(
'required' => true,
'choices' => MoyenEnum::getAvailableTypes(),
// 'choices_as_values' => true,
'choice_label' => function ($choice) {
return MoyenEnum::getTypeName($choice);
},
))
->add('user.cotisations.first.recu', CheckboxType::class, array('label' => 'Reçu'))
->end()
->with('Date', ['class' => 'col-md-4'])
->add('debut', null, array(
......@@ -42,16 +51,14 @@ class CotisationAdmin extends AbstractAdmin
'widget' => 'single_text',
'html5' => false,
'attr' => ['class' => 'js-datepicker'],
)
)
))
->add('fin', null, array(
'label' => 'Date de fin',
'data' => new \DateTime('+ 1 year'),
'widget' => 'single_text',
'html5' => false,
'attr' => ['class' => 'js-datepicker'],
)
)
))
->end()
;
}
......@@ -70,7 +77,6 @@ class CotisationAdmin extends AbstractAdmin
unset($this->listModes['mosaic']);
$listMapper
// ->addIdentifier('user')
->addIdentifier('type')
->addIdentifier('annee')
->addIdentifier('debut')
->addIdentifier('fin')
......
<?php
namespace App\Admin;
use App\Entity\User;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Form\Type\Filter\ChoiceType;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Show\ShowMapper;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType as SChoiceType;
class FluxAdmin extends AbstractAdmin
{
protected $datagridValues = [
'_sort_order' => 'DESC',
'_sort_by' => 'createdAt',
];
/**
* {@inheritdoc}
*/
protected function configureRoutes(RouteCollection $collection)
{
$collection->clearExcept('list');
}
/**
* {@inheritdoc}
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
{
$datagridMapper
->add('type', null, array(
'label' => 'Type',
'advanced_filter' => false,
'show_filter' => true
))
->add('transfert_or_transaction', 'doctrine_orm_callback', array(
'label' => "Transfert ou transaction ?",
'callback' => function ($queryBuilder, $alias, $field, $value) {
if (!$value['value']) {
return;
}
$queryBuilder
->where($alias.".parenttype = :type")
->setParameter('type', $value['value']);
return true;
},
'advanced_filter' => false,
'show_filter' => true,
'field_type' => SChoiceType::class,
'field_options' => array(
'choices' => array('Transactions' => 'transaction', 'Transferts' => 'transfert'),
'placeholder' => 'Indifférent',
'expanded' => true,
'multiple' => false
)
))
->add('operateur', null, array(
'label' => 'Operateur',
'advanced_filter' => false,
'show_filter' => true
))
;
}
public function getTemplate($name)
{
if ($name == 'list') {
return 'block/fluxlist.html.twig';
}
return parent::getTemplate($name);
}
public function getTotalTransaction()
{
$datagrid = $this->getDatagrid();
$datagrid->buildPager();
$query = $datagrid->getQuery();
$query
->select('SUM( ' . $query->getRootAlias() . '.montant) as total')
->where($query->getRootAlias().".parenttype = :type")
->setParameter('type', 'transaction')
->setFirstResult(null)
->setMaxResults(null);
$result = $query->execute(array(), \Doctrine\ORM\Query::HYDRATE_SINGLE_SCALAR);
return $result;
}
/**
* {@inheritdoc}
*/
protected function configureListFields(ListMapper $listMapper)
{
unset($this->listModes['mosaic']);
$listMapper
->addIdentifier('type', null, array('label' => 'Type'))
->addIdentifier('createdAt', null, array('label' => 'Date'))
->addIdentifier('operateur', User::class, array('label' => 'Operateur'))
// ->addIdentifier('expediteur', null, array('label' => 'Expediteur'))
->addIdentifier('expediteur', null, array('label' => 'Expediteur'))//, 'template' => 'block/flux_entity.html.twig'))
->addIdentifier('destinataire', null, array('label' => 'Destinataire'))
->addIdentifier('montant', null, array('label' => 'Montant'))
->addIdentifier('reference', null, array('label' => 'Reference'))
;
}
}
......@@ -3,10 +3,17 @@
namespace App\Admin;
use App\Admin\UserAdmin;
use App\Entity\Cotisation;
use App\Entity\Geoloc;
use App\Entity\Prestataire;
use App\Entity\User;
use App\Entity\Usergroup;
use App\Enum\MoyenEnum;
use Doctrine\ORM\Query;
use FOS\UserBundle\Model\UserManagerInterface;
use Knp\Menu\ItemInterface as MenuItemInterface;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
......@@ -14,11 +21,14 @@ use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\MediaBundle\Form\Type\MediaType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class PrestataireAdmin extends UserAdmin
class PrestataireAdmin extends AbstractAdmin
{
protected $baseRouteName = 'prestataire';
protected $baseRoutePattern = 'prestataire';
......@@ -28,20 +38,44 @@ class PrestataireAdmin extends UserAdmin
parent::configure();
}
protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
{
if (!$childAdmin && !in_array($action, ['edit', 'show'])) {
return;
}
$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) {
$menu->addChild('Edit User', [
'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('admin_app_user_edit', ['id' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL)
]);
}
}
/**
* {@inheritdoc}
*/
protected function configureFormFields(FormMapper $formMapper): void
{
// Initialize prestataire
$user = $this->getSubject();
$presta = $this->getSubject();
$user = $this->userManager->createUser();
$groupe = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Prestataire');
$user->setEnabled(true);
$user->addGroup($groupe);
$user->addRole('ROLE_PRESTATAIRE');
$presta = new Prestataire();
// $presta = new Prestataire();
$presta->setGeoloc(new Geoloc());
$now = new \DateTime();
$cotisation = new Cotisation();
$cotisation->setDebut($now);
$cotisation->setFin(new \DateTime('+ 1 year'));
$user->addCotisation($cotisation);
$user->setPrestataire($presta);
$presta->setUser($user);
// get the current Image instance
$imageHelp = null;
......@@ -58,61 +92,91 @@ class PrestataireAdmin extends UserAdmin
$formMapper
->tab('Prestataire')
->with('General', ['class' => 'col-md-7'])
->add('prestataire.raison', TextType::class, array(
->with('Identité', ['class' => 'col-md-7'])
->add('user.firstname', TextType::class, array(
'label' => 'Prénom :',
'required' => true
))
->add('user.lastname', TextType::class, array(
'label' => 'Nom :',
'required' => true
))
->add('user.phone', TextType::class, array(
'label' => 'Téléphone :',
'required' => true
))
->add('user.email', TextType::class, array(
'label' => 'Email :',
'required' => true
))
->end()
->with('Cotisation', ['class' => 'col-md-5'])
->add('user.cotisations.first.annee', TextType::class, array('label' => 'Année', 'data' => $now->format('Y')))
->add('user.cotisations.first.montant', TextType::class, array('label' => 'Montant'))
->add('user.cotisations.first.moyen', ChoiceType::class, array(
'required' => true,
'choices' => MoyenEnum::getAvailableTypes(),
// 'choices_as_values' => true,
'choice_label' => function ($choice) {
return MoyenEnum::getTypeName($choice);
},
))
->add('user.cotisations.first.recu', CheckboxType::class, array('label' => 'Reçu'))
->end()
->with('Société', ['class' => 'col-md-7'])
->add('raison', TextType::class, array(
'label' => 'Raison :',
'required' => true
))
->add('prestataire.statut', TextType::class, array(
->add('statut', TextType::class, array(
'label' => 'Statut :',
'required' => false
))
->add('prestataire.siret', TextType::class, array(
->add('siret', TextType::class, array(
'label' => 'SIRET :',
'required' => true
))
->add('prestataire.iban', TextType::class, array(
->add('iban', TextType::class, array(
'label' => 'IBAN :',
'required' => true
))
->end()
->with('Responsable', ['class' => 'col-md-5'])
->add('prestataire.metier', TextType::class, array(
'label' => 'Métier :',
'required' => true
))
->add('prestataire.responsable', TextType::class, array(
->add('responsable', TextType::class, array(
'label' => 'Responsable :',
'required' => false
))
->add('metier', TextType::class, array(
'label' => 'Métier responsable :',
'required' => true
))
->end()
->with('Addresse', ['class' => 'col-md-7'])
->add('prestataire.geoloc.adresse', TextType::class, array(
->with('Addresse', ['class' => 'col-md-5'])
->add('geoloc.adresse', TextType::class, array(
'label' => 'Addresse :',
'required' => false
))
->add('prestataire.geoloc.cpostal', TextType::class, array(
->add('geoloc.cpostal', TextType::class, array(
'label' => 'Code postal :',
'required' => false
))
->add('prestataire.geoloc.ville', TextType::class, array(
->add('geoloc.ville', TextType::class, array(
'label' => 'Ville :',
'required' => false
))
->add('prestataire.geoloc.lat', TextType::class, array(
'label' => 'Latitude :',
'required' => false
))
->add('prestataire.geoloc.lon', TextType::class, array(
'label' => 'Longitude :',
'required' => false
))
// ->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('prestataire.media', MediaType::class, array(
->add('media', MediaType::class, array(
'provider' => 'sonata.media.provider.image',
'context' => 'prestataire',
'help' => $imageHelp
'help' => $imageHelp,
'required' => false
))
->end()
->end()
......@@ -120,6 +184,35 @@ class PrestataireAdmin extends UserAdmin
parent::configureFormFields($formMapper);
}
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);
// send email to user
}
$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));
}
/**
* {@inheritdoc}
*/
......@@ -127,8 +220,8 @@ class PrestataireAdmin extends UserAdmin
{
parent::configureDatagridFilters($datagridMapper);
$datagridMapper
->add('prestataire.raison')
->add('prestataire.statut')
->add('raison')
->add('statut')
;
}
......@@ -152,18 +245,18 @@ class PrestataireAdmin extends UserAdmin
{
unset($this->listModes['mosaic']);
$listMapper
->addIdentifier('username')
->addIdentifier('email')
->addIdentifier('prestataire.raison')
->addIdentifier('enabled', null, array('label' => 'Activé', 'datatype' => 'App.User', 'template' => '@SonataAdmin/Boolean/editable_boolean.html.twig'))
->addIdentifier('createdAt')
->addIdentifier('user.username')
->addIdentifier('user.email')
->addIdentifier('raison')
->addIdentifier('user.enabled', null, array('label' => 'Activé', 'datatype' => 'App.User', 'template' => '@SonataAdmin/Boolean/editable_boolean.html.twig'))
->addIdentifier('user.createdAt')
;
if ($this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
$listMapper
->addIdentifier('impersonating', 'string', ['template' => '@SonataUser/Admin/Field/impersonating.html.twig'])
;
}
// if ($this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
// $listMapper
// ->addIdentifier('user.impersonating', 'string', ['template' => '@SonataUser/Admin/Field/impersonating.html.twig'])
// ;
// }
}
protected function configureRoutes(RouteCollection $collection)
......@@ -177,7 +270,9 @@ class PrestataireAdmin extends UserAdmin
public function createQuery($context = 'list')
{
$query = parent::createQuery($context);
$query->andWhere($query->getRootAliases()[0] . '.prestataire IS NOT NULL');
// $query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);
$query->innerJoin($query->getRootAliases()[0] .'.user', 'u')
->addSelect('u');
return $query;
}
}
......@@ -5,13 +5,8 @@ namespace App\Admin;
use App\Admin\UserAdmin;
use App\Entity\Geoloc;
use App\Entity\Prestataire;
use App\Entity\User;
use App\Entity\Usergroup;
use Doctrine\ORM\Query;
use FOS\UserBundle\Model\UserManagerInterface;
use Knp\Menu\ItemInterface as MenuItemInterface;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
......@@ -22,50 +17,29 @@ use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class PrestataireDAdmin extends AbstractAdmin
class PrestataireoldAdmin extends UserAdmin
{
protected $baseRouteName = 'prestataired';
protected $baseRoutePattern = 'prestataired';
protected $baseRouteName = 'prestataireo';
protected $baseRoutePattern = 'prestataireo';
public function configure()
{
parent::configure();
}
protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
{
if (!$childAdmin && !in_array($action, ['edit', 'show'])) {
return;
}
$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) {
$menu->addChild('Edit User', [
'uri' => $this->getConfigurationPool()->getContainer()->get('router')->generate('admin_app_user_edit', ['id' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL)
]);
}
}
/**
* {@inheritdoc}
*/
protected function configureFormFields(FormMapper $formMapper): void
{
// Initialize prestataire
$presta = $this->getSubject();
$user = $this->userManager->createUser();
$user->setEnabled(1); // enable the user or enable it later with a confirmation token in the email
// $this->userManager->updateUser($user);
$user = $this->getSubject();
$groupe = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Prestataire');
$user->setEnabled(true);
$user->addGroup($groupe);
$user->addRole('ROLE_PRESTATAIRE');
// $presta = new Prestataire();
$presta = new Prestataire();
$presta->setGeoloc(new Geoloc());
$user->setPrestataire($presta);
......@@ -85,57 +59,57 @@ class PrestataireDAdmin extends AbstractAdmin
$formMapper
->tab('Prestataire')
->with('General', ['class' => 'col-md-7'])
->add('raison', TextType::class, array(
->add('prestataire.raison', TextType::class, array(
'label' => 'Raison :',
'required' => true
))
->add('statut', TextType::class, array(
->add('prestataire.statut', TextType::class, array(
'label' => 'Statut :',
'required' => false
))
->add('siret', TextType::class, array(
->add('prestataire.siret', TextType::class, array(
'label' => 'SIRET :',
'required' => true
))
->add('iban', TextType::class, array(
->add('prestataire.iban', TextType::class, array(
'label' => 'IBAN :',
'required' => true
))
->end()
->with('Responsable', ['class' => 'col-md-5'])
->add('metier', TextType::class, array(
->add('prestataire.metier', TextType::class, array(
'label' => 'Métier :',
'required' => true
))
->add('responsable', TextType::class, array(
->add('prestataire.responsable', TextType::class, array(
'label' => 'Responsable :',
'required' => false
))
->end()
->with('Addresse', ['class' => 'col-md-7'])
->add('geoloc.adresse', TextType::class, array(
->add('prestataire.geoloc.adresse', TextType::class, array(
'label' => 'Addresse :',
'required' => false
))
->add('geoloc.cpostal', TextType::class, array(
->add('prestataire.geoloc.cpostal', TextType::class, array(
'label' => 'Code postal :',
'required' => false
))
->add('geoloc.ville', TextType::class, array(
->add('prestataire.geoloc.ville', TextType::class, array(
'label' => 'Ville :',
'required' => false
))
->add('geoloc.lat', TextType::class, array(
->add('prestataire.geoloc.lat', TextType::class, array(
'label' => 'Latitude :',
'required' => false
))
->add('geoloc.lon', TextType::class, array(
->add('prestataire.geoloc.lon', TextType::class, array(
'label' => 'Longitude :',
'required' => false
))
->end()
->with('Image', ['class' => 'col-md-5'])
->add('media', MediaType::class, array(
->add('prestataire.media', MediaType::class, array(
'provider' => 'sonata.media.provider.image',
'context' => 'prestataire',
'help' => $imageHelp
......@@ -153,8 +127,8 @@ class PrestataireDAdmin extends AbstractAdmin
{
parent::configureDatagridFilters($datagridMapper);
$datagridMapper
->add('raison')
->add('statut')
->add('prestataire.raison')
->add('prestataire.statut')
;
}
......@@ -178,18 +152,18 @@ class PrestataireDAdmin extends AbstractAdmin
{
unset($this->listModes['mosaic']);
$listMapper
->addIdentifier('user.username')
->addIdentifier('user.email')
->addIdentifier('raison')
->addIdentifier('user.enabled', null, array('label' => 'Activé', 'datatype' => 'App.User', 'template' => '@SonataAdmin/Boolean/editable_boolean.html.twig'))
->addIdentifier('user.createdAt')
->addIdentifier('username')
->addIdentifier('email')
->addIdentifier('prestataire.raison')
->addIdentifier('enabled', null, array('label' => 'Activé', 'datatype' => 'App.User', 'template' => '@SonataAdmin/Boolean/editable_boolean.html.twig'))
->addIdentifier('createdAt')
;
// if ($this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
// $listMapper
// ->addIdentifier('user.impersonating', 'string', ['template' => '@SonataUser/Admin/Field/impersonating.html.twig'])
// ;
// }
if ($this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
$listMapper
->addIdentifier('impersonating', 'string', ['template' => '@SonataUser/Admin/Field/impersonating.html.twig'])
;
}
}
protected function configureRoutes(RouteCollection $collection)
......@@ -203,9 +177,7 @@ class PrestataireDAdmin extends AbstractAdmin
public function createQuery($context = 'list')
{
$query = parent::createQuery($context);
// $query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);
$query->innerJoin('o.user', 'u')
->addSelect('u');
$query->andWhere($query->getRootAliases()[0] . '.prestataire IS NOT NULL');
return $query;
}
}
......@@ -20,6 +20,9 @@ class GroupAdmin extends BaseGroupAdmin
{
protected function configureRoutes(RouteCollection $collection)
{
$subject = $this->getSubject();
if (!empty($subject) && !($subject->isGranted('ROLE_SUPER_ADMIN') || $subject->isGranted('ROLE_ADMIN_SIEGE'))) {
$collection->clearExcept('list');
}
}
}
......@@ -2,6 +2,8 @@
namespace App\Entity;
use App\Entity\EntityTrait\EnablableEntityTrait;
use App\Entity\EntityTrait\GeolocEntityTrait;
use App\Entity\User;
use Doctrine\ORM\Mapping as ORM;
......@@ -10,6 +12,9 @@ use Doctrine\ORM\Mapping as ORM;
*/
class Adherent
{
use EnablableEntityTrait,
GeolocEntityTrait;
/**
* @ORM\Id()
* @ORM\GeneratedValue()
......@@ -25,7 +30,7 @@ class Adherent
/**
* @var User
*
* @ORM\OneToOne(targetEntity="User", cascade={"all"}, mappedBy="adherent")
* @ORM\OneToOne(targetEntity="User", cascade={"all"}, mappedBy="adherent", fetch="EAGER")
*/
protected $user;
......@@ -49,7 +54,7 @@ class Adherent
/**
* @return User
*/
public function getUser(): User
public function getUser(): ?User
{
return $this->user;
}
......@@ -75,4 +80,8 @@ class Adherent
return $this;
}
public function __toString(): string
{
return (!empty($this->getUser() && $this->getUser()->getUsername())?$this->getUser()->getUsername():'Adherent '.$this->getId());
}
}
......@@ -3,6 +3,7 @@
namespace App\Entity;
use App\Entity\User;
use App\Enum\MoyenEnum;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Symfony\Component\Validator\Constraints as Assert;
......@@ -25,13 +26,6 @@ class Cotisation
protected $id;
/**
* @var string
*
* @ORM\Column(name="type", type="string", length=12)
*/
private $type;
/**
* @var int
*
* @ORM\Column(name="annee", type="integer", length=4)
......@@ -62,7 +56,7 @@ class Cotisation
/**
* @var string
*
* @ORM\Column(name="moyen", type="string", length=20)
* @ORM\Column(name="moyen", type="string", length=100)
*/
private $moyen;
......@@ -109,24 +103,6 @@ class Cotisation
}
/**
* @return string
*/
public function getType(): ?string
{
return $this->type;
}
/**
* @param string $type
* @return Cotisation
*/
public function setType(string $type)
{
$this->type = $type;
return $this;
}
/**
* @return int
*/
public function getAnnee(): ?int
......@@ -206,13 +182,13 @@ class Cotisation
return $this->moyen;
}
/**
* @param string $moyen
* @return Cotisation
*/
public function setMoyen(string $moyen)
public function setMoyen($moyen)
{
if (!in_array($moyen, MoyenEnum::getAvailableTypes())) {
throw new \InvalidArgumentException("Moyen de paiement invalide !");
}
$this->moyen = $moyen;
return $this;
}
......
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\User;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity()
*/
class EmailToken
{
/**
* @ORM\Id()
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="emailTokens")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $user;
/**
* @ORM\Column(name="token", type="string", length=255)
*/
private $token;
/**
* @ORM\Column(name="expired_at", type="date")
*/
private $expiredAt;
public function __construct()
{
$bytes = random_bytes(64);
$this->token = rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
$this->expiredAt = new \DateTime('+ 3 days');
}
/**
* Get token
* @return string
*/
public function getToken()
{
return $this->token;
}
/**
* Set token
* @return $this
*/
public function setToken($token)
{
$this->token = $token;
return $this;
}
/**
* Get expiredAt
* @return \DateTime
*/
public function getExpiredAt()
{
return $this->expiredAt;
}
/**
* Set expiredAt
* @return $this
*/
public function setExpiredAt($expiredAt)
{
$this->expiredAt = $expiredAt;
return $this;
}
/**
* Get user
* @return User
*/
public function getUser()
{
return $this->user;
}
/**
* Set user
* @return $this
*/
public function setUser(User $user)
{
$this->user = $user;
return $this;
}
/**
* return true if the token is not expired
* @return boolean true if valid
*/
public function isValid()
{
$now = new \DateTime();
return ($now < $this->expiredAt);
}
}
......@@ -15,7 +15,7 @@ use Symfony\Component\Validator\Constraints as Assert;
* @ORM\Entity
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="discr", type="string")
* @ORM\DiscriminatorMap({"transfert" = "Transfert", "transaction" = "Transaction"})
* @ORM\DiscriminatorMap({"transfert" = "Transfert", "transaction" = "Transaction", "tro_adh_pre" = "TransactionAdherentPrestataire", "tro_pre_adh" = "TransactionPrestataireAdherent", "tro_pre_pre" = "TransactionPrestatairePrestataire", "tre_cpt_adh" = "TransfertComptoirAdherent", "tre_cpt_grp" = "TransfertComptoirGroupe", "tre_cpt_pre" = "TransfertComptoirPrestataire", "tre_grp_cpt" = "TransfertGroupeComptoir", "tre_pre_cpt" = "TransfertPrestataireComptoir", "tre_sie_grp" = "TransfertSiegeGroupe"})
*/
abstract class Flux
{
......@@ -31,20 +31,28 @@ abstract class Flux
protected $id;
/**
* @ORM\OneToOne(targetEntity="User", inversedBy="user", cascade={"all"})
* @ORM\ManyToOne(targetEntity="User", inversedBy="flux", cascade={"all"})
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=true)
*/
protected $operateur;
/**
* TYPE DE TRANSACTION :
* Type de transfert / transaction : exemple : Prestataire à Adhérent
* @var string
*
* @ORM\Column(name="type", type="string", length=3)
* @ORM\Column(name="type", type="string", length=200)
*/
protected $type;
/**
* Type de flux : transfert / transaction
* @var string
*
* @ORM\Column(name="parenttype", type="string", length=20)
*/
protected $parenttype;
/**
* @var float
*
* @ORM\Column(name="montant", type="decimal", precision=7, scale=2)
......@@ -58,8 +66,131 @@ abstract class Flux
*/
protected $reference;
protected $expediteur=null;
protected $expediteur = null;
protected $destinataire = null;
abstract public function getParenttype();
public function getId(): int
{
return $this->id;
}
/**
* @param $parenttype
* @return $this
*/
public function setParenttype($parenttype)
{
$this->parenttype = $parenttype;
return $this;
}
/**
* @param User $destinataire
* @return $this
*/
public function setOperateur(User $operateur)
{
$this->operateur = $operateur;
return $this;
}
/**
* @return User operateur
*/
public function getOperateur(): User
{
return $this->operateur;
}
/**
* @param $destinataire
* @return $this
*/
public function setDestinataire($destinataire)
{
$this->destinataire = $destinataire;
return $this;
}
/**
* @return destinataire
*/
public function getDestinataire()
{
return $this->destinataire;
}
/**
* @param $expediteur
* @return $this
*/
public function setExpediteur($expediteur)
{
$this->expediteur = $expediteur;
return $this;
}
/**
* @return expediteur
*/
public function getExpediteur()
{
return $this->expediteur;
}
/**
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* @param string $type
* @return Transaction
*/
public function setType(string $type)
{
$this->type = $type;
return $this;
}
/**
* @return float
*/
public function getMontant(): float
{
return $this->montant;
}
protected $destinataire=null;
/**
* @param float $montant
* @return Transaction
*/
public function setMontant(float $montant)
{
$this->montant = $montant;
return $this;
}
/**
* @return string
*/
public function getReference(): string
{
return $this->reference;
}
/**
* @param string $reference
* @return Transaction
*/
public function setReference(string $reference)
{
$this->reference = $reference;
return $this;
}
}
......@@ -179,6 +179,6 @@ class Groupe
public function __toString(): string
{
return $this->getName()?$this->getName():'Groupe';
return (!empty($this->getName())?$this->getName():'Groupe');
}
}
......@@ -26,8 +26,6 @@ class Prestataire
GeolocEntityTrait,
HasCompteEntity;
const UPLOAD_DIR = "prestataire";
/**
* @var int
*
......@@ -124,9 +122,8 @@ class Prestataire
/**
* @var \Application\Sonata\MediaBundle\Entity\Media
* @Assert\NotBlank()
* @ORM\ManyToOne(targetEntity="App\Application\Sonata\MediaBundle\Entity\Media", cascade={"persist"}, fetch="LAZY")
* @ORM\JoinColumn(name="media_id", referencedColumnName="id")
* @ORM\JoinColumn(name="media_id", referencedColumnName="id", nullable=true)
*/
protected $media;
......@@ -491,6 +488,6 @@ class Prestataire
public function __toString(): string
{
return ($this->raison?$this->raison:($this->getUser()?$this->getUser()->getFullname():'Prestataire '.$this->getId()));
return ($this->raison?$this->raison:($this->getUser()?$this->getUser()->getFullname():'Prestataire'));
}
}
......@@ -79,4 +79,9 @@ class Siege
}
return $this;
}
public function __toString(): string
{
return 'SIEGE';
}
}
......@@ -2,10 +2,8 @@
namespace App\Entity;
use App\Entity\EntityTrait\EnablableEntityTrait;
use App\Entity\Flux;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* TRANSACTION
......@@ -23,9 +21,14 @@ use Symfony\Component\Validator\Constraints as Assert;
* - ADHERENTS => PRESTATAIRES (Paiement numérique)
*
* @ORM\Entity
* @ORM\Table(name="transaction")
*/
class Transaction extends Flux
{
/**
* @return string
*/
public function getParenttype(): string
{
return 'transaction';
}
}
<?php
namespace App\Entity;
use App\Entity\Adherent;
use App\Entity\Prestataire;
use App\Entity\Transaction;
use Doctrine\ORM\Mapping as ORM;
/**
* TRANSACTION
* - ADHERENTS => PRESTATAIRES (Paiement numérique)
*
* @ORM\Entity
*/
class TransactionAdherentPrestataire extends Transaction
{
/**
* @ORM\OneToOne(targetEntity="Adherent", cascade={"all"})
* @ORM\JoinColumn(name="adherent_id", referencedColumnName="id", nullable=true)
*/
protected $expediteur;
/**
* @ORM\OneToOne(targetEntity="Prestataire", cascade={"all"})
* @ORM\JoinColumn(name="prestataire_id", referencedColumnName="id", nullable=true)
*/
protected $destinataire;
/**
* @return string
*/
public function getType(): string
{
return 'adherent_prestataire';
}
}
<?php
namespace App\Entity;
use App\Entity\Adherent;
use App\Entity\Prestataire;
use App\Entity\Transaction;
use Doctrine\ORM\Mapping as ORM;
/**
* TRANSACTION
* - PRESTATAIRES => ADHERENTS (Virement vers un adherent)
*
* @ORM\Entity
*/
class TransactionPrestataireAdherent extends Transaction
{
/**
* @ORM\OneToOne(targetEntity="Prestataire", cascade={"all"})
* @ORM\JoinColumn(name="prestataire_id", referencedColumnName="id", nullable=true)
*/
protected $expediteur;
/**
* @ORM\OneToOne(targetEntity="Adherent", cascade={"all"})
* @ORM\JoinColumn(name="adherent_id", referencedColumnName="id", nullable=true)
*/
protected $destinataire;
/**
* @return string
*/
public function getType(): string
{
return 'prestataire_adherent';
}
}
<?php
namespace App\Entity;
use App\Entity\Adherent;
use App\Entity\Prestataire;
use App\Entity\Transaction;
use Doctrine\ORM\Mapping as ORM;
/**
* TRANSACTION
* - PRESTATAIRES => PRESTATAIRES (Virement entre prestataires)
*
* @ORM\Entity
*/
class TransactionPrestatairePrestataire extends Transaction
{
/**
* @ORM\OneToOne(targetEntity="Prestataire", cascade={"all"})
* @ORM\JoinColumn(name="prestataire_id", referencedColumnName="id", nullable=true)
*/
protected $expediteur;
/**
* @ORM\OneToOne(targetEntity="Prestataire", cascade={"all"})
* @ORM\JoinColumn(name="prestataire_dest_id", referencedColumnName="id", nullable=true)
*/
protected $destinataire;
/**
* @return string
*/
public function getType(): string
{
return 'prestataire_prestataire';
}
}
......@@ -2,11 +2,8 @@
namespace App\Entity;
use App\Entity\EntityTrait\EnablableEntityTrait;
use App\Entity\Flux;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* TRANSFERT
......@@ -27,8 +24,14 @@ use Symfony\Component\Validator\Constraints as Assert;
* - PRESTATAIRES => COMPTOIRS (Reconversion)
*
* @ORM\Entity()
* @ORM\Table()
*/
class Transfert extends Flux
{
/**
* @return string
*/
public function getParenttype(): string
{
return 'transfert';
}
}
<?php
namespace App\Entity;
use App\Entity\Adherent;
use App\Entity\Comptoir;
use App\Entity\Transfert;
use Doctrine\ORM\Mapping as ORM;
/**
* TRANSFERT
* - COMPTOIRS => ADHERENTS (Diffusion de monnaie papier auprès des adhérents)
*
* @ORM\Entity()
*/
class TransfertComptoirAdherent extends Transfert
{
/**
* @ORM\OneToOne(targetEntity="Comptoir", cascade={"all"})
* @ORM\JoinColumn(name="comptoir_id", referencedColumnName="id", nullable=true)
*/
protected $expediteur;
/**
* @ORM\OneToOne(targetEntity="Adherent", cascade={"all"})
* @ORM\JoinColumn(name="adherent_id", referencedColumnName="id", nullable=true)
*/
protected $destinataire;
/**
* @return string
*/
public function getType(): string
{
return 'comptoir_adherent';
}
}
<?php
namespace App\Entity;
use App\Entity\Comptoir;
use App\Entity\Groupe;
use App\Entity\Transfert;
use Doctrine\ORM\Mapping as ORM;
/**
* TRANSFERT
* - COMPTOIRS => GROUPES LOCAUX (Transfert du comptoir au groupe)
*
* @ORM\Entity()
*/
class TransfertComptoirGroupe extends Transfert
{
/**
* @ORM\OneToOne(targetEntity="Comptoir", cascade={"all"})
* @ORM\JoinColumn(name="comptoir_id", referencedColumnName="id", nullable=true)
*/
protected $expediteur;
/**
* @ORM\OneToOne(targetEntity="Groupe", cascade={"all"})
* @ORM\JoinColumn(name="groupe_id", referencedColumnName="id", nullable=true)
*/
protected $destinataire;
/**
* @return string
*/
public function getType(): string
{
return 'comptoir_groupe';
}
}
<?php
namespace App\Entity;
use App\Entity\Comptoir;
use App\Entity\Prestataire;
use App\Entity\Transfert;
use Doctrine\ORM\Mapping as ORM;
/**
* TRANSFERT
* - COMPTOIRS => PRESTATAIRES (Diffusion de monnaie papier auprès des prestataires)
*
* @ORM\Entity()
*/
class TransfertComptoirPrestataire extends Transfert
{
/**
* @ORM\OneToOne(targetEntity="Comptoir", cascade={"all"})
* @ORM\JoinColumn(name="comptoir_id", referencedColumnName="id", nullable=true)
*/
protected $expediteur;
/**
* @ORM\OneToOne(targetEntity="Prestataire", cascade={"all"})
* @ORM\JoinColumn(name="prestataire_id", referencedColumnName="id", nullable=true)
*/
protected $destinataire;
/**
* @return string
*/
public function getType(): string
{
return 'comptoir_prestataire';
}
}
<?php
namespace App\Entity;
use App\Entity\Comptoir;
use App\Entity\Groupe;
use App\Entity\Transfert;
use Doctrine\ORM\Mapping as ORM;
/**
* TRANSFERT
* - GROUPES LOCAUX => COMPTOIRS (Transfert du groupe au comptoir)
*
* @ORM\Entity()
*/
class TransfertGroupeComptoir extends Transfert
{
/**
* @ORM\OneToOne(targetEntity="Groupe", cascade={"all"})
* @ORM\JoinColumn(name="groupe_id", referencedColumnName="id", nullable=true)
*/
protected $expediteur;
/**
* @ORM\OneToOne(targetEntity="Comptoir", cascade={"all"})
* @ORM\JoinColumn(name="comptoir_id", referencedColumnName="id", nullable=true)
*/
protected $destinataire;
/**
* @return string
*/
public function getType(): string
{
return 'groupe_comptoir';
}
}
<?php
namespace App\Entity;
use App\Entity\Comptoir;
use App\Entity\Prestataire;
use App\Entity\Transfert;
use Doctrine\ORM\Mapping as ORM;
/**
* TRANSFERT
* - PRESTATAIRES => COMPTOIRS (Reconversion)
*
* @ORM\Entity()
*/
class TransfertPrestataireComptoir extends Transfert
{
/**
* @ORM\OneToOne(targetEntity="Prestataire", cascade={"all"})
* @ORM\JoinColumn(name="prestataire_id", referencedColumnName="id", nullable=true)
*/
protected $expediteur;
/**
* @ORM\OneToOne(targetEntity="Comptoir", cascade={"all"})
* @ORM\JoinColumn(name="comptoir_id", referencedColumnName="id", nullable=true)
*/
protected $destinataire;
/**
* @return string
*/
public function getType(): string
{
return 'prestataire_comptoir';
}
}
<?php
namespace App\Entity;
use App\Entity\Groupe;
use App\Entity\Siege;
use App\Entity\Transfert;
use Doctrine\ORM\Mapping as ORM;
/**
* TRANSFERT
* - SIEGE => GROUPES LOCAUX (Transfert du siège au groupe)
*
* @ORM\Entity()
*/
class TransfertSiegeGroupe extends Transfert
{
/**
* @ORM\OneToOne(targetEntity="Siege", cascade={"all"})
* @ORM\JoinColumn(name="siege_id", referencedColumnName="id", nullable=true)
*/
protected $expediteur;
/**
* @ORM\OneToOne(targetEntity="Groupe", cascade={"all"})
* @ORM\JoinColumn(name="groupe_id", referencedColumnName="id", nullable=true)
*/
protected $destinataire;
/**
* @return string
*/
public function getType(): string
{
return 'siege_groupe';
}
}
......@@ -3,6 +3,8 @@
namespace App\Entity;
use App\Entity\Adherent;
use App\Entity\EmailToken;
use App\Entity\Flux;
use App\Entity\Prestataire;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Event\LifecycleEventArgs;
......@@ -17,7 +19,7 @@ use Symfony\Component\Validator\Constraints as Assert;
* @ORM\Table(name="user")
* @UniqueEntity(
* fields={"firstname", "lastname", "email"},
* errorPath="lastname",
* errorPath="email",
* message="Ce nom avec cet email est déjà utilisé !"
* )
*/
......@@ -61,9 +63,23 @@ class User extends BaseUser
*/
private $cotisations;
/**
* @ORM\OneToMany(targetEntity="Flux", mappedBy="operateur", cascade={"all"})
*/
protected $flux;
/**
* @ORM\OneToMany(targetEntity="EmailToken", mappedBy="user", cascade={"persist", "remove"})
* @ORM\OrderBy({"expiredAt" = "DESC"})
*/
private $emailTokens;
public function __construct()
{
parent::__construct();
$this->cotisations = new ArrayCollection();
$this->flux = new ArrayCollection();
$this->emailTokens = new ArrayCollection();
}
public function getCommonName(): ?string
......@@ -218,4 +234,72 @@ class User extends BaseUser
// }
return $this;
}
/**
* @return Flux[]|ArrayCollection
*/
public function getFlux()
{
return $this->flux;
}
/**
* @param Flux $flux
* @return $this
*/
public function addFlux(Flux $flux)
{
if (!$this->flux->contains($flux)) {
$this->flux[] = $flux;
$flux->setUser($this);
}
return $this;
}
/**
* @param Flux $flux
* @return $this
*/
public function removeFlux(Flux $flux)
{
throw new \LogicException('User::removeFlux : This code should not be reached!');
// if ($this->flux->contains($flux)) {
// $this->flux->removeElement($flux);
// }
return $this;
}
public function createEmailToken()
{
$token = new EmailToken();
$token->setUser($this);
$this->emailTokens->add($token);
return $token;
}
public function getFirstValidEmailToken()
{
foreach ($this->getEmailTokens() as $emailToken) {
if ($emailToken->isValid()) {
return $emailToken;
}
}
return null;
}
public function getEmailTokens()
{
return $this->emailTokens;
}
public function getEmailToken($token)
{
foreach ($this->emailTokens as $emailToken) {
if ($emailToken->getToken()==$token) {
return $emailToken;
}
}
}
}
<?php
namespace App\Enum;
abstract class MoyenEnum
{
const MOYEN_CB = "cb";
const MOYEN_ESPECE = "espece";
const MOYEN_CHEQUE = "cheque";
const MOYEN_VIREMENT = "virement";
const MOYEN_AUTRE = "autre";
/** @var array user friendly named type */
protected static $typeName = [
self::MOYEN_CB => 'Carte bancaire',
self::MOYEN_ESPECE => 'Espèce',
self::MOYEN_CHEQUE => 'Chèque',
self::MOYEN_VIREMENT => 'Virement',
self::MOYEN_AUTRE => 'Autre',
];
/**
* @param string $typeShortName
* @return string
*/
public static function getTypeName($typeShortName)
{
if (!isset(static::$typeName[$typeShortName])) {
return "Unknown type ($typeShortName)";
}
return static::$typeName[$typeShortName];
}
/**
* @return array<string>
*/
public static function getAvailableTypes()
{
return [
self::MOYEN_CB,
self::MOYEN_ESPECE,
self::MOYEN_CHEQUE,
self::MOYEN_VIREMENT,
self::MOYEN_AUTRE
];
}
}
<?php
namespace App\EventListener;
use App\Entity\Adherent;
use App\Entity\EntityTrait\GeolocEntityTrait;
use App\Entity\Prestataire;
use App\Entity\User;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Geocoder\Provider\Nominatim\Nominatim;
use Geocoder\Query\GeocodeQuery;
class UserListener
{
public function preUpdate(PreUpdateEventArgs $eventArgs)
{
$entity = $eventArgs->getEntity();
if (!($entity instanceof User) && !empty($user->getUsername())) {
return;
}
// GEOCODING ADDRESS :
$httpClient = new \Http\Adapter\Guzzle6\Client();
$provider = Nominatim::withOpenStreetMapServer($httpClient, 'test');
$geocoder = new \Geocoder\StatefulGeocoder($provider, 'fr');
$fullAddress = $entity->getAdresse().' '.$entity->getCpostal().' '.$entity->getVille();
// Query geocoding from complete addresse
$result = $geocoder->geocodeQuery(GeocodeQuery::create($fullAddress));
if (count($result) > 0) {
$coords = $result->first()->getCoordinates();
$entity->setLat($coords->getLatitude());
$entity->setLon($coords->getLongitude());
}
}
}
......@@ -4,6 +4,7 @@ namespace App\Listener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
......@@ -43,12 +44,32 @@ class AfterLoginRedirection implements AuthenticationSuccessHandlerInterface
}, $roles);
if (in_array('ROLE_SUPER_ADMIN', $rolesTab, true)) {
// c'est un aministrateur : on le rediriger vers l'espace admin
// c'est un administrateur
if ($this->getTargetUrlFromSession($request->getSession(), $token) != null) {
// on le redirige vers l'url demandée à l'origine si elle existe
$redirection = new RedirectResponse($this->getTargetUrlFromSession($request->getSession(), $token));
} else {
// sinon on le redirige vers le dashboard
$redirection = new RedirectResponse($this->router->generate('sonata_admin_dashboard'));
}
} else {
$redirection = new RedirectResponse($this->router->generate('index'));
}
return $redirection;
}
/**
* @return string|null
*/
private function getTargetUrlFromSession(SessionInterface $session, TokenInterface $token)
{
$key = sprintf('_security.%s.target_path', $token->getProviderKey());
if ($session->has($key)) {
return $session->get($key);
}
return null;
}
}
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20190122155645 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE flux ADD adherent_id INT DEFAULT NULL, ADD prestataire_id INT DEFAULT NULL, ADD prestataire_dest_id INT DEFAULT NULL, ADD comptoir_id INT DEFAULT NULL, ADD groupe_id INT DEFAULT NULL, ADD siege_id INT DEFAULT NULL, DROP expediteur, DROP destinataire, CHANGE type type VARCHAR(200) NOT NULL');
$this->addSql('ALTER TABLE flux ADD CONSTRAINT FK_7252313A25F06C53 FOREIGN KEY (adherent_id) REFERENCES adherent (id)');
$this->addSql('ALTER TABLE flux ADD CONSTRAINT FK_7252313ABE3DB2B7 FOREIGN KEY (prestataire_id) REFERENCES prestataire (id)');
$this->addSql('ALTER TABLE flux ADD CONSTRAINT FK_7252313AECEF536E FOREIGN KEY (prestataire_dest_id) REFERENCES prestataire (id)');
$this->addSql('ALTER TABLE flux ADD CONSTRAINT FK_7252313AAEB0C1F5 FOREIGN KEY (comptoir_id) REFERENCES comptoir (id)');
$this->addSql('ALTER TABLE flux ADD CONSTRAINT FK_7252313A7A45358C FOREIGN KEY (groupe_id) REFERENCES groupe (id)');
$this->addSql('ALTER TABLE flux ADD CONSTRAINT FK_7252313ABF006E8B FOREIGN KEY (siege_id) REFERENCES siege (id)');
$this->addSql('CREATE INDEX IDX_7252313A25F06C53 ON flux (adherent_id)');
$this->addSql('CREATE INDEX IDX_7252313ABE3DB2B7 ON flux (prestataire_id)');
$this->addSql('CREATE INDEX IDX_7252313AECEF536E ON flux (prestataire_dest_id)');
$this->addSql('CREATE INDEX IDX_7252313AAEB0C1F5 ON flux (comptoir_id)');
$this->addSql('CREATE INDEX IDX_7252313A7A45358C ON flux (groupe_id)');
$this->addSql('CREATE INDEX IDX_7252313ABF006E8B ON flux (siege_id)');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE flux DROP FOREIGN KEY FK_7252313A25F06C53');
$this->addSql('ALTER TABLE flux DROP FOREIGN KEY FK_7252313ABE3DB2B7');
$this->addSql('ALTER TABLE flux DROP FOREIGN KEY FK_7252313AECEF536E');
$this->addSql('ALTER TABLE flux DROP FOREIGN KEY FK_7252313AAEB0C1F5');
$this->addSql('ALTER TABLE flux DROP FOREIGN KEY FK_7252313A7A45358C');
$this->addSql('ALTER TABLE flux DROP FOREIGN KEY FK_7252313ABF006E8B');
$this->addSql('DROP INDEX IDX_7252313A25F06C53 ON flux');
$this->addSql('DROP INDEX IDX_7252313ABE3DB2B7 ON flux');
$this->addSql('DROP INDEX IDX_7252313AECEF536E ON flux');
$this->addSql('DROP INDEX IDX_7252313AAEB0C1F5 ON flux');
$this->addSql('DROP INDEX IDX_7252313A7A45358C ON flux');
$this->addSql('DROP INDEX IDX_7252313ABF006E8B ON flux');
$this->addSql('ALTER TABLE flux ADD expediteur VARCHAR(100) NOT NULL COLLATE utf8_general_ci, ADD destinataire VARCHAR(100) NOT NULL COLLATE utf8_general_ci, DROP adherent_id, DROP prestataire_id, DROP prestataire_dest_id, DROP comptoir_id, DROP groupe_id, DROP siege_id, CHANGE type type VARCHAR(3) NOT NULL COLLATE utf8_general_ci');
}
}
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20190122174459 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE flux ADD parenttype VARCHAR(20) NOT NULL');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE flux DROP parenttype');
}
}
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20190122221702 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE adherent ADD geoloc_id INT DEFAULT NULL, ADD enabled TINYINT(1) NOT NULL');
$this->addSql('ALTER TABLE adherent ADD CONSTRAINT FK_90D3F060EF390162 FOREIGN KEY (geoloc_id) REFERENCES geoloc (id)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_90D3F060EF390162 ON adherent (geoloc_id)');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE adherent DROP FOREIGN KEY FK_90D3F060EF390162');
$this->addSql('DROP INDEX UNIQ_90D3F060EF390162 ON adherent');
$this->addSql('ALTER TABLE adherent DROP geoloc_id, DROP enabled');
}
}
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20190122224702 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE cotisation DROP type');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE cotisation ADD type VARCHAR(12) NOT NULL COLLATE utf8mb4_unicode_ci');
}
}
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20190123025255 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE TABLE email_token (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, token VARCHAR(255) NOT NULL, expired_at DATE NOT NULL, INDEX IDX_C27AE0B4A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = InnoDB');
$this->addSql('ALTER TABLE email_token ADD CONSTRAINT FK_C27AE0B4A76ED395 FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('DROP TABLE email_token');
}
}
<?php
namespace App\Security;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
class EmailTokenAuthenticator extends AbstractGuardAuthenticator
{
private $em;
private $router;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
$this->router = $router;
}
public function setRouter(Router $router)
{
$this->router = $router;
}
/**
* Called on every request to decide if this authenticator should be
* used for the request. Returning false will cause this authenticator
* to be skipped.
*/
public function supports(Request $request)
{
return $request->query->has('emailToken');
}
/**
* Called on every request. Return whatever credentials you want to
* be passed to getUser() as $credentials.
*/
public function getCredentials(Request $request)
{
return array(
'token' => $request->query->get('emailToken'),
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$token = $credentials['token'];
$emailToken = $this->em->getRepository('App\Entity\EmailToken')
->findOneByToken($token);
return $emailToken->getUser();
}
public function checkCredentials($credentials, UserInterface $user)
{
$emailToken = $user->getEmailToken($credentials['token']);
$now = new \DateTime();
return $now < $emailToken->getExpiredAt();
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
//Redirect with no emailToken
return new RedirectResponse($this->router->generate($request->get('_route'), $request->get('_route_params')));
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
return new RedirectResponse($this->router->generate('index'));
}
/**
* Called when authentication is needed, but it's not sent
*/
public function start(Request $request, AuthenticationException $authException = null)
{
return null;
}
public function supportsRememberMe()
{
return false;
}
}
......@@ -5,6 +5,7 @@ namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;
class AppExtension extends AbstractExtension
{
......@@ -18,17 +19,16 @@ class AppExtension extends AbstractExtension
// ];
// }
public function getFunctions(): array
public function getTests(): array
{
return [
new TwigFunction('getLastNews', [$this, 'getLastNews']),
new TwigTest('instanceof', [$this, 'instanceof']),
];
}
public function getLastNews($limit)
public function instanceof($var, $instance)
{
$db = $this->
$result= $db->findBy(array('enabled' => true), array('created' => 'DESC', 'limit' => $limit));
return $result;
$reflexionClass = new \ReflectionClass($instance);
return $reflexionClass->isInstance($var);
}
}
{# {% extends '@SonataAdmin/CRUD/base_list_field.html.twig' %}
{% block field%}
{%- spaceless %}
{% if object is instanceof("App\\Entity\\Adherent") %}
{% set text = 'adherentttt' %}
{% else %}
{% set text = 'otherrr' %}
{% endif %}
<span class="label" style='cursor:pointer;'>{{ text }}</span>
{% endspaceless -%}
{% endblock %} #}
<td class="sonata-ba-list-field sonata-ba-list-field-{{ field_description.type }}" objectId="{{ admin.id(object) }}"{% if field_description.options.row_align is defined %} style="text-align:{{ field_description.options.row_align }}"{% endif %}>
{% set route = field_description.options.route.name|default(null) %}
{% if field_description.label|lower == 'expediteur' %}
{% if object.expediteur is instanceof("App\\Entity\\Adherent") %}
{% set routea = 'adherent_edit' %}
{% elseif object.expediteur is instanceof("App\\Entity\\Prestataire") %}
{% set routea = 'prestataire_edit' %}
{% elseif object.expediteur is instanceof("App\\Entity\\Comptoir") %}
{% set routea = 'admin_app_comptoir_edit' %}
{% elseif object.expediteur is instanceof("App\\Entity\\Groupe") %}
{% set routea = 'admin_app_groupe_edit' %}
{% else %}
{% set routea = '' %}
{% endif %}
{% if routea != ''
%}
<a class="sonata-link-identifier" href="{{ path(routea, {'id': object.expediteur.id}) }}">
{%- block field %}
{% spaceless %}
{% if field_description.options.collapse is defined %}
{% set collapse = field_description.options.collapse %}
<div class="sonata-readmore"
data-readmore-height="{{ collapse.height|default(40) }}"
data-readmore-more="{{ collapse.more|default('read_more')|trans({}, 'SonataAdminBundle') }}"
data-readmore-less="{{ collapse.less|default('read_less')|trans({}, 'SonataAdminBundle') }}">{{ value }}</div>
{% else %}
{{ value }}
{% endif %}
{% endspaceless %}
{% endblock -%}
</a>
{% endif %}
{% elseif
field_description.options.identifier is defined
and route
and admin.hasRoute(route)
and admin.hasAccess(route, route in ['show', 'edit'] ? object : null)
%}
<a class="sonata-link-identifier" href="{{ admin.generateObjectUrl(route, object, field_description.options.route.parameters) }}">
{{ block('field') }}
</a>
{% else %}
{% set isEditable = field_description.options.editable is defined and field_description.options.editable and admin.hasAccess('edit', object) %}
{% set xEditableType = field_description.type|sonata_xeditable_type %}
{% if isEditable and xEditableType %}
{% set url = path(
'sonata_admin_set_object_field_value',
admin.getPersistentParameters|default([])|merge({
'context': 'list',
'field': field_description.name,
'objectId': admin.id(object),
'code': admin.code(object)
})
) %}
{% if field_description.type == 'date' and value is not empty %}
{% set data_value = value.format('Y-m-d') %}
{% elseif field_description.type == 'boolean' and value is empty %}
{% set data_value = 0 %}
{% else %}
{% set data_value = value %}
{% endif %}
<span {% block field_span_attributes %}class="x-editable"
data-type="{{ xEditableType }}"
data-value="{{ data_value }}"
data-title="{{ field_description.label|trans({}, field_description.translationDomain) }}"
data-pk="{{ admin.id(object) }}"
data-url="{{ url }}" {% endblock %}>
{{ block('field') }}
</span>
{% else %}
{{ block('field') }}
{% endif %}
{% endif %}
</td>
{% extends '@SonataAdmin/CRUD/base_list.html.twig' %}
{% block list_header %}
<div class="pull-left" style="margin: 10px 5px;">
<label for="{{ admin.uniqid }}_sum_of_orders" class="control-label">Total des transactions : </label>
<label class="control-label">{{ admin.getTotalTransaction() }}</label>
</div>
{% endblock %}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment