ImportController.php 60.2 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?php

namespace App\Controller;

use App\Entity\Adherent;
use App\Entity\Comptoir;
use App\Entity\ContactComptoir;
use App\Entity\ContactPrestataire;
use App\Entity\CotisationAdherent;
use App\Entity\CotisationPrestataire;
use App\Entity\EtatPrestataire;
use App\Entity\Geoloc;
use App\Entity\GeolocPrestataire;
use App\Entity\Groupe;
use App\Entity\Import;
use App\Entity\Prestataire;
use App\Entity\Rubrique;
use App\Entity\Siege;
use App\Entity\User;
use App\Entity\Usergroup;
21 22
use App\Enum\CurrencyEnum;
use App\Enum\FluxEnum;
Julien Jorry committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
use App\Enum\ImportEnum;
use App\Enum\MoyenEnum;
use App\Events\MLCEvents;
use App\Form\Type\ImportFormType;
use App\Utils\CustomEntityManager;
use App\Utils\OperationUtils;
use Behat\Transliterator\Transliterator;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Util\TokenGeneratorInterface;
use Sonata\AdminBundle\Controller\CRUDController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Translation\TranslatorInterface;

class ImportController extends CRUDController
{
    protected $header;
    protected $warnings;
    protected $errors;
    protected $nberrors;
    protected $nbsuccess;
    protected $success;
    protected $lineErrors;
    protected $em;
    protected $file;
    protected $security;
    protected $userManager;
    protected $translator;
    protected $tokenGenerator;
    protected $operationUtils;
56
    protected $test;
Julien Jorry committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

    public function __construct(CustomEntityManager $em, Security $security, UserManagerInterface $userManager, TranslatorInterface $translator, TokenGeneratorInterface $tokenGenerator, EventDispatcherInterface $eventDispatcher, OperationUtils $operationUtils)
    {
        $this->header = null;
        $this->warnings = [];
        $this->errors = [];
        $this->nberrors = 0;
        $this->nbsuccess = 0;
        $this->lineErrors = [];
        $this->em = $em;
        $this->security = $security;
        $this->userManager = $userManager;
        $this->translator = $translator;
        $this->tokenGenerator = $tokenGenerator;
        $this->eventDispatcher = $eventDispatcher;
        $this->operationUtils = $operationUtils;
        $this->sendemail = false;
74
        $this->test = false;
Julien Jorry committed
75 76 77 78 79 80 81 82 83 84 85
    }

    public function createAction()
    {
        $import = new Import();
        $userLogguedIn = $this->em->merge($this->getUser());
        $import->setUser($userLogguedIn);
        $form = $this->createForm(ImportFormType::class, $import);
        $form->handleRequest($this->getRequest());

        if ($form->isSubmitted() && $form->isValid()) {
86 87
            $this->em->getConnection()->getConfiguration()->setSQLLogger(null);
            gc_collect_cycles();
Julien Jorry committed
88 89 90 91
            $import = $form->getData();
            $media = $import->getMedia();
            $type = $import->getType();
            $this->sendemail = (bool) $import->getSendemail();
Julien Jorry committed
92
            $this->test = (bool) $import->getTest();
Julien Jorry committed
93

94 95 96 97 98 99
            // $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();
                $idimport = $import->getId();
Julien Jorry committed
100

101
                $this->importFromCSV($type, $media);
Julien Jorry committed
102

103 104
                $import = $this->em->getRepository(Import::class)->findOneById($idimport);
                $import->setEnabled(true);
Julien Jorry committed
105

106 107 108 109 110 111 112
                $import->setSuccess(json_encode($this->success));
                $import->setWarnings(json_encode($this->warnings));
                $import->setErrors(json_encode($this->errors));
                $import->setNbentityadded($this->nbsuccess);
                $import->setNbentityerror($this->nberrors);
                $this->em->persist($import);
                $this->em->flush();
Julien Jorry committed
113

114 115 116 117 118 119 120 121 122 123 124 125 126 127
                // $this->em->getConnection()->commit(); // commit all !

                if (empty($this->errors)) {
                    if ($this->test) {
                        $this->addFlash(
                            'success',
                            '(TEST) Import effectué avec succès !'
                        );
                    } else {
                        $this->addFlash(
                            'success',
                            'Import effectué avec succès !'
                        );
                    }
128 129
                } else {
                    $this->addFlash(
130 131
                        'error',
                        "Il y a eu des erreurs lors de l'import !"
132 133
                    );
                }
134 135
            } catch (Exception $e) {
                // $this->em->getConnection()->rollBack(); // Rollback all previous commit !
Julien Jorry committed
136 137
                $this->addFlash(
                    'error',
138
                    "Il y a eu une erreur lors de l'import : " . $e->getMessage()
Julien Jorry committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
                );
            }

            return $this->redirect($this->admin->generateUrl('show', ['id' => $import->getId()]));
        }

        return $this->renderWithExtraParams('@kohinos/admin/import.html.twig', [
            'action' => 'list',
            'form' => $form->createView(),
            'errors' => $this->errors,
            'warnings' => $this->warnings,
            'success' => $this->success,
            'linkcsverror' => (count($this->lineErrors) > 0) ? $this->generateUrl('getcsv', ['header' => $this->header, 'data' => array_values($this->lineErrors)]) : null,
            'csvparams' => $this->getParameter('app.import.header'),
        ]);
    }

    private function importFromCSV($type, $media)
    {
        // Turning off doctrine default logs queries for saving memory
        $this->em->getConnection()->getConfiguration()->setSQLLogger(null);

        // Get file provider
        $provider = $this->container->get($media->getProviderName());

        $csvRows = $this->parseCSV($provider->getFilesystem()->getAdapter()->getDirectory(), $provider->getReferenceImage($media));
        if (!mb_detect_encoding(implode(';', $csvRows[1]), 'UTF-8', true)) {
            $this->errors['error'] = $this->translator->trans("Le fichier n'est pas encodé en UTF-8 !");

            return [];
        }
        $this->header = implode(';', array_values($csvRows[0]));

        $config = $this->getParameter('app.import.header');

174
        $result = null;
Julien Jorry committed
175 176 177 178 179 180 181 182
        if (ImportEnum::IMPORT_ADHERENT == $type) {
            $result = $this->importAdherent($csvRows);
        } elseif (ImportEnum::IMPORT_PRESTATAIRE == $type) {
            $result = $this->importPrestataire($csvRows);
        } elseif (ImportEnum::IMPORT_GROUPE == $type) {
            $result = $this->importGroupe($csvRows);
        } elseif (ImportEnum::IMPORT_COMPTOIR == $type) {
            $result = $this->importComptoir($csvRows);
183 184
        } elseif (ImportEnum::IMPORT_OPERATION == $type) {
            $result = $this->importOperations($csvRows);
Julien Jorry committed
185 186 187 188 189 190 191
        } else {
            // Ne devrait jamais arriver, mais sait-on jamais !
            $this->errors['error'] = $this->translator->trans('Choisir un type de données à importer !');
        }

        return $result;
    }
192

193 194 195 196 197 198 199 200 201 202
    /**
     * Open and parse .CSV file.
     *
     * @param string $filePath        Path of the file
     * @param string $fileName        Name of the file
     * @param bool   $ignoreFirstLine If true, ignore first line
     *
     * @return array Array of parsed values with array's key = firstline
     */
    private function parseCSV($filePath, $fileName, $ignoreFirstLine = false)
Julien Jorry committed
203
    {
204
        $csv = new \SplFileObject($filePath . '/' . $fileName);
Julien Jorry committed
205

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        $rows = [];
        $firstline = null;
        if (($handle = fopen($csv->getRealPath(), 'r')) !== false) {
            $i = 0;
            while (($data = fgetcsv($handle, null, ';')) !== false) {
                ++$i;
                if (1 == $i) {
                    $firstline = $data;
                    $rows[] = $data;
                    if ($ignoreFirstLine) {
                        continue;
                    }
                } else {
                    if (count($firstline) != count($data)) {
                        $this->addError($data, $i, 'Ligne entière', $this->translator->trans("La ligne ne contient pas le bon nombre d'éléments requis !"));
                        ++$this->nberrors;
                        continue;
                    }
                    $rows[] = array_combine(array_values($firstline), array_values($data));
                }
            }
            fclose($handle);
        }

        return $rows;
Julien Jorry committed
231 232 233 234 235
    }

    private function importComptoir($csvRows)
    {
        // Iterate over the reader and write each row to the database
236
        //idmlc;groupe;nom;description;adresse;cpostal;ville;latitude;longitude;compte;gestionnaire_email1;gestionnaire_nom1;gestionnaire_prenom1;gestionnaire_phone1;gestionnaire_mobile1;contact1;phone1;email1;contact2;phone2;email2
Julien Jorry committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
        $line = 1;
        foreach ($csvRows as $row) {
            if (1 == $line) {
                ++$line;
                continue;
            }
            if (!(array_key_exists('groupe', $row) && array_key_exists('nom', $row))) {
                $this->addError($row, $line, 'nom & groupe', $this->translator->trans("Les colonnes 'nom' et 'groupe' sont obligatoires !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }

            $groupe = array_key_exists('groupe', $row) ? $row['groupe'] : '';
            $nom = array_key_exists('nom', $row) ? $row['nom'] : '';
            if (empty($groupe)) {
                $this->addError($row, $line, 'groupe', $this->translator->trans("Le 'groupe' est obligatoire !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            if (empty($nom)) {
                $this->addError($row, $line, 'nom', $this->translator->trans("Le 'nom' est obligatoire !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
264
            $idmlc = array_key_exists('idmlc', $row) ? $row['idmlc'] : '';
Julien Jorry committed
265 266 267 268 269 270 271 272 273 274 275 276
            $description = array_key_exists('description', $row) ? $row['description'] : '';
            $adresse = array_key_exists('adresse', $row) ? $row['adresse'] : '';
            $cpostal = array_key_exists('cpostal', $row) ? $row['cpostal'] : '';
            $ville = array_key_exists('ville', $row) ? $row['ville'] : '';
            $latitude = array_key_exists('latitude', $row) ? $row['latitude'] : '';
            $longitude = array_key_exists('longitude', $row) ? $row['longitude'] : '';
            $compte = array_key_exists('compte', $row) ? $row['compte'] : '';

            $groupeFound = $this->em->getRepository(Groupe::class)->findOneBy(['slug' => $this->slugify($groupe)]);
            if (empty($groupeFound)) {
                $groupeFound = new Groupe();
                $groupeFound->setName($groupe);
277
                $groupeFound->setSiege($this->em->getRepository(Siege::class)->getTheOne());
278 279 280
                if (!$this->test) {
                    $this->em->persist($groupeFound);
                }
Julien Jorry committed
281 282 283 284 285
                $this->addSuccess($row, $line, 'groupe', $this->translator->trans('Groupe ajouté : ') . $groupe);
            }
            $comptoir = $this->em->getRepository(Comptoir::class)->findOneBy(['slug' => $this->slugify($nom), 'groupe' => $groupeFound]);
            if (empty($comptoir)) {
                $comptoir = new Comptoir();
286
                $comptoir->setIdmlc($idmlc);
Julien Jorry committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
                $comptoir->setGroupe($groupeFound);
                $comptoir->setName($nom);
                if (!empty($description)) {
                    $comptoir->setContent($description);
                } else {
                    $this->addWarning($row, $line, 'description', 'empty');
                }
                if (!empty($compte)) {
                    $comptoir->setCompte($this->tofloat($compte));
                } else {
                    $this->addWarning($row, $line, 'compte', 'empty');
                }
                if (!empty($adresse) || !empty($cpostal) || !empty($ville)) {
                    $geolocFound = new Geoloc();
                    $geolocFound->setAdresse($adresse);
302
                    $geolocFound->setCpostal($cpostal);
Julien Jorry committed
303 304
                    $geolocFound->setVille($ville);
                    if (!empty($latitude) && !empty($longitude)) {
Julien Jorry committed
305 306
                        $geolocFound->setLat(floatval(str_replace(',', '.', $latitude)));
                        $geolocFound->setLon(floatval(str_replace(',', '.', $longitude)));
Julien Jorry committed
307 308 309 310 311 312 313 314 315
                    }
                    $comptoir->setGeoloc($geolocFound);
                }
                // Importer les contacts du comptoir s'ils existent (par défaut en public)
                $cptContact = 1;
                while (array_key_exists('contact' . $cptContact, $row) && $cptContact < 10) {
                    $contact = array_key_exists('contact' . $cptContact, $row) ? $row['contact' . $cptContact] : '';
                    $phone = array_key_exists('phone' . $cptContact, $row) ? $row['phone' . $cptContact] : '';
                    $email = array_key_exists('email' . $cptContact, $row) ? $row['email' . $cptContact] : '';
Julien Jorry committed
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
                    if (!empty(trim($contact))) {
                        $contactC = $this->em->getRepository(ContactComptoir::class)->findOneBy(['comptoir' => $comptoir, 'name' => $contact]);
                        if (empty($contactComptoir)) {
                            $contactC = new ContactComptoir();
                        }
                        $contactC->setComptoir($comptoir);
                        $contactC->setEnabled(true);
                        $contactC->setName($contact);
                        $contactC->setTel($phone);
                        $contactC->setEmail($email);
                        if (!$this->test) {
                            $this->em->persist($contactC);
                        }
                        $this->addSuccess($row, $line, 'contact', $this->translator->trans('Contact ajouté : ') . $contactC);
                    } else {
                        break;
332
                    }
Julien Jorry committed
333 334 335 336 337
                    ++$cptContact;
                }

                // Importer les gestionnaires de comptoir s'ils existent
                $groupeGestionnaire = $this->em->getRepository(Usergroup::class)->findOneByName('Comptoir');
Julien Jorry committed
338
                $gestionnaires = $this->importGestionnaires($row, $line, $groupeGestionnaire);
Julien Jorry committed
339 340 341 342
                $comptoir->setGestionnaires($gestionnaires);

                $this->addSuccess($row, $line, 'comptoir', $this->translator->trans('Comptoir ajouté : ') . $nom);
                ++$this->nbsuccess;
343 344 345
                if (!$this->test) {
                    $this->em->persist($comptoir);
                    $this->em->flush();
346
                    // $this->em->clear();
347
                }
Julien Jorry committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361
            } else {
                $this->addError($row, $line, 'nom', $this->translator->trans('Le comptoir avec ce nom {name} existe déjà !', ['name' => $nom]));
                ++$this->nberrors;
            }

            ++$line;
        }
        ksort($this->errors);
        ksort($this->warnings);
    }

    private function importGroupe($csvRows)
    {
        // Iterate over the reader and write each row to the database
362
        // idmlc;nom;description;compte;gestionnaire_email1;gestionnaire_nom1;gestionnaire_prenom1;gestionnaire_phone1;gestionnaire_mobile1
Julien Jorry committed
363 364 365 366 367 368 369 370 371 372 373 374 375
        $line = 1;
        foreach ($csvRows as $row) {
            if (1 == $line) {
                ++$line;
                continue;
            }
            $name = array_key_exists('nom', $row) ? $row['nom'] : '';
            if (empty($name)) {
                $this->addError($row, $line, 'nom', $this->translator->trans("Le 'nom' est obligatoire !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
376
            $idmlc = array_key_exists('idmlc', $row) ? $row['idmlc'] : '';
Julien Jorry committed
377 378
            $description = array_key_exists('description', $row) ? $row['description'] : '';
            $compte = array_key_exists('compte', $row) ? $row['compte'] : '';
379 380 381 382 383 384 385
            $groupe = null;
            if (!empty($idmlc)) {
                $groupe = $this->em->getRepository(Groupe::class)->findOneBy(['idmlc' => $idmlc]);
            }
            if (empty($groupe)) {
                $groupe = $this->em->getRepository(Groupe::class)->findOneBy(['slug' => $this->slugify($name)]);
            }
Julien Jorry committed
386 387
            if (empty($groupe)) {
                $groupe = new Groupe();
388
                $groupe->setIdmlc($idmlc);
Julien Jorry committed
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
                $groupe->setSiege($this->em->getRepository(Siege::class)->getTheOne());
                if (!empty($name)) {
                    $groupe->setName($name);
                } else {
                    $this->addWarning($row, $line, 'name', 'empty');
                }
                if (!empty($content)) {
                    $groupe->setContent($content);
                } else {
                    $this->addWarning($row, $line, 'content', 'empty');
                }
                if (!empty($compte)) {
                    $groupe->setCompte($this->tofloat($compte));
                } else {
                    $this->addWarning($row, $line, 'compte', 'empty');
                }
                // Importer les gestionnaires du groupe s'ils existent
                $groupeGestionnaire = $this->em->getRepository(Usergroup::class)->findOneByName('Gestionnaire de Groupe');
Julien Jorry committed
407
                $gestionnaires = $this->importGestionnaires($row, $line, $groupeGestionnaire);
Julien Jorry committed
408 409 410 411
                $groupe->setGestionnaires($gestionnaires);

                $this->addSuccess($row, $line, 'groupe', $this->translator->trans('Groupe ajouté : ') . $name);
                ++$this->nbsuccess;
412 413 414
                if (!$this->test) {
                    $this->em->persist($groupe);
                    $this->em->flush();
415
                    // $this->em->clear();
416
                }
Julien Jorry committed
417 418 419 420 421 422 423 424 425 426
            } else {
                $this->addError($row, $line, 'name', $this->translator->trans("Le groupe avec ce nom '" . $name . "' existe déjà !"));
                ++$this->nberrors;
            }
            ++$line;
        }
        ksort($this->errors);
        ksort($this->warnings);
    }

427 428 429 430 431
    private function importGroupePrestataire($csvRows)
    {
        // @TODO
    }

Julien Jorry committed
432 433 434
    private function importPrestataire($csvRows)
    {
        // Iterate over the reader and write each row to the database
435
        // idmlc;groupe;adresse;cpostal;ville;raison;metier;statut;responsable;iban;siret;web;horaires;description;rubriques;tags;tauxreconversion;cotisations;gestionnaire_email1;gestionnaire_nom1;gestionnaire_prenom1;gestionnaire_phone1;gestionnaire_mobile1;contact1;phone1;email1;contact2;phone2;email2
Julien Jorry committed
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        $line = 1;
        foreach ($csvRows as $row) {
            $hasError = false;
            if (1 == $line) {
                ++$line;
                continue;
            }
            if (!array_key_exists('groupe', $row)) {
                $this->addError($row, $line, 'groupe', $this->translator->trans("La colonne 'groupe' est obligatoire !"));
            }
            if (!array_key_exists('adresse', $row)) {
                $this->addError($row, $line, 'adresse', $this->translator->trans("La colonne 'adresse' est obligatoire !"));
            }
            if (!array_key_exists('cpostal', $row)) {
                $this->addError($row, $line, 'cpostal', $this->translator->trans("La colonne 'cpostal' est obligatoire !"));
            }
            if (!array_key_exists('ville', $row)) {
                $this->addError($row, $line, 'ville', $this->translator->trans("La colonne 'ville' est obligatoire !"));
            }
            if (!array_key_exists('raison', $row)) {
                $this->addError($row, $line, 'raison', $this->translator->trans("La colonne 'raison' est obligatoire !"));
            }
            if (!(array_key_exists('groupe', $row) && array_key_exists('adresse', $row) && array_key_exists('cpostal', $row) && array_key_exists('ville', $row) && array_key_exists('raison', $row))) {
                ++$line;
                ++$this->nberrors;
                continue;
            }
            $groupe = array_key_exists('groupe', $row) ? $row['groupe'] : '';
            $adresse = array_key_exists('adresse', $row) ? $row['adresse'] : '';
            $cpostal = array_key_exists('cpostal', $row) ? $row['cpostal'] : '';
            $ville = array_key_exists('ville', $row) ? $row['ville'] : '';
            $raison = array_key_exists('raison', $row) ? $row['raison'] : '';
            if (empty($groupe)) {
                $this->addError($row, $line, 'groupe', $this->translator->trans("Le 'groupe' est obligatoire !"));
            }
            if (empty($adresse)) {
                $this->addError($row, $line, 'adresse', $this->translator->trans("Le 'adresse' est obligatoire !"));
            }
            if (empty($cpostal)) {
                $this->addError($row, $line, 'cpostal', $this->translator->trans("Le 'cpostal' est obligatoire !"));
            }
            if (empty($ville)) {
                $this->addError($row, $line, 'ville', $this->translator->trans("Le 'ville' est obligatoire !"));
            }
            if (empty($raison)) {
                $this->addError($row, $line, 'raison', $this->translator->trans("Le 'raison' est obligatoire !"));
            }
            if (empty($groupe) || empty($adresse) || empty($cpostal) || empty($ville) || empty($raison)) {
                ++$this->nberrors;
                ++$line;
                continue;
            }
488
            $idmlc = array_key_exists('idmlc', $row) ? $row['idmlc'] : '';
Julien Jorry committed
489 490 491 492 493 494 495 496 497 498 499 500 501
            $metier = array_key_exists('metier', $row) ? $row['metier'] : '';
            $statut = array_key_exists('statut', $row) ? $row['statut'] : '';
            $responsable = array_key_exists('responsable', $row) ? $row['responsable'] : '';
            $iban = array_key_exists('iban', $row) ? $row['iban'] : '';
            $siret = array_key_exists('siret', $row) ? $row['siret'] : '';
            $web = array_key_exists('web', $row) ? $row['web'] : '';
            $horaires = array_key_exists('horaires', $row) ? $row['horaires'] : '';
            $description = array_key_exists('description', $row) ? $row['description'] : '';
            $rubriques = array_key_exists('rubriques', $row) ? $row['rubriques'] : '';
            $tags = array_key_exists('tags', $row) ? $row['tags'] : '';
            $tauxreconversion = array_key_exists('tauxreconversion', $row) ? $row['tauxreconversion'] : '';
            $cotisations = array_key_exists('cotisations', $row) ? $row['cotisations'] : '';

502 503 504 505 506 507 508
            $prestataire = null;
            if (!empty($idmlc)) {
                $prestataire = $this->em->getRepository(Prestataire::class)->findOneBy(['idmlc' => $idmlc]);
            }
            if (empty($prestataire)) {
                $prestataire = $this->em->getRepository(Prestataire::class)->findOneBy(['slug' => $this->slugify($raison)]);
            }
Julien Jorry committed
509 510
            if (empty($prestataire)) {
                $prestataire = new Prestataire();
511
                $prestataire->setIdmlc($idmlc);
Julien Jorry committed
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563

                if (!empty($raison)) {
                    $prestataire->setRaison($raison);
                } else {
                    $this->addWarning($row, $line, 'raison', 'empty');
                }
                if (!empty($metier)) {
                    $prestataire->setMetier($metier);
                } else {
                    $this->addWarning($row, $line, 'metier', 'empty');
                }
                if (!empty($statut)) {
                    $prestataire->setStatut($statut);
                } else {
                    $this->addWarning($row, $line, 'statut', 'empty');
                }
                if (!empty($responsable)) {
                    $prestataire->setResponsable($responsable);
                } else {
                    $this->addWarning($row, $line, 'responsable', 'empty');
                }
                if (!empty($iban)) {
                    $prestataire->setIban($iban);
                } else {
                    $this->addWarning($row, $line, 'iban', 'empty');
                }
                if (!empty($siret)) {
                    $prestataire->setSiret($siret);
                } else {
                    $this->addWarning($row, $line, 'siret', 'empty');
                }
                if (!empty($web)) {
                    $prestataire->setWeb($web);
                } else {
                    $this->addWarning($row, $line, 'web', 'empty');
                }
                if (!empty($horaires)) {
                    $prestataire->setHoraires($horaires);
                } else {
                    $this->addWarning($row, $line, 'horaires', 'empty');
                }
                if (!empty($description)) {
                    $prestataire->setDescription($description);
                } else {
                    $this->addWarning($row, $line, 'description', 'empty');
                }

                $cptContact = 1;
                while (array_key_exists('contact' . $cptContact, $row) && $cptContact < 10) {
                    $contact = array_key_exists('contact' . $cptContact, $row) ? $row['contact' . $cptContact] : '';
                    $phone = array_key_exists('phone' . $cptContact, $row) ? $row['phone' . $cptContact] : '';
                    $email = array_key_exists('email' . $cptContact, $row) ? $row['email' . $cptContact] : '';
Julien Jorry committed
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
                    if (!empty(trim($contact))) {
                        $contactC = $this->em->getRepository(ContactPrestataire::class)->findOneBy(['prestataire' => $prestataire, 'name' => $contact]);
                        if (empty($contactC)) {
                            $contactC = new ContactPrestataire();
                        }
                        $contactC->setPrestataire($prestataire);
                        $contactC->setEnabled(true);
                        $contactC->setName($contact);
                        $contactC->setTel($phone);
                        $contactC->setEmail($email);
                        if (!$this->test) {
                            $this->em->persist($contactC);
                        }
                        $this->addSuccess($row, $line, 'contact', $this->translator->trans('Contact ajouté : ') . $contact);
                    } else {
                        break;
580
                    }
Julien Jorry committed
581 582 583 584
                    ++$cptContact;
                }
                // Importer les gestionnaires du prestataire s'ils existent
                $groupeGestionnaire = $this->em->getRepository(Usergroup::class)->findOneByName('Prestataire');
Julien Jorry committed
585
                $gestionnaires = $this->importGestionnaires($row, $line, $groupeGestionnaire);
Julien Jorry committed
586 587 588
                if (!$this->test) {
                    $prestataire->setUsers($gestionnaires);
                }
Julien Jorry committed
589 590 591 592 593 594

                if (!empty($groupe)) {
                    $groupeFound = $this->em->getRepository(Groupe::class)->findOneBy(['slug' => $this->slugify($groupe)]);
                    if (empty($groupeFound)) {
                        $groupeFound = new Groupe();
                        $groupeFound->setName($groupe);
595
                        $groupeFound->setSiege($this->em->getRepository(Siege::class)->getTheOne());
596 597 598
                        if (!$this->test) {
                            $this->em->persist($groupeFound);
                        }
Julien Jorry committed
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
                        $this->addWarning($row, $line, 'groupe', $this->translator->trans('Groupe introuvable, création du groupe : ') . $groupe);
                    }
                    $prestataire->setGroupe($groupeFound);
                } else {
                    $this->addWarning($row, $line, 'groupe', 'empty');
                }
                if (!empty($cotisations)) {
                    $cotisationArray = explode(',', $cotisations);
                    if (count($cotisationArray) > 0) {
                        foreach ($cotisationArray as $cotisationDetails) {
                            $cotisation = new CotisationPrestataire();
                            $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_SUPER_ADMIN');
                            $cotisation->setExpediteur($prestataire);
                            $cotisation->setMoyen(MoyenEnum::MOYEN_AUTRE);
                            $cotisationDetailsArray = explode(':', $cotisationDetails);
                            if (1 == count($cotisationDetailsArray)) {
                                $cotisation->setMontant(intval($cotisationDetails));
                                $cotisation->getCotisationInfos()->setDebut($now);
                                $cotisation->getCotisationInfos()->setFin(new DateTime('+ 1 year'));
                            } else {
                                $cotisation->setMontant(intval($cotisationDetailsArray[0]));
                                $cotisation->getCotisationInfos()->setAnnee($cotisationDetailsArray[1]);
                                $cotisation->getCotisationInfos()->setDebut(DateTime::createFromFormat('Ymd', intval($cotisationDetailsArray[1]) . '0101'));
                                $cotisation->getCotisationInfos()->setFin(DateTime::createFromFormat('Ymd', intval($cotisationDetailsArray[1]) . '1231'));
                            }
629 630
                            if (!$this->test) {
                                $this->em->persist($cotisation);
Julien Jorry committed
631
                            }
632
                            $this->addSuccess($row, $line, 'cotisations', $this->translator->trans('Cotisation(s) ajoutée(s) ligne : ') . $line);
Julien Jorry committed
633 634 635 636 637 638 639 640 641 642 643 644
                        }
                    }
                } else {
                    $this->addWarning($row, $line, 'cotisations', 'empty');
                }
                if (!empty($rubriques)) {
                    $rubriquesArray = explode(',', $rubriques);
                    foreach ($rubriquesArray as $rubrique) {
                        $rubriqueFound = $this->em->getRepository(Rubrique::class)->findOneBy(['slug' => $this->slugify($rubrique)]);
                        if (empty($rubriqueFound)) {
                            $rubriqueFound = new Rubrique();
                            $rubriqueFound->setName($rubrique);
645 646 647
                            if (!$this->test) {
                                $this->em->persist($rubriqueFound);
                            }
Julien Jorry committed
648 649 650 651 652 653 654 655 656 657 658 659 660 661
                            $this->addSuccess($row, $line, 'rubrique', $this->translator->trans('Rubrique ajoutée : ') . $rubrique);
                        }
                        $prestataire->addRubrique($rubriqueFound);
                    }
                } else {
                    $this->addWarning($row, $line, 'rubriques', 'empty');
                }
                if (!empty($tags)) {
                    $tagsArray = explode(',', $tags);
                    foreach ($tagsArray as $tag) {
                        $tagFound = $this->em->getRepository(EtatPrestataire::class)->findOneBy(['slug' => $this->slugify($tag)]);
                        if (empty($tagFound)) {
                            $tagFound = new EtatPrestataire();
                            $tagFound->setName($tag);
662 663 664
                            if (!$this->test) {
                                $this->em->persist($tagFound);
                            }
Julien Jorry committed
665 666 667 668 669 670 671 672
                            $this->addSuccess($row, $line, 'tag', $this->translator->trans('Tag ajouté : ') . $tag);
                        }
                        $prestataire->addEtat($tagFound);
                    }
                } else {
                    $this->addWarning($row, $line, 'tags', 'empty');
                }
                if (!empty($adresse) || !empty($cpostal) || !empty($ville)) {
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
                    // $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 {
Julien Jorry committed
692 693 694 695 696 697
                    $geolocP = new GeolocPrestataire();
                    $geolocP->setName('Adresse');
                    $geolocP->setPrestataire($prestataire);
                    $geolocFound = new Geoloc();
                    $geolocFound->setEnabled(true);
                    $geolocFound->setAdresse($adresse);
698
                    $geolocFound->setCpostal($cpostal);
Julien Jorry committed
699 700
                    $geolocFound->setVille($ville);
                    $geolocP->setGeoloc($geolocFound);
701 702
                    $prestataire->addGeoloc($geolocP);
                    // }
703 704
                    if (!$this->test) {
                        $this->em->persist($geolocP);
705
                        $this->em->flush();
706
                    }
Julien Jorry committed
707 708
                }
            } else {
709
                $this->addError($row, $line, 'name', $this->translator->trans("Le prestataire avec cette raison '" . $raison . "' existe déjà, impossible de le réimporter !"));
Julien Jorry committed
710 711 712 713 714 715
                ++$this->nberrors;
                $hasError = true;
            }
            if (!$hasError) {
                $this->addSuccess($row, $line, 'user', $this->translator->trans('Prestataire ajouté : ') . $prestataire->__toString());
                ++$this->nbsuccess;
716 717 718 719 720
                if (!$this->test) {
                    $this->em->persist($prestataire);
                    $this->em->flush();
                    $this->em->clear();
                }
Julien Jorry committed
721 722 723 724 725 726 727 728 729 730 731
            }

            ++$line;
        }
        ksort($this->errors);
        ksort($this->warnings);
    }

    private function importAdherent($csvRows)
    {
        // Iterate over the reader and write each row to the database
732
        // idmlc;groupe;email;prenom;nom;phone;mobile;adresse;cpostal;ville;cotisations
Julien Jorry committed
733
        $line = 1;
734
        $now = new DateTime();
Julien Jorry committed
735 736 737 738 739 740
        foreach ($csvRows as $row) {
            $hasError = false;
            if (1 == $line) {
                ++$line;
                continue;
            }
741
            // gc_collect_cycles();
742
            $idmlc = array_key_exists('idmlc', $row) ? $row['idmlc'] : '';
Julien Jorry committed
743 744 745 746 747 748 749 750 751 752 753
            $groupe = array_key_exists('groupe', $row) ? $row['groupe'] : '';
            $firstname = array_key_exists('prenom', $row) ? $row['prenom'] : '';
            $lastname = array_key_exists('nom', $row) ? $row['nom'] : '';
            $email = array_key_exists('email', $row) ? $row['email'] : '';
            $phone = array_key_exists('phone', $row) ? $row['phone'] : '';
            $mobile = array_key_exists('mobile', $row) ? $row['mobile'] : '';
            $adresse = array_key_exists('adresse', $row) ? $row['adresse'] : '';
            $cpostal = array_key_exists('cpostal', $row) ? $row['cpostal'] : '';
            $ville = array_key_exists('ville', $row) ? $row['ville'] : '';
            $cotisations = array_key_exists('cotisations', $row) ? $row['cotisations'] : '';

Julien Jorry committed
754
            if (empty($email)) {
Julien Jorry committed
755 756 757 758 759 760
                $this->addError($row, $line, 'email', $this->translator->trans("La colonne 'email' est obligatoire !"));
                ++$line;
                ++$this->nberrors;
                continue;
            }

761 762 763
            $adherent = null;
            if (!empty($idmlc)) {
                $adherent = $this->em->getRepository(Adherent::class)->findOneBy(['idmlc' => $idmlc]);
Julien Jorry committed
764
            }
765
            if (empty($adherent)) {
766
                $userFound = $this->em->getRepository(User::class)->findOneBy(['email' => $email]);
Julien Jorry committed
767 768 769
                if (!empty($userFound)) {
                    $adherent = $userFound->getAdherent();
                }
Julien Jorry committed
770
            }
771 772 773
            if (empty($adherent)) {
                $adherent = new Adherent();
                $user = $this->userManager->createUser();
Julien Jorry committed
774 775
                $user->setUsername($email);
                $user->setEmail($email);
776 777 778 779 780 781 782 783
                $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->setGroups([$usergroupe]);
                $user->setAdherent($adherent);
                $adherent->setUser($user);
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
            } 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 {
                $this->addWarning($row, $line, 'prenom', 'empty');
            }
            if (!empty($lastname)) {
                $user->setLastname($lastname);
            } else {
                $this->addWarning($row, $line, 'nom', 'empty');
            }
            if (!empty($phone)) {
                $user->setPhone($phone);
            } else {
                $this->addWarning($row, $line, 'phone', 'empty');
            }
            if (!empty($mobile)) {
                $user->setMobile($mobile);
            } else {
                $this->addWarning($row, $line, 'mobile', 'empty');
            }
            if (!empty($groupe)) {
                $groupeFound = $this->em->getRepository(Groupe::class)->findOneBy(['slug' => $this->slugify($groupe)]);
                if (empty($groupeFound)) {
                    $groupeFound = new Groupe();
                    $groupeFound->setName($groupe);
                    $groupeFound->setSiege($this->em->getRepository(Siege::class)->getTheOne());
                    if (!$this->test) {
                        $this->em->persist($groupeFound);
                        $this->em->flush();
818
                    }
819
                    $this->addSuccess($row, $line, 'groupe', $this->translator->trans('Groupe ajouté : ') . $groupe);
820
                }
821
                if ($adherent->getGroupe() != $groupeFound) {
822 823
                    $adherent->setGroupe($groupeFound);
                }
824 825 826
            } else {
                $this->addWarning($row, $line, 'groupe', 'empty');
            }
Julien Jorry committed
827 828 829
            if (!$this->test) {
                $this->em->persist($adherent);
            }
830 831 832 833 834 835 836 837 838 839

            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)) {
840
                                $cotisationFound = $this->em->getRepository(CotisationAdherent::class)->isCotisationAdherentExist($adherent, intval($cotisationDetails), date('Y'));
841 842 843 844 845
                            } else {
                                $cotisationFound = $this->em->getRepository(CotisationAdherent::class)->isCotisationAdherentExist($adherent, intval($cotisationDetailsArray[0]), $cotisationDetailsArray[1]);
                            }
                        }
                        if (!empty($cotisationFound)) {
846
                            $this->addWarning($row, $line, 'cotisation', $this->translator->trans("Cotisation déjà trouvée pour l'année ") . (1 == count($cotisationDetailsArray)) ? date('Y') : $cotisationDetailsArray[1]);
847 848
                            unset($cotisationFound);
                        } else {
849 850 851
                            $cotisation = new CotisationAdherent();
                            $cotisation->setRecu(true);
                            $cotisation->setReference('Import du ' . $now->format('d/m/Y H:i'));
852
                            $userLogguedIn = $this->em->merge($this->getUser());
853 854 855 856 857 858 859 860
                            $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);
                            if (1 == count($cotisationDetailsArray)) {
                                $cotisation->setMontant(intval($cotisationDetails));
861
                                $cotisation->getCotisationInfos()->setAnnee(date('Y'));
862 863 864 865 866 867 868 869
                                $cotisation->getCotisationInfos()->setDebut($now);
                                $cotisation->getCotisationInfos()->setFin(new DateTime('+ 1 year'));
                            } else {
                                $cotisation->setMontant(intval($cotisationDetailsArray[0]));
                                $cotisation->getCotisationInfos()->setAnnee($cotisationDetailsArray[1]);
                                $cotisation->getCotisationInfos()->setDebut(DateTime::createFromFormat('Ymd', intval($cotisationDetailsArray[1]) . '0101'));
                                $cotisation->getCotisationInfos()->setFin(DateTime::createFromFormat('Ymd', intval($cotisationDetailsArray[1]) . '1231'));
                            }
Julien Jorry committed
870 871 872
                            if (!$this->test) {
                                $this->em->persist($cotisation);
                            }
Julien Jorry committed
873
                        }
874 875 876 877 878 879 880 881 882
                        // 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);
Julien Jorry committed
883
                    }
884
                }
885 886 887 888 889 890 891 892 893 894
            } else {
                $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)) {
895 896
                    $geolocFound = new Geoloc();
                    $geolocFound->setAdresse($adresse);
897
                    $geolocFound->setCpostal($cpostal);
898 899
                    $geolocFound->setVille($ville);
                    $adherent->setGeoloc($geolocFound);
Julien Jorry committed
900 901 902
                    if (!$this->test) {
                        $this->em->persist($geolocFound);
                    }
903
                    $this->addSuccess($row, $line, 'adresse', $this->translator->trans('Adhérent : nouvelle adresse : ') . $geolocFound->__toString());
Julien Jorry committed
904 905
                }
            }
906

Julien Jorry committed
907 908 909 910
            if (!$hasError) {
                $this->addSuccess($row, $line, 'user', $this->translator->trans('Adhérent bien ajouté ligne : ') . $line);
                ++$this->nbsuccess;
                $user->setPasswordRequestedAt(new \DateTime());
Julien Jorry committed
911 912 913 914
                if (!$this->test) {
                    if ($this->sendemail) {
                        $this->eventDispatcher->dispatch(MLCEvents::REGISTRATION_ADHERENT, new UserEvent($user, $this->getRequest()));
                    }
Julien Jorry committed
915 916
                }
            }
917 918 919
            $this->em->flush();
            $this->em->clear();
            gc_collect_cycles();
Julien Jorry committed
920 921 922 923 924 925
            ++$line;
        }
        ksort($this->errors);
        ksort($this->warnings);
    }

926
    private function importOperations($csvRows)
Julien Jorry committed
927
    {
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
        // Iterate over the reader and write each row to the database
        //exp_idmlc|exp;exp_type;dest_idmlc|dest;dest_type;user_email;montant;devise;date;type;moyen;reference;tauxreconversion;data
        $line = 1;
        foreach ($csvRows as $row) {
            if (1 == $line) {
                ++$line;
                continue;
            }
            if (!(array_key_exists('exp_idmlc', $row) || array_key_exists('exp', $row))) {
                $this->addError($row, $line, 'exp_idmlc or exp', $this->translator->trans("La colonne 'exp_idmlc' ou 'exp' est obligatoire !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            if (!(array_key_exists('dest_idmlc', $row) || array_key_exists('dest', $row))) {
                $this->addError($row, $line, 'dest_idmlc or dest', $this->translator->trans("La colonne 'dest_idmlc'ou 'dest' est obligatoire !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            if (!array_key_exists('exp_type', $row)) {
                $this->addError($row, $line, 'exp_type', $this->translator->trans("La colonne 'exp_type' est obligatoire !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            if (!array_key_exists('dest_type', $row)) {
                $this->addError($row, $line, 'dest_type', $this->translator->trans("La colonne 'dest_type' est obligatoire !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            if (!array_key_exists('montant', $row)) {
                $this->addError($row, $line, 'montant', $this->translator->trans("La colonne 'montant' est obligatoire !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            if (!array_key_exists('devise', $row)) {
                $this->addError($row, $line, 'devise', $this->translator->trans("La colonne 'devise' est obligatoire !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            if (!array_key_exists('date', $row)) {
                $this->addError($row, $line, 'date', $this->translator->trans("La colonne 'date' est obligatoire !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            if (!array_key_exists('type', $row)) {
                $this->addError($row, $line, 'type', $this->translator->trans("La colonne 'type' est obligatoire !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            $exp_id = array_key_exists('exp_idmlc', $row) ? $row['exp_idmlc'] : '';
            $exp_name = array_key_exists('exp', $row) ? $row['exp'] : '';
            $exp_type = array_key_exists('exp_type', $row) ? $row['exp_type'] : '';
            $dest_id = array_key_exists('dest_idmlc', $row) ? $row['dest_idmlc'] : '';
            $dest_name = array_key_exists('dest', $row) ? $row['dest'] : '';
            $dest_type = array_key_exists('dest_type', $row) ? $row['dest_type'] : '';
            if (!in_array($exp_type, ImportEnum::getAvailableOperators())) {
                $this->addError($row, $line, 'exp_type', $this->translator->trans("La colonne 'exp_type' n'est pas valide !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            if (!in_array($dest_type, ImportEnum::getAvailableOperators())) {
                $this->addError($row, $line, 'dest_type', $this->translator->trans("La colonne 'dest_type' n'est pas valide !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            $exp = $this->getEntityFromData($exp_type, $exp_id, $exp_name);
1003
            if (null === $exp) {
1004 1005 1006 1007 1008 1009
                $this->addError($row, $line, 'exp', $this->translator->trans("L'expediteur est introuvable !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            $dest = $this->getEntityFromData($dest_type, $dest_id, $dest_name);
1010 1011
            if (null === $dest) {
                $this->addError($row, $line, 'dest', $this->translator->trans('Le destinataire est introuvable !'));
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
                ++$this->nberrors;
                ++$line;
                continue;
            }
            $montant = $row['montant'];
            if (!preg_match('/^[0-9]*([\.,][0-9]*)?$/', $montant)) {
                $this->addError($row, $line, 'montant', $this->translator->trans("La colonne 'montant' est invalide !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            // $currency = $row['devise'];
            // if (!in_array($currency, CurrencyEnum::getAvailableTypes())) {
            //     $this->addError($row, $line, 'currency', $this->translator->trans("La colonne 'currency' est invalide !"));
            //     ++$this->nberrors;
            //     ++$line;
            //     continue;
            // }
            $dateCsv = $row['date'];
            $date = DateTime::createFromFormat('Y-m-d H:i', $dateCsv);
            if (false === $date) {
                $this->addError($row, $line, 'date', $this->translator->trans("La date est invalide (format attendu : 'YYYY-mm-dd HH:ii', exemple 2020-11-29 11:53) !"));
                ++$this->nberrors;
                ++$line;
                continue;
            }
            $typeFlux = $row['type'];
            if (!in_array($typeFlux, FluxEnum::getAvailableTypes())) {
1040
                $this->addError($row, $line, 'type', $this->translator->trans('Le type de flux est invalide (types attendus : ' . implode(', ', FluxEnum::getAvailableTypes()) . ') !'));
1041 1042 1043 1044 1045 1046
                ++$this->nberrors;
                ++$line;
                continue;
            }
            $moyen = $row['moyen'];
            if (!in_array($moyen, MoyenEnum::getAvailableTypes())) {
1047
                $this->addError($row, $line, 'moyen', $this->translator->trans('Le moyen est invalide (moyens attendus : ' . implode(', ', MoyenEnum::getAvailableTypes()) . ') !'));
1048 1049 1050 1051
                ++$this->nberrors;
                ++$line;
                continue;
            }
Julien Jorry committed
1052

1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
            $reference = array_key_exists('reference', $row) ? $row['reference'] : '';
            $tauxreconversion = array_key_exists('tauxreconversion', $row) ? $row['tauxreconversion'] : '';
            $data = array_key_exists('data', $row) ? $row['data'] : '';

            //@TODO : enregistrer les données passées dans flux et operation avec un flag historical
            $fluxClass = FluxEnum::getClassName($typeFlux);
            $flux = new $fluxClass();
            $flux->setHistorical(true);
            $flux->setOperateur($this->getUser());
            $flux->setRole($this->getUser()->getGroups()[0]->__toString());
            $flux->setExpediteur($exp);
            $flux->setDestinataire($dest);
            $flux->setMoyen($moyen);
            $flux->setMontant($montant);
            $flux->setReference($reference);
            $flux->setTauxreconversion($tauxreconversion);
            if (is_string($data)) {
                $flux->setData([$data]);
            } elseif (is_array($data)) {
                $flux->setData($data);
            }

            if (!$this->test) {
                try {
                    $this->em->persist($flux);
                    $this->em->flush();
                    $flux->setCreatedAt($date);
                    $this->em->persist($flux);
                    $this->em->flush();

                    $operations = $flux->getAllOperations($this->em);
                    foreach ($operations as $operation) {
                        $operation->setHistorical(true);
                        $this->em->persist($operation);
                        $this->em->flush();
                        $operation->setCreatedAt($date);
                        $this->em->persist($operation);
                        $this->em->flush();
Julien Jorry committed
1091
                    }
1092
                } catch (Exception $e) {
1093
                    $this->addError($row, $line, 'all', $this->translator->trans("L'enregistrement du flux a posé problème ! " . $e->getMessage()));
1094 1095 1096
                    ++$this->nberrors;
                    ++$line;
                    continue;
Julien Jorry committed
1097
                }
1098 1099
            } else {
                $this->addSuccess($row, $line, 'all', $this->translator->trans('Flux ajouté : ') . $flux->__toString());
Julien Jorry committed
1100 1101
            }
        }
1102
    }
Julien Jorry committed
1103

1104 1105 1106 1107
    private function getEntityFromData(string $type, string $idmlc, string $idNameOrEmail)
    {
        $entity = null;
        $idNameOrEmailSlug = $this->slugify($idNameOrEmail);
1108
        if ('prestataire' == $type) {
1109 1110 1111 1112 1113
            if (!empty($idNameOrEmail)) {
                $entity = $this->em->getRepository(Prestataire::class)->findOneBy(['slug' => $idNameOrEmailSlug]);
            } elseif (!empty($idmlc)) {
                $entity = $this->em->getRepository(Prestataire::class)->findOneBy(['idmlc' => $idmlc]);
            }
1114
        } elseif ('adherent' == $type) {
1115 1116 1117 1118 1119 1120 1121 1122
            if (!empty($idNameOrEmail)) {
                $userFound = $this->em->getRepository(User::class)->findOneBy(['username' => $idNameOrEmail]);
                if (!empty($userFound)) {
                    $entity = $userFound->getAdherent();
                }
            } elseif (!empty($idmlc)) {
                $entity = $this->em->getRepository(Adherent::class)->findOneBy(['idmlc' => $idmlc]);
            }
1123
        } elseif ('siege' == $type && 'siege' == $exp_id) {
1124
            $siege = $this->em->getRepository(Siege::class)->getTheOne();
1125
        } elseif ('groupe' == $type) {
1126 1127 1128 1129 1130
            if (!empty($idNameOrEmail)) {
                $entity = $this->em->getRepository(Groupe::class)->findOneBy(['slug' => $idNameOrEmailSlug]);
            } elseif (!empty($idmlc)) {
                $entity = $this->em->getRepository(Groupe::class)->findOneBy(['idmlc' => $idmlc]);
            }
1131
        } elseif ('comptoir' == $type) {
1132 1133 1134 1135 1136 1137 1138 1139
            if (!empty($idNameOrEmail)) {
                $entity = $this->em->getRepository(Comptoir::class)->findOneBy(['slug' => $idNameOrEmailSlug]);
            } elseif (!empty($idmlc)) {
                $entity = $this->em->getRepository(Comptoir::class)->findOneBy(['idmlc' => $idmlc]);
            }
        }

        return $entity;
Julien Jorry committed
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
    }

    /**
     * Import manager of comptoir / groupe / presta.
     *
     * @param array     $row    Value of line imported
     * @param Usergroup $groupe Groupe add to manager imported
     *
     * @return User Manager created
     */
Julien Jorry committed
1150
    private function importGestionnaires($row, $line, Usergroup $groupe)
Julien Jorry committed
1151 1152 1153
    {
        $cptGestionnaire = 1;
        $users = new ArrayCollection();
1154
        $usergroupe = $this->em->getRepository(Usergroup::class)->findOneByName('Adherent');
Julien Jorry committed
1155 1156 1157 1158 1159 1160
        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] : '';

            $userFound = $this->em->getRepository(User::class)->findOneBy(['email' => $email]);
            if (!empty($userFound)) {
                $userFound->addPossiblegroup($groupe);
1161
                if (!$this->test) {
Julien Jorry committed
1162
                    $users[] = $userFound;
1163
                    $this->em->persist($userFound);
Julien Jorry committed
1164 1165
                } else {
                    $this->em->detach($userFound);
1166 1167
                }
                $this->addSuccess($row, $line, 'gestionnaire', $this->translator->trans('Rôle ' . $groupe . ' ajouté à l\'utilisateur ') . $userFound);
Julien Jorry committed
1168 1169 1170 1171 1172 1173 1174
            } else {
                $nom = array_key_exists('gestionnaire_nom' . $cptGestionnaire, $row) ? $row['gestionnaire_nom' . $cptGestionnaire] : '';
                $prenom = array_key_exists('gestionnaire_prenom' . $cptGestionnaire, $row) ? $row['gestionnaire_prenom' . $cptGestionnaire] : '';
                $phone = array_key_exists('gestionnaire_phone' . $cptGestionnaire, $row) ? $row['gestionnaire_phone' . $cptGestionnaire] : '';
                $mobile = array_key_exists('gestionnaire_mobile' . $cptGestionnaire, $row) ? $row['gestionnaire_mobile' . $cptGestionnaire] : '';

                $adherent = new Adherent();
Julien Jorry committed
1175
                $user = new User(); // $this->userManager->createUser();
Julien Jorry committed
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
                $user->setConfirmationToken($this->tokenGenerator->generateToken());
                $user->setEnabled(true);
                $user->setPassword(md5(random_bytes(10)));
                $user->addPossiblegroup($usergroupe);
                $user->addPossiblegroup($groupe);
                $user->setGroups([$groupe]);
                $user->setFirstname($prenom);
                $user->setLastname($nom);
                $user->setPhone($phone);
                $user->setMobile($mobile);
                $user->setEmail($email);
                $user->setUsername($email);
                $user->setAdherent($adherent);
                $adherent->setUser($user);
                $users[] = $user;
1191 1192 1193
                $this->addSuccess($row, $line, 'gestionnaire', $this->translator->trans('Nouvel adhérent/gestionnaire' . $adherent . ' bien ajouté ligne : ') . $line);
                if (!$this->test) {
                    $this->em->persist($user);
1194
                    $this->userManager->updateUser($user);
1195 1196
                    $this->em->persist($adherent);
                    $this->em->flush();
1197 1198
                    // $this->em->clear();
                    gc_collect_cycles();
1199
                }
Julien Jorry committed
1200
            }
Julien Jorry committed
1201
            if (!$this->test && $this->sendemail) {
Julien Jorry committed
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
                $this->eventDispatcher->dispatch(MLCEvents::REGISTRATION_ADHERENT, new UserEvent($user, $this->getRequest()));
            }
            ++$cptGestionnaire;
        }

        return $users;
    }

    private function addSuccess($row, $line, $key, $message = '')
    {
        $csvline = implode(';', array_values($row));
        $this->success[$line][$key] = $message;
    }

    private function addError($row, $line, $key, $err = '')
    {
        $this->lineErrors[$line] = implode(';', array_values($row));
        $this->errors[$line][$key] = (array_key_exists($key, $row) ? (!empty($row[$key]) ? '"' . $row[$key] . '"' : '') : '') . ' [' . $err . ']';
    }

    private function addWarning($row, $line, $key, $err = '')
    {
        $csvline = implode(';', array_values($row));
        if ('empty' == $err) {
            $errString = $this->translator->trans('Valeur vide !');
            $this->warnings[$line][$key] = '[' . $errString . ' ]';
        } elseif ('invalid' == $err) {
            $errString = $this->translator->trans('Valeur invalide !');
            $this->warnings[$line][$key] = '"' . (array_key_exists($key, $row) ? $row[$key] : '') . '" [' . $errString . ']';
        } elseif ('' != $err) {
            $this->warnings[$line][$key] = '"' . (array_key_exists($key, $row) ? $row[$key] : '') . '" [' . $err . ']';
        }
    }

    private function tofloat($num)
    {
        $dotPos = strrpos($num, '.');
        $commaPos = strrpos($num, ',');
        $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
            ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);

        if (!$sep) {
            return floatval(preg_replace('/[^0-9]/', '', $num));
        }

        return floatval(
            preg_replace('/[^0-9]/', '', substr($num, 0, $sep)) . '.' .
            preg_replace('/[^0-9]/', '', substr($num, $sep + 1, strlen($num)))
        );
    }
1252 1253 1254 1255 1256 1257 1258

    private function slugify($string)
    {
        $string = Transliterator::transliterate($string, '-');

        return Transliterator::urlize($string, '-');
    }
Julien Jorry committed
1259
}