Browse Source

Suppression utilisateur

develop
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

@@ -95,23 +95,4 @@ class UserBuilder
$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

@@ -814,7 +814,6 @@ abstract class AbstractAdminController extends EaAbstractCrudController
$filteredValue = ['value' => $context->getRequest()->query->get('q')];
$filterManager->applyFilter($repositoryQuery, $field, $filteredValue);
$repositoryQuery->select('.' . $autocompleteContext['propertyName']);
//dump($repositoryQuery->getQueryBuilder()->getQuery()->getDQL());

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

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

@@ -30,6 +30,7 @@ use Lc\SovBundle\Doctrine\EntityManager;
use Lc\SovBundle\Doctrine\Extension\BlameableInterface;
use Lc\SovBundle\Factory\User\UserFactory;
use Lc\SovBundle\Form\User\ConfirmDeleteUserFormType;
use Lc\SovBundle\Model\User\UserInterface;
use Lc\SovBundle\Translation\FlashBagTranslator;
use Lc\SovBundle\Translation\TranslatorAdmin;
use Symfony\Component\HttpFoundation\RequestStack;
@@ -96,14 +97,15 @@ abstract class UserAdminController extends AbstractAdminController
{
$entityManager = $this->getEntityManager();

// Todo envisager un refactor similaire pour toutes les fonctions CRUD
$eaBeforeCrudActionEventDelete = $this->eaBeforeCrudActionEventDelete($context);
if (!is_null($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);
if ($event->isPropagationStopped()) {
return $event->getResponse();
@@ -112,102 +114,42 @@ abstract class UserAdminController extends AbstractAdminController
$user = $event->getEntityInstance();


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


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

$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 {
$entityManager->flush();
$this->addFlashTranslator('success', 'deleted');
} catch (ForeignKeyConstraintViolationException $e) {
throw new EntityRemoveException(['entity_name' => $context->getEntity()->getName(), 'message' => $e->getMessage()]);
}
return $this->redirect($this->getAdminUrlGenerator()->setAction(Crud::PAGE_INDEX)->setEntityId(null)->generateUrl());

}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([
'pageName' => Crud::PAGE_DETAIL,
'templatePath' => '@LcSov/adminlte/crud/delete.html.twig',
'confirm_delete_user_form' => $confirmDeleteUserForm->createView(),
'global_actions' => array(),
'batch_actions' => array(),
'entities_warning' => $entitiesWarning,
'entities_update' => $entitiesToUpdate,
'warning_message_list' => $warningMessages
]));

$event = new AfterCrudActionEvent($context, $responseParameters);
@@ -217,7 +159,41 @@ abstract class UserAdminController extends AbstractAdminController
}

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

@@ -2,6 +2,7 @@

namespace Lc\SovBundle\Definition;

use Lc\SovBundle\Container\ComponentContainer;
use Lc\SovBundle\Container\File\FileContainer;
use Lc\SovBundle\Container\Newsletter\NewsletterContainer;
use Lc\SovBundle\Container\Reminder\ReminderContainer;
@@ -31,7 +32,8 @@ class ApplicationDefinition
TicketMessageContainer::class,
GroupUserContainer::class,
UserContainer::class,
SiteSettingContainer::class
SiteSettingContainer::class,
ComponentContainer::class
];
}


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

@@ -31,7 +31,7 @@ class ConfirmDeleteUserFormType extends AbstractType
{

$builder->add(
'confirm',
'confirmDelete',
CheckboxType::class,
[
'translation_domain' => 'admin',
@@ -40,7 +40,11 @@ class ConfirmDeleteUserFormType extends AbstractType

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

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


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

@@ -23,7 +23,7 @@ abstract class TicketMessageModel extends AbstractLightEntity implements TicketM
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)
*/
protected $ticket;

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

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

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

@@ -6,7 +6,7 @@
{% trans_default_domain ea.i18n.translationDomain %}

{% 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 %}

{% block content_breadcrumb %}
@@ -31,19 +31,24 @@
{% block card_body_wrapper %}
<div class="card-body">
{% 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 %}
</div>
{% endblock %}
@@ -51,8 +56,9 @@
<div class="card-footer">
<div class="row">
{% block delete_form %}
{% form_theme confirm_delete_user_form '@LcSov/adminlte/crud/form_theme.html.twig' %}
{{ 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) }}
{% endblock delete_form %}
</div>

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

@@ -234,8 +234,6 @@
{% endif %}

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

Loading…
Cancel
Save