Browse Source

Suppression utilisateur

feature/symfony6.1
Fabien Normand 2 years ago
parent
commit
3eadc6e305
9 changed files with 88 additions and 115 deletions
  1. +0
    -19
      Builder/User/UserBuilder.php
  2. +0
    -1
      Controller/AbstractAdminController.php
  3. +51
    -75
      Controller/User/UserAdminController.php
  4. +3
    -1
      Definition/ApplicationDefinition.php
  5. +7
    -2
      Form/User/ConfirmDeleteUserFormType.php
  6. +1
    -1
      Model/Ticket/TicketMessageModel.php
  7. +6
    -0
      Resources/translations/admin.fr.yaml
  8. +20
    -14
      Resources/views/adminlte/crud/delete.html.twig
  9. +0
    -2
      Resources/views/adminlte/crud/form_theme.html.twig

+ 0
- 19
Builder/User/UserBuilder.php View File

$this->entityManager->flush(); $this->entityManager->flush();
} }
} }

public function getEntitiesToDeleteForUserDelete(UserInterface $user, string $entityFqcn, RepositoryQueryInterface $repositoryQuery)
{
$entitiesToDelete =array();
// if (new $entityFqcn instanceof BlameableInterface) {
// //CreatedBy
// $query = $repositoryQuery->create();
// $query->filterByCreatedBy($user);
// $entitiesToDelete['nullify']['createdBy'] = $query->find();
//
// //UpdatedBy
// $query = $repositoryQuery->create();
// $query->filterByUpdatedBy($user);
// $entitiesToDelete['nullify']['updatedBy'] = $query->find();
// }


return $entitiesToDelete;
}
} }

+ 0
- 1
Controller/AbstractAdminController.php View File

$filteredValue = ['value' => $context->getRequest()->query->get('q')]; $filteredValue = ['value' => $context->getRequest()->query->get('q')];
$filterManager->applyFilter($repositoryQuery, $field, $filteredValue); $filterManager->applyFilter($repositoryQuery, $field, $filteredValue);
$repositoryQuery->select('.' . $autocompleteContext['propertyName']); $repositoryQuery->select('.' . $autocompleteContext['propertyName']);
//dump($repositoryQuery->getQueryBuilder()->getQuery()->getDQL());


$responses = array(); $responses = array();
foreach ($repositoryQuery->find() as $result) { foreach ($repositoryQuery->find() as $result) {

+ 51
- 75
Controller/User/UserAdminController.php View File

use Lc\SovBundle\Doctrine\Extension\BlameableInterface; use Lc\SovBundle\Doctrine\Extension\BlameableInterface;
use Lc\SovBundle\Factory\User\UserFactory; use Lc\SovBundle\Factory\User\UserFactory;
use Lc\SovBundle\Form\User\ConfirmDeleteUserFormType; use Lc\SovBundle\Form\User\ConfirmDeleteUserFormType;
use Lc\SovBundle\Model\User\UserInterface;
use Lc\SovBundle\Translation\FlashBagTranslator; use Lc\SovBundle\Translation\FlashBagTranslator;
use Lc\SovBundle\Translation\TranslatorAdmin; use Lc\SovBundle\Translation\TranslatorAdmin;
use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\RequestStack;
{ {
$entityManager = $this->getEntityManager(); $entityManager = $this->getEntityManager();


// Todo envisager un refactor similaire pour toutes les fonctions CRUD
$eaBeforeCrudActionEventDelete = $this->eaBeforeCrudActionEventDelete($context); $eaBeforeCrudActionEventDelete = $this->eaBeforeCrudActionEventDelete($context);
if (!is_null($eaBeforeCrudActionEventDelete)) { if (!is_null($eaBeforeCrudActionEventDelete)) {
return $eaBeforeCrudActionEventDelete; return $eaBeforeCrudActionEventDelete;
} }


$entityInstance = $context->getEntity()->getInstance();
$user = $context->getEntity()->getInstance();


$event = new BeforeEntityDeletedEvent($entityInstance);
$event = new BeforeEntityDeletedEvent($user);
$this->container->get('event_dispatcher')->dispatch($event); $this->container->get('event_dispatcher')->dispatch($event);
if ($event->isPropagationStopped()) { if ($event->isPropagationStopped()) {
return $event->getResponse(); return $event->getResponse();
$user = $event->getEntityInstance(); $user = $event->getEntityInstance();




$metas = $entityManager->getMetadataFactory()->getAllMetadata();
foreach ($metas as $meta) {
$entityFqcnList[] = $meta->getName();
}


// Creéer formulaire avec un champ confirm // Creéer formulaire avec un champ confirm
$confirmDeleteUserForm = $this->createForm(ConfirmDeleteUserFormType::class, null, array( $confirmDeleteUserForm = $this->createForm(ConfirmDeleteUserFormType::class, null, array(
'action' => $this->getAdminUrlGenerator()->generateUrl() 'action' => $this->getAdminUrlGenerator()->generateUrl()
)); ));

$confirmDeleteUserForm->handleRequest($context->getRequest()); $confirmDeleteUserForm->handleRequest($context->getRequest());


$entityManager->delete($user);


$entitiesWarning['reductionCart'] = $this->getReductionCartContainer()->getStore()->getByUserOutOfContext($user);
$entitiesWarning['reductionCatalog'] = $this->getReductionCatalogContainer()->getStore()->getByUserOutOfContext($user);
$entitiesWarning['reductionCredit'] = $this->getReductionCreditContainer()->getStore()->getReductionCreditByUserOutOfContext($user);
$entitiesWarning['reductionGift'] = $this->getReductionCreditContainer()->getStore()->getReductionGiftByUserOutOfContext($user);


//si clqiue suppression
$entitiesToDelete = array();
foreach ($entityFqcnList as $entityFqcn) {

if (!is_null($this->getApplicationDefinition()->getContainerByEntityFqcn($entityFqcn))) {
$repositoryQuery = $this->container->get(
$this->getApplicationDefinition()->getContainerByEntityFqcn($entityFqcn)
)->getRepositoryQuery();

$entitiesToDelete[$entityFqcn] = $this->getUserContainer()->getBuilder()->getEntitiesToDeleteForUserDelete($user, $entityFqcn, $repositoryQuery);

}

}

$entityManager->delete($entityInstance);

dump($entityManager->getUnitOfWork()->getScheduledEntityDeletions());
// dump($entityManager->getUnitOfWork()->getEntityChangeSet());
dump($entityManager->getUnitOfWork()->getScheduledEntityUpdates());
dump($entityManager->getUnitOfWork()->getScheduledEntityInsertions());

if ($confirmDeleteUserForm->isSubmitted()) {

$entityManager->flush();
$this->get(FlashBagTranslator::class)->add('success', 'deleted', $this->getTranslationEntityName());
$warningMessages = $this->getDeleteUserWarningMessageList($user);



$this->deleteEntity($this->container->get('doctrine')->getManagerForClass($context->getEntity()->getFqcn()), $entityInstance);
//Todo supprimer les éléments listés
//Avant la suppression on s'assure que l'utilisateur à confirmer et qu'il n'y aucun message d'erreur
if ($confirmDeleteUserForm->isSubmitted() && count($warningMessages['danger']) === 0) {
//Détecter les tables qui possède des relations avec un champ qui n'existe plus
//Dans le cas ci-dessous détecter les adresses lié à un utilisateur qui n'existe plus
//SELECT * FROM address a LEFT OUTER JOIN user u ON(u.id=a.user_id) WHERE u.id is null
try { try {
$entityManager->flush();
$this->addFlashTranslator('success', 'deleted');
} catch (ForeignKeyConstraintViolationException $e) { } catch (ForeignKeyConstraintViolationException $e) {
throw new EntityRemoveException(['entity_name' => $context->getEntity()->getName(), 'message' => $e->getMessage()]); throw new EntityRemoveException(['entity_name' => $context->getEntity()->getName(), 'message' => $e->getMessage()]);
} }
return $this->redirect($this->getAdminUrlGenerator()->setAction(Crud::PAGE_INDEX)->setEntityId(null)->generateUrl()); return $this->redirect($this->getAdminUrlGenerator()->setAction(Crud::PAGE_INDEX)->setEntityId(null)->generateUrl());


}else{ }else{
$entitiesToDelete = $entityManager->getUnitOfWork()->getScheduledEntityDeletions();
$entitiesToUpdate = $entityManager->getUnitOfWork()->getScheduledEntityUpdates();
if($confirmDeleteUserForm->isSubmitted()){
$this->addFlashTranslator('error', 'cannotDelete');
}
} }


// foreach ($entitiesToDelete as $entityFqcn) {
// foreach ($entityFqcn as $action => $field) {
// if ($action == 'nullify') {
// foreach ($field as $fieldName => $entityList) {
// $method = 'set' . ucfirst($fieldName);
// $methodGet = 'get' . ucfirst($fieldName);
// foreach ($entityList as $entity) {
// $entity->$method(null);
// $this->getEntityManager()->update($entity);
// }
// }
// }
//
//
//// if ($action == 'delete') {
//// foreach ($field as $entity) {
//// dump($entity);
//// $this->getEntityManager()->delete($entity);
//// }
//// }
//
// }
//
// }
//Détecter les merde
//SELECT * FROM address a LEFT OUTER JOIN user u ON(u.id=a.user_id) WHERE u.id is null

$responseParameters = $this->configureResponseParameters(KeyValueStore::new([ $responseParameters = $this->configureResponseParameters(KeyValueStore::new([
'pageName' => Crud::PAGE_DETAIL, 'pageName' => Crud::PAGE_DETAIL,
'templatePath' => '@LcSov/adminlte/crud/delete.html.twig', 'templatePath' => '@LcSov/adminlte/crud/delete.html.twig',
'confirm_delete_user_form' => $confirmDeleteUserForm->createView(), 'confirm_delete_user_form' => $confirmDeleteUserForm->createView(),
'global_actions' => array(), 'global_actions' => array(),
'batch_actions' => array(), 'batch_actions' => array(),
'entities_warning' => $entitiesWarning,
'entities_update' => $entitiesToUpdate,
'warning_message_list' => $warningMessages
])); ]));


$event = new AfterCrudActionEvent($context, $responseParameters); $event = new AfterCrudActionEvent($context, $responseParameters);
} }


return $responseParameters; return $responseParameters;
}

public function getDeleteUserWarningMessageList(UserInterface $user): array
{
$warningMessages = array();
$warningMessages['danger'] = [];
$warningMessages['warning'] = [];
$warningMessages['info'] = [];




$entityManager = $this->getEntityManager();

$entityToDeleteListCount = array();
$entityToDeleteListName = array();
foreach ($entityManager->getUnitOfWork()->getScheduledEntityDeletions() as $entityToDelete) {
if (isset($entityToDeleteListCount[(new \ReflectionClass($entityToDelete))->getShortName()])) {
$entityToDeleteListCount[(new \ReflectionClass($entityToDelete))->getShortName()]++;
} else {
$entityToDeleteListCount[(new \ReflectionClass($entityToDelete))->getShortName()] = 1;
}
$entityToDeleteListName[(new \ReflectionClass($entityToDelete))->getShortName()][] = $entityToDelete->getId();
}

foreach ($entityToDeleteListCount as $entityName => $entityToDeleteCount) {
$warningMessages['info'][] = $this->getTranslatorAdmin()->transFlashMessage(
'error',
'deleteEntityCascade',
'User',
array(
'%entity%' => $this->getTranslatorAdmin()->trans('entity.'.$entityName.'.label_plurial'),
'%count%' => $entityToDeleteCount
)
);
}

return $warningMessages;
} }
} }

+ 3
- 1
Definition/ApplicationDefinition.php View File



namespace Lc\SovBundle\Definition; namespace Lc\SovBundle\Definition;


use Lc\SovBundle\Container\ComponentContainer;
use Lc\SovBundle\Container\File\FileContainer; use Lc\SovBundle\Container\File\FileContainer;
use Lc\SovBundle\Container\Newsletter\NewsletterContainer; use Lc\SovBundle\Container\Newsletter\NewsletterContainer;
use Lc\SovBundle\Container\Reminder\ReminderContainer; use Lc\SovBundle\Container\Reminder\ReminderContainer;
TicketMessageContainer::class, TicketMessageContainer::class,
GroupUserContainer::class, GroupUserContainer::class,
UserContainer::class, UserContainer::class,
SiteSettingContainer::class
SiteSettingContainer::class,
ComponentContainer::class
]; ];
} }



+ 7
- 2
Form/User/ConfirmDeleteUserFormType.php View File

{ {


$builder->add( $builder->add(
'confirm',
'confirmDelete',
CheckboxType::class, CheckboxType::class,
[ [
'translation_domain' => 'admin', 'translation_domain' => 'admin',


$builder->add( $builder->add(
'delete', 'delete',
SubmitType::class
SubmitType::class,
array(
'label'=> 'action.delete'
)

); );
} }
public function configureOptions(OptionsResolver $resolver): void public function configureOptions(OptionsResolver $resolver): void
// an arbitrary string used to generate the value of the token // an arbitrary string used to generate the value of the token
// using a different string for each form improves its security // using a different string for each form improves its security
'csrf_token_id' => 'ea-delete', 'csrf_token_id' => 'ea-delete',
'translation_domain'=> 'admin'
]); ]);
} }



+ 1
- 1
Model/Ticket/TicketMessageModel.php View File

protected $message; protected $message;


/** /**
* @ORM\ManyToOne(targetEntity="Lc\SovBundle\Model\Ticket\TicketInterface", inversedBy="ticketMessages", cascade={"remove"})
* @ORM\ManyToOne(targetEntity="Lc\SovBundle\Model\Ticket\TicketInterface", inversedBy="ticketMessages")
* @ORM\JoinColumn(nullable=false) * @ORM\JoinColumn(nullable=false)
*/ */
protected $ticket; protected $ticket;

+ 6
- 0
Resources/translations/admin.fr.yaml View File

editWithTitle: 'Modifier "%label%" : %title% (#%id%)' editWithTitle: 'Modifier "%label%" : %title% (#%id%)'
detail: Voir "%label%" (#%id%) detail: Voir "%label%" (#%id%)
un_titre: Un titre un_titre: Un titre
delete: "Supprimer %label% : <br /> %title% (#%id%)"
account: account:
profile: Mes informations personnelles profile: Mes informations personnelles
change_password: Changer de mot de passe change_password: Changer de mot de passe
birthdate: Date de naissance birthdate: Date de naissance
groupUsers: Groupe d'utilisateurs groupUsers: Groupe d'utilisateurs
isVerified: Actif isVerified: Actif
flashes:
error:
cannotDelete: L'utilisateur ne peut pas être supprimé, voir les élements dans suppression impossible.
Page: Page:
label: Page label: Page
label_plurial: Pages label_plurial: Pages
being-processed: En attente being-processed: En attente
closed: Fermé closed: Fermé
TicketMessage: TicketMessage:
label_plurial: Message de ticket
fields: fields:
message: Votre réponse message: Votre réponse
closeTicket: Fermer la demande closeTicket: Fermer la demande
default: default:
fields: fields:
id: Id id: Id
confirmDelete: Confirmer la suppression
createdAt: Créé le createdAt: Créé le
user: Utilisateur user: Utilisateur
firstname: Prénom firstname: Prénom

+ 20
- 14
Resources/views/adminlte/crud/delete.html.twig View File

{% trans_default_domain ea.i18n.translationDomain %} {% trans_default_domain ea.i18n.translationDomain %}


{% block content_title %} {% block content_title %}
{{ 'delete'|sov_trans_admin_title(translation_entity_name, {id: ea.getEntity().getInstance().getId()}) }}
{{ 'delete'|sov_trans_admin_title(translation_entity_name, {id: ea.getEntity().getInstance().getId(), title: ea.getEntity().getInstance()})|raw }}
{% endblock %} {% endblock %}


{% block content_breadcrumb %} {% block content_breadcrumb %}
{% block card_body_wrapper %} {% block card_body_wrapper %}
<div class="card-body"> <div class="card-body">
{% block detail_fields %} {% block detail_fields %}
{% for type, messageList in warning_message_list %}
{% if messageList|length >0 %}
<div class="alert alert-{{ type }}">
{% if type =='danger' %}
<h5><i class="icon fas fa-ban"></i> Suppresion impossible</h5>
{% elseif type =='warning' %}
<h5><i class="icon fas fa-exclamation-triangle"></i> À vérifier avant
suppression</h5>
{% elseif type =='info' %}
<h5><i class="icon fas fa-info"></i> Élements qui seront supprimés</h5>
{% endif %}


{{ dump(entities_warning) }}
{{ dump(entities_update) }}
{# {% for entity_fqcn, entity_actions in entities_delete %}#}
{# <div class="callout callout-danger">#}
{# <h5>{{ entity_fqcn }}</h5>#}
{# {% for action, entity_field_list in entity_actions %}#}
{# {% for field, entity_list in entity_field_list %}#}
{# <p>{{ entity_list|length }} entités à {{ action }} sur le champ {{ field }}</p>#}
{# {% endfor %}#}
{# {% endfor %}#}
{# </div>#}
{# {% endfor %}#}
{% for message in messageList %}
<p>{{ message|raw }}</p>
{% endfor %}
</div>
{% endif %}
{% endfor %}
{% endblock %} {% endblock %}
</div> </div>
{% endblock %} {% endblock %}
<div class="card-footer"> <div class="card-footer">
<div class="row"> <div class="row">
{% block delete_form %} {% block delete_form %}
{% form_theme confirm_delete_user_form '@LcSov/adminlte/crud/form_theme.html.twig' %}
{{ form_start(confirm_delete_user_form) }} {{ form_start(confirm_delete_user_form) }}
<input type="hidden" name="token" value="{{ csrf_token('ea-delete') }}" />
<input type="hidden" name="token" value="{{ csrf_token('ea-delete') }}"/>
{{ form_end(confirm_delete_user_form) }} {{ form_end(confirm_delete_user_form) }}
{% endblock delete_form %} {% endblock delete_form %}
</div> </div>

+ 0
- 2
Resources/views/adminlte/crud/form_theme.html.twig View File

{% endif %} {% endif %}


<div class="col-12"> <div class="col-12">
{# {{ dump(form.vars) }} #}
{# {{ dump(form.vars.ea_crud_form.ea_field) }} #}
<div class="input-group"> <div class="input-group">
<div class="input-group-prepend"> <div class="input-group-prepend">
{% if form.parent.vars['row_attr']['data-sortable'] is defined %} {% if form.parent.vars['row_attr']['data-sortable'] is defined %}

Loading…
Cancel
Save