Commit fa7ce658 by Julien Jorry

Fix import : fix adherent import : can update from adherent import if needed + fix some errors

parent ac119167
......@@ -40,7 +40,6 @@ use Symfony\Component\Translation\TranslatorInterface;
class ImportController extends CRUDController
{
protected $siege;
protected $header;
protected $warnings;
protected $errors;
......@@ -72,14 +71,12 @@ class ImportController extends CRUDController
$this->tokenGenerator = $tokenGenerator;
$this->eventDispatcher = $eventDispatcher;
$this->operationUtils = $operationUtils;
$this->siege = null;
$this->sendemail = false;
$this->test = false;
}
public function createAction()
{
$this->siege = $this->em->getRepository(Siege::class)->getTheOne();
$import = new Import();
$userLogguedIn = $this->em->merge($this->getUser());
$import->setUser($userLogguedIn);
......@@ -87,12 +84,16 @@ class ImportController extends CRUDController
$form->handleRequest($this->getRequest());
if ($form->isSubmitted() && $form->isValid()) {
$this->em->getConnection()->getConfiguration()->setSQLLogger(null);
gc_collect_cycles();
$import = $form->getData();
$media = $import->getMedia();
$type = $import->getType();
$this->sendemail = (bool) $import->getSendemail();
$this->test = (bool) $import->getTest();
// $this->em->getConnection()->beginTransaction(); // suspend auto-commit
try {
// Sauvegarder l'import en base de données avant l'essai d'import
$this->em->persist($import);
$this->em->flush();
......@@ -111,6 +112,8 @@ class ImportController extends CRUDController
$this->em->persist($import);
$this->em->flush();
// $this->em->getConnection()->commit(); // commit all !
if (empty($this->errors)) {
if ($this->test) {
$this->addFlash(
......@@ -129,6 +132,13 @@ class ImportController extends CRUDController
"Il y a eu des erreurs lors de l'import !"
);
}
} catch (Exception $e) {
// $this->em->getConnection()->rollBack(); // Rollback all previous commit !
$this->addFlash(
'error',
"Il y a eu une erreur lors de l'import : ".$e->getMessage()
);
}
return $this->redirect($this->admin->generateUrl('show', ['id' => $import->getId()]));
}
......@@ -264,7 +274,7 @@ class ImportController extends CRUDController
if (empty($groupeFound)) {
$groupeFound = new Groupe();
$groupeFound->setName($groupe);
$groupeFound->setSiege($this->siege);
$groupeFound->setSiege($this->em->getRepository(Siege::class)->getTheOne());
if (!$this->test) {
$this->em->persist($groupeFound);
}
......@@ -289,7 +299,7 @@ class ImportController extends CRUDController
if (!empty($adresse) || !empty($cpostal) || !empty($ville)) {
$geolocFound = new Geoloc();
$geolocFound->setAdresse($adresse);
$geolocFound->setCpostal(intval($cpostal));
$geolocFound->setCpostal($cpostal);
$geolocFound->setVille($ville);
if (!empty($latitude) && !empty($longitude)) {
$geolocFound->setLat((float) $latitude);
......@@ -326,7 +336,7 @@ class ImportController extends CRUDController
if (!$this->test) {
$this->em->persist($comptoir);
$this->em->flush();
$this->em->clear();
// $this->em->clear();
}
} else {
$this->addError($row, $line, 'nom', $this->translator->trans('Le comptoir avec ce nom {name} existe déjà !', ['name' => $nom]));
......@@ -395,7 +405,7 @@ class ImportController extends CRUDController
if (!$this->test) {
$this->em->persist($groupe);
$this->em->flush();
$this->em->clear();
// $this->em->clear();
}
} else {
$this->addError($row, $line, 'name', $this->translator->trans("Le groupe avec ce nom '" . $name . "' existe déjà !"));
......@@ -566,7 +576,7 @@ class ImportController extends CRUDController
if (empty($groupeFound)) {
$groupeFound = new Groupe();
$groupeFound->setName($groupe);
$groupeFound->setSiege($this->siege);
$groupeFound->setSiege($this->em->getRepository(Siege::class)->getTheOne());
if (!$this->test) {
$this->em->persist($groupeFound);
}
......@@ -644,18 +654,39 @@ class ImportController extends CRUDController
$this->addWarning($row, $line, 'tags', 'empty');
}
if (!empty($adresse) || !empty($cpostal) || !empty($ville)) {
// $geolocFound = $this->em->getRepository(Geoloc::class)->findOneBy([
// 'adresse' => $adresse,
// 'cpostal' => $cpostal,
// 'ville' => $ville
// ]);
// if (!empty($geolocFound)) {
// $geolocP = $this->em->getRepository(GeolocPrestataire::class)->findOneBy([
// 'name' => 'Adresse',
// 'prestataire' => $prestataire,
// 'geoloc' => $geolocFound
// ]);
// if (empty($geolocP)) {
// $geolocP = new GeolocPrestataire();
// $geolocP->setName('Adresse');
// $geolocP->setPrestataire($prestataire);
// $geolocP->setGeoloc($geolocFound);
// $prestataire->addGeoloc($geolocP);
// }
// } else {
$geolocP = new GeolocPrestataire();
$geolocP->setName('Adresse');
$geolocP->setPrestataire($prestataire);
$geolocFound = new Geoloc();
$geolocFound->setEnabled(true);
$geolocFound->setAdresse($adresse);
$geolocFound->setCpostal(intval($cpostal));
$geolocFound->setCpostal($cpostal);
$geolocFound->setVille($ville);
$geolocP->setGeoloc($geolocFound);
$prestataire->setGeolocs([$geolocP]);
$prestataire->addGeoloc($geolocP);
// }
if (!$this->test) {
$this->em->persist($geolocP);
$this->em->flush();
}
}
} else {
......@@ -684,12 +715,14 @@ class ImportController extends CRUDController
// Iterate over the reader and write each row to the database
// idmlc;groupe;email;prenom;nom;phone;mobile;adresse;cpostal;ville;cotisations
$line = 1;
$now = new DateTime();
foreach ($csvRows as $row) {
$hasError = false;
if (1 == $line) {
++$line;
continue;
}
// gc_collect_cycles();
$idmlc = array_key_exists('idmlc', $row) ? $row['idmlc'] : '';
$groupe = array_key_exists('groupe', $row) ? $row['groupe'] : '';
$firstname = array_key_exists('prenom', $row) ? $row['prenom'] : '';
......@@ -714,14 +747,13 @@ class ImportController extends CRUDController
$adherent = $this->em->getRepository(Adherent::class)->findOneBy(['idmlc' => $idmlc]);
}
if (empty($adherent)) {
$userFound = $this->em->getRepository(User::class)->findOneBy(['username' => $email]);
$userFound = $this->em->getRepository(User::class)->findOneBy(['email' => $email]);
if (!empty($userFound)) {
$adherent = $userFound->getAdherent();
}
}
if (empty($adherent)) {
$adherent = new Adherent();
$adherent->setIdmlc($idmlc);
$user = $this->userManager->createUser();
$user->setUsername($email);
$user->setEmail($email);
......@@ -733,7 +765,11 @@ class ImportController extends CRUDController
$user->setGroups([$usergroupe]);
$user->setAdherent($adherent);
$adherent->setUser($user);
} else {
$this->addWarning($row, $line, 'email', $this->translator->trans("L'adherent avec cet email '" . $email . "' existe déjà, on tente une mise à jour !"));
$user = $adherent->getUser();
}
$adherent->setIdmlc($idmlc);
if (!empty($firstname)) {
$user->setFirstname($firstname);
} else {
......@@ -744,21 +780,6 @@ class ImportController extends CRUDController
} else {
$this->addWarning($row, $line, 'nom', 'empty');
}
if (!empty($email)) {
$userFound = $this->em->getRepository(User::class)->findOneBy(['email' => $email]);
if (!empty($userFound)) {
$hasError = true;
$this->addError($row, $line, 'email', $this->translator->trans("L'email est déjà utilisé !"));
++$line;
++$this->nberrors;
continue;
} else {
$user->setEmail($email);
$user->setUsername($email);
}
} else {
$this->addWarning($row, $line, 'email', 'empty');
}
if (!empty($phone)) {
$user->setPhone($phone);
} else {
......@@ -774,34 +795,51 @@ class ImportController extends CRUDController
if (empty($groupeFound)) {
$groupeFound = new Groupe();
$groupeFound->setName($groupe);
$groupeFound->setSiege($this->siege);
$groupeFound->setSiege($this->em->getRepository(Siege::class)->getTheOne());
if (!$this->test) {
$this->em->persist($groupeFound);
$this->em->flush();
}
$this->addSuccess($row, $line, 'groupe', $this->translator->trans('Groupe ajouté : ') . $groupe);
}
if ($adherent->getGroupe() != $groupeFound) {
$adherent->setGroupe($groupeFound);
}
} else {
$this->addWarning($row, $line, 'groupe', 'empty');
}
$userLogguedIn = $this->em->merge($this->getUser());
if (!empty($cotisations)) {
$cotisationArray = explode(',', $cotisations);
if (count($cotisationArray) > 0) {
foreach ($cotisationArray as $cotisationDetails) {
$cotisationDetailsArray = explode(':', $cotisationDetails);
$cotisationFound = null;
if (!empty($adherent->getId())) {
if (1 == count($cotisationDetailsArray)) {
$cotisationFound = $this->em->getRepository(CotisationAdherent::class)->isCotisationAdherentExist($adherent, intval($cotisationDetails), date("Y"));
} else {
$cotisationFound = $this->em->getRepository(CotisationAdherent::class)->isCotisationAdherentExist($adherent, intval($cotisationDetailsArray[0]), $cotisationDetailsArray[1]);
}
}
if (!empty($cotisationFound)) {
$this->addWarning($row, $line, 'cotisation', $this->translator->trans("Cotisation déjà trouvée pour l'année ") . (1 == count($cotisationDetailsArray)) ? date("Y") : $cotisationDetailsArray[1]);
unset($cotisationFound);
} else {
$cotisation = new CotisationAdherent();
$now = new DateTime();
$cotisation->setRecu(true);
$cotisation->setReference('Import du ' . $now->format('d/m/Y H:i'));
$userLogguedIn = $this->em->merge($this->getUser());
$cotisation->setOperateur($userLogguedIn);
$cotisation->setRole('ROLE_ADHERENT');
$cotisation->setExpediteur($adherent);
$mlcPrestataire = $this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]);
$cotisation->setDestinataire($mlcPrestataire);
$cotisation->setMoyen(MoyenEnum::MOYEN_AUTRE);
$cotisationDetailsArray = explode(':', $cotisationDetails);
if (1 == count($cotisationDetailsArray)) {
$cotisation->setMontant(intval($cotisationDetails));
$cotisation->getCotisationInfos()->setAnnee(date("Y"));
$cotisation->getCotisationInfos()->setDebut($now);
$cotisation->getCotisationInfos()->setFin(new DateTime('+ 1 year'));
} else {
......@@ -810,15 +848,16 @@ class ImportController extends CRUDController
$cotisation->getCotisationInfos()->setDebut(DateTime::createFromFormat('Ymd', intval($cotisationDetailsArray[1]) . '0101'));
$cotisation->getCotisationInfos()->setFin(DateTime::createFromFormat('Ymd', intval($cotisationDetailsArray[1]) . '1231'));
}
// $this->em->persist($cotisation);
if (!$this->test) {
try {
$this->operationUtils->executeOperations($cotisation);
$this->addSuccess($row, $line, 'cotisations', $this->translator->trans('Cotisation(s) ajoutée(s) ligne : ') . $line);
} catch (\Exception $e) {
$this->addError($row, $line, 'cotisations', $this->translator->trans('Cotisation problème : ') . $e->getMessage());
}
$this->em->persist($cotisation);
}
// if (!$this->test) {
// try {
// $this->operationUtils->executeOperations($cotisation);
// $this->addSuccess($row, $line, 'cotisations', $this->translator->trans('Cotisation(s) ajoutée(s) ligne : ') . $line);
// } catch (\Exception $e) {
// $this->addError($row, $line, 'cotisations', $this->translator->trans('Cotisation problème : ') . $e->getMessage());
// }
// }
$this->addSuccess($row, $line, 'cotisations', $this->translator->trans('Cotisation(s) ajoutée(s) ligne : ') . $line);
}
}
......@@ -826,30 +865,36 @@ class ImportController extends CRUDController
$this->addWarning($row, $line, 'cotisations', 'empty');
}
if (!empty($adresse) || !empty($cpostal) || !empty($ville)) {
$geolocFound = $this->em->getRepository(Geoloc::class)->findOneBy([
'adresse' => $adresse,
'cpostal' => $cpostal,
'ville' => $ville,
]);
if (empty($geolocFound)) {
$geolocFound = new Geoloc();
$geolocFound->setAdresse($adresse);
$geolocFound->setCpostal(intval($cpostal));
$geolocFound->setCpostal($cpostal);
$geolocFound->setVille($ville);
$adherent->setGeoloc($geolocFound);
$this->em->persist($geolocFound);
$this->addSuccess($row, $line, 'adresse', $this->translator->trans('Adhérent : nouvelle adresse : ') . $geolocFound->__toString());
}
} else {
$this->addError($row, $line, 'email', $this->translator->trans("L'adherent avec cet email '" . $email . "' existe déjà, impossible de le réimporter !"));
++$this->nberrors;
$hasError = true;
}
if (!$hasError) {
$this->addSuccess($row, $line, 'user', $this->translator->trans('Adhérent bien ajouté ligne : ') . $line);
++$this->nbsuccess;
$user->setPasswordRequestedAt(new \DateTime());
if (!$this->test) {
$this->userManager->updateUser($user);
$this->userManager->updateUser($user, false);
if ($this->sendemail) {
$this->eventDispatcher->dispatch(MLCEvents::REGISTRATION_ADHERENT, new UserEvent($user, $this->getRequest()));
}
$this->em->flush();
$this->em->clear();
}
}
$this->em->flush();
$this->em->clear();
gc_collect_cycles();
++$line;
}
ksort($this->errors);
......@@ -1084,6 +1129,7 @@ class ImportController extends CRUDController
{
$cptGestionnaire = 1;
$users = new ArrayCollection();
$usergroupe = $this->em->getRepository(Usergroup::class)->findOneByName('Adherent');
while (array_key_exists('gestionnaire_email' . $cptGestionnaire, $row) && !empty($row['gestionnaire_email' . $cptGestionnaire]) && $cptGestionnaire < 10) {
$email = array_key_exists('gestionnaire_email' . $cptGestionnaire, $row) ? $row['gestionnaire_email' . $cptGestionnaire] : '';
......@@ -1106,7 +1152,6 @@ class ImportController extends CRUDController
$user->setConfirmationToken($this->tokenGenerator->generateToken());
$user->setEnabled(true);
$user->setPassword(md5(random_bytes(10)));
$usergroupe = $this->em->getRepository(Usergroup::class)->findOneByName('Adherent');
$user->addPossiblegroup($usergroupe);
$user->addPossiblegroup($groupe);
$user->setGroups([$groupe]);
......@@ -1122,8 +1167,11 @@ class ImportController extends CRUDController
$this->addSuccess($row, $line, 'gestionnaire', $this->translator->trans('Nouvel adhérent/gestionnaire' . $adherent . ' bien ajouté ligne : ') . $line);
if (!$this->test) {
$this->em->persist($user);
$this->userManager->updateUser($user);
$this->em->persist($adherent);
$this->em->flush();
// $this->em->clear();
gc_collect_cycles();
}
}
if (!$this->test && $this->sendemail) {
......
......@@ -130,12 +130,10 @@ class IndexController extends AbstractController
$siege = $form['siege']->getData();
$user = $form['user']->getData();
$groupe = $form['groupe']->getData();
$comptoir = $form['comptoir']->getData();
$configs = $form['config']->getData();
$iban = $form['iban']->getData();
$website = $form['website']->getData();
$groupe->setSiege($siege);
$comptoir->setGroupe($groupe);
//Création du prestataire recevant les cotisations
$presta = new Prestataire();
......@@ -203,17 +201,28 @@ class IndexController extends AbstractController
$this->em->persist($account);
$this->em->persist($groupe);
}
$comptoirData = $form['comptoir']->getData();
$comptoirName = $comptoirData['name'];
$comptoirCompte = $comptoirData['compte'];
$comptoirGeoloc = $comptoirData['geoloc'];
if (!empty($comptoir)) {
$comptoir = new Comptoir();
$comptoir->setName($comptoirName);
$comptoir->setEnabled(true);
$comptoir->setGeoloc($comptoirGeoloc);
$comptoir->setGroupe($groupe);
$this->em->persist($comptoir);
if (null == $comptoir->getAccountWithCurrency(CurrencyEnum::CURRENCY_MLC)) {
$account = new AccountComptoir();
$account
->setBalance($comptoir->getCompte())
->setBalance(empty($comptoirCompte) ? $comptoirCompte : 0)
->setCurrency(CurrencyEnum::CURRENCY_MLC)
;
$comptoir->addAccount($account);
$this->em->persist($account);
$this->em->persist($comptoir);
}
}
$this->userManager->updateUser($user);
$this->em->persist($presta);
if (null == $presta->getAccountWithCurrency(CurrencyEnum::CURRENCY_EMLC)) {
......
......@@ -57,4 +57,9 @@ class AccountAdherent extends Account
{
return $this->getAdherent();
}
public function __toString(): string
{
return 'AccountAdherent '.$this->getAdherent();
}
}
......@@ -14,6 +14,7 @@ use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Ramsey\Uuid\Doctrine\UuidGenerator;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\MaxDepth;
......@@ -32,6 +33,7 @@ use Symfony\Component\Serializer\Annotation\MaxDepth;
* denormalizationContext={"groups"={"write"}}
* )
* @ORM\Entity(repositoryClass="App\Repository\ComptoirRepository")
* @UniqueEntity(fields="slug", message="Name or Slug is already taken.")
* @ORM\HasLifecycleCallbacks()
* @ORM\Table(name="comptoir")
*/
......
......@@ -23,7 +23,7 @@ use Symfony\Component\Serializer\Annotation\Groups;
* TRANSACTION
* - Cotisation d'un adhérent.
*
* @ORM\Entity
* @ORM\Entity(repositoryClass="App\Repository\CotisationRepository")
*/
class CotisationAdherent extends Cotisation
{
......
......@@ -20,7 +20,7 @@ trait HasCompteEntity
/**
* @return int
*/
public function getCompte(): float
public function getCompte(): ?float
{
return $this->compte;
}
......@@ -30,7 +30,7 @@ trait HasCompteEntity
*
* @return $this
*/
public function setCompte(float $compte)
public function setCompte(?float $compte)
{
$this->compte = $compte;
......
......@@ -13,6 +13,7 @@ use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Ramsey\Uuid\Doctrine\UuidGenerator;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\MaxDepth;
......@@ -31,6 +32,7 @@ use Symfony\Component\Serializer\Annotation\MaxDepth;
* denormalizationContext={"groups"={"write"}}
* )
* @ORM\Entity
* @UniqueEntity(fields="slug", message="Name or Slug is already taken.")
* @ORM\Table(name="groupe")
* @ORM\HasLifecycleCallbacks()
*/
......
......@@ -12,6 +12,7 @@ use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Ramsey\Uuid\Doctrine\UuidGenerator;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
......@@ -30,6 +31,7 @@ use Symfony\Component\Validator\Constraints as Assert;
* denormalizationContext={"groups"={"write"}}
* )
* @ORM\Entity(repositoryClass="App\Repository\GroupeprestataireRepository")
* @UniqueEntity(fields="slug", message="Name or Slug is already taken.")
* @ORM\Table(name="groupeprestaire")
*/
class Groupeprestataire
......
......@@ -14,6 +14,7 @@ use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Ramsey\Uuid\Doctrine\UuidGenerator;
use SpecShaper\GdprBundle\Validator\Constraints as GdprAssert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
......@@ -32,6 +33,7 @@ use Symfony\Component\Validator\Constraints as Assert;
* denormalizationContext={"groups"={"write"}}
* )
* @ORM\Entity(repositoryClass="App\Repository\PrestataireRepository")
* @UniqueEntity(fields="slug", message="Raison or Slug is already taken.")
* @ORM\Table(name="prestataire")
* @ORM\HasLifecycleCallbacks()
*/
......
......@@ -18,17 +18,17 @@ class FirstComptoirFormType extends AbstractType
->add('enabled', HiddenType::class, array('data' => true))
->add('name', TextType::class, array(
'label' => 'Nom :',
'required' => true,
'required' => false,
'help' => "Vous pourrez éditer la description dans l'interface d'administration"
))
->add('geoloc', GeolocFormType::class, array(
'label' => 'Géolocalisation :',
'attr' => ['class' => 'ml-4'],
'required' => true
'required' => false
))
->add('compte', NumberType::class, array(
'label' => 'Solde de monnaie papier actuellement au comptoir :',
'required' => true
'required' => false
))
;
}
......@@ -36,7 +36,8 @@ class FirstComptoirFormType extends AbstractType
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Comptoir::class
'data_class' => null,
'validation_groups' => false,
]);
}
......
<?php
namespace App\Repository;
use App\Entity\Adherent;
use App\Entity\CotisationAdherent;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method CotisationAdherent|null find($id, $lockMode = null, $lockVersion = null)
* @method CotisationAdherent|null findOneBy(array $criteria, array $orderBy = null)
* @method CotisationAdherent[] findAll()
* @method CotisationAdherent[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class CotisationRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, CotisationAdherent::class);
$em = $this->getEntityManager();
$this->connection = $em->getConnection();
$this->tableName = $em->getMetadataFactory()->getMetadataFor(CotisationAdherent::class)->getTableName();
}
public function isCotisationAdherentExist(Adherent $adherent, $montant, $year): bool
{
$qb = $this->createQueryBuilder('f');
$result = $qb
->leftJoin('f.cotisationInfos', 'i')
->where("f.type = 'cotisation_adherent'")
->andWhere('f.montant = :montant')
->andWhere('f.expediteur = :adherent')
->andWhere('i.annee = :year')
->setParameter('montant', $montant)
->setParameter('adherent', $adherent)
->setParameter('year', $year)
->getQuery()
->getResult();
return !empty($result);
}
}
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