ImportController.php 60.4 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?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;
19
use App\Entity\TypePrestataire;
Julien Jorry committed
20 21
use App\Entity\User;
use App\Entity\Usergroup;
22 23
use App\Enum\CurrencyEnum;
use App\Enum\FluxEnum;
Julien Jorry committed
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 56
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;
57
    protected $test;
Julien Jorry committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

    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;
75
        $this->test = false;
Julien Jorry committed
76 77 78 79 80 81 82 83 84 85 86
    }

    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()) {
87 88
            $this->em->getConnection()->getConfiguration()->setSQLLogger(null);
            gc_collect_cycles();
Julien Jorry committed
89 90 91 92
            $import = $form->getData();
            $media = $import->getMedia();
            $type = $import->getType();
            $this->sendemail = (bool) $import->getSendemail();
Julien Jorry committed
93
            $this->test = (bool) $import->getTest();
Julien Jorry committed
94

95 96 97 98 99 100
            // $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
101

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

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

107 108 109 110 111 112 113
                $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
114

115 116 117 118 119 120 121 122 123 124 125 126 127 128
                // $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 !'
                        );
                    }
129 130
                } else {
                    $this->addFlash(
131 132
                        'error',
                        "Il y a eu des erreurs lors de l'import !"
133 134
                    );
                }
135 136
            } catch (Exception $e) {
                // $this->em->getConnection()->rollBack(); // Rollback all previous commit !
Julien Jorry committed
137 138
                $this->addFlash(
                    'error',
139
                    "Il y a eu une erreur lors de l'import : " . $e->getMessage()
Julien Jorry committed
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 174
                );
            }

            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');

175
        $result = null;
Julien Jorry committed
176 177 178 179 180 181 182 183
        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);
184 185
        } elseif (ImportEnum::IMPORT_OPERATION == $type) {
            $result = $this->importOperations($csvRows);
Julien Jorry committed
186 187 188 189 190 191 192
        } else {
            // Ne devrait jamais arriver, mais sait-on jamais !
            $this->errors['error'] = $this->translator->trans('Choisir un type de données à importer !');
        }

        return $result;
    }
193

194 195 196 197 198 199 200 201 202 203
    /**
     * 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
204
    {
205
        $csv = new \SplFileObject($filePath . '/' . $fileName);
Julien Jorry committed
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 231
        $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
232 233 234 235 236
    }

    private function importComptoir($csvRows)
    {
        // Iterate over the reader and write each row to the database
237
        //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
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 264
        $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;
            }
265
            $idmlc = array_key_exists('idmlc', $row) ? $row['idmlc'] : '';
Julien Jorry committed
266 267 268 269 270 271 272 273 274 275 276 277
            $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);
278
                $groupeFound->setSiege($this->em->getRepository(Siege::class)->getTheOne());
279 280 281
                if (!$this->test) {
                    $this->em->persist($groupeFound);
                }
Julien Jorry committed
282 283 284 285 286
                $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();
287
                $comptoir->setIdmlc($idmlc);
Julien Jorry committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
                $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);
303
                    $geolocFound->setCpostal($cpostal);
Julien Jorry committed
304 305
                    $geolocFound->setVille($ville);
                    if (!empty($latitude) && !empty($longitude)) {
Julien Jorry committed
306 307
                        $geolocFound->setLat(floatval(str_replace(',', '.', $latitude)));
                        $geolocFound->setLon(floatval(str_replace(',', '.', $longitude)));
Julien Jorry committed
308 309 310 311 312 313 314 315 316
                    }
                    $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
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
                    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;
333
                    }
Julien Jorry committed
334 335 336 337 338
                    ++$cptContact;
                }

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

                $this->addSuccess($row, $line, 'comptoir', $this->translator->trans('Comptoir ajouté : ') . $nom);
                ++$this->nbsuccess;
344 345 346
                if (!$this->test) {
                    $this->em->persist($comptoir);
                    $this->em->flush();
347
                    // $this->em->clear();
348
                }
Julien Jorry committed
349 350 351 352 353 354 355 356 357 358 359 360 361 362
            } 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
363
        // idmlc;nom;description;compte;gestionnaire_email1;gestionnaire_nom1;gestionnaire_prenom1;gestionnaire_phone1;gestionnaire_mobile1
Julien Jorry committed
364 365 366 367 368 369 370 371 372 373 374 375 376
        $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;
            }
377
            $idmlc = array_key_exists('idmlc', $row) ? $row['idmlc'] : '';
Julien Jorry committed
378 379
            $description = array_key_exists('description', $row) ? $row['description'] : '';
            $compte = array_key_exists('compte', $row) ? $row['compte'] : '';
380 381 382 383 384 385 386
            $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
387 388
            if (empty($groupe)) {
                $groupe = new Groupe();
389
                $groupe->setIdmlc($idmlc);
Julien Jorry committed
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
                $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
408
                $gestionnaires = $this->importGestionnaires($row, $line, $groupeGestionnaire);
Julien Jorry committed
409 410 411 412
                $groupe->setGestionnaires($gestionnaires);

                $this->addSuccess($row, $line, 'groupe', $this->translator->trans('Groupe ajouté : ') . $name);
                ++$this->nbsuccess;
413 414 415
                if (!$this->test) {
                    $this->em->persist($groupe);
                    $this->em->flush();
416
                    // $this->em->clear();
417
                }
Julien Jorry committed
418 419 420 421 422 423 424 425 426 427
            } 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);
    }

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

Julien Jorry committed
433 434 435
    private function importPrestataire($csvRows)
    {
        // Iterate over the reader and write each row to the database
436
        // 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
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 488
        $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;
            }
489
            $idmlc = array_key_exists('idmlc', $row) ? $row['idmlc'] : '';
Julien Jorry committed
490 491 492 493 494 495 496 497 498 499 500 501 502
            $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'] : '';

503 504 505 506 507 508 509
            $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
510 511
            if (empty($prestataire)) {
                $prestataire = new Prestataire();
512
                $prestataire->setTypeprestataire($this->em->getRepository(TypePrestataire::class)->findOneBy(['slug' => 'prestataire']));
513
                $prestataire->setIdmlc($idmlc);
Julien Jorry committed
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 564 565

                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
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
                    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;
582
                    }
Julien Jorry committed
583 584 585 586
                    ++$cptContact;
                }
                // Importer les gestionnaires du prestataire s'ils existent
                $groupeGestionnaire = $this->em->getRepository(Usergroup::class)->findOneByName('Prestataire');
Julien Jorry committed
587
                $gestionnaires = $this->importGestionnaires($row, $line, $groupeGestionnaire);
Julien Jorry committed
588 589 590
                if (!$this->test) {
                    $prestataire->setUsers($gestionnaires);
                }
Julien Jorry committed
591 592 593 594 595 596

                if (!empty($groupe)) {
                    $groupeFound = $this->em->getRepository(Groupe::class)->findOneBy(['slug' => $this->slugify($groupe)]);
                    if (empty($groupeFound)) {
                        $groupeFound = new Groupe();
                        $groupeFound->setName($groupe);
597
                        $groupeFound->setSiege($this->em->getRepository(Siege::class)->getTheOne());
598 599 600
                        if (!$this->test) {
                            $this->em->persist($groupeFound);
                        }
Julien Jorry committed
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 629 630
                        $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'));
                            }
631 632
                            if (!$this->test) {
                                $this->em->persist($cotisation);
Julien Jorry committed
633
                            }
634
                            $this->addSuccess($row, $line, 'cotisations', $this->translator->trans('Cotisation(s) ajoutée(s) ligne : ') . $line);
Julien Jorry committed
635 636 637 638 639 640 641 642 643 644 645 646
                        }
                    }
                } 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);
647 648 649
                            if (!$this->test) {
                                $this->em->persist($rubriqueFound);
                            }
Julien Jorry committed
650 651 652 653 654 655 656 657 658 659 660 661 662 663
                            $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);
664 665 666
                            if (!$this->test) {
                                $this->em->persist($tagFound);
                            }
Julien Jorry committed
667 668 669 670 671 672 673 674
                            $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)) {
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
                    // $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
694 695 696 697 698 699
                    $geolocP = new GeolocPrestataire();
                    $geolocP->setName('Adresse');
                    $geolocP->setPrestataire($prestataire);
                    $geolocFound = new Geoloc();
                    $geolocFound->setEnabled(true);
                    $geolocFound->setAdresse($adresse);
700
                    $geolocFound->setCpostal($cpostal);
Julien Jorry committed
701 702
                    $geolocFound->setVille($ville);
                    $geolocP->setGeoloc($geolocFound);
703 704
                    $prestataire->addGeoloc($geolocP);
                    // }
705 706
                    if (!$this->test) {
                        $this->em->persist($geolocP);
707
                        $this->em->flush();
708
                    }
Julien Jorry committed
709 710
                }
            } else {
711
                $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
712 713 714 715 716 717
                ++$this->nberrors;
                $hasError = true;
            }
            if (!$hasError) {
                $this->addSuccess($row, $line, 'user', $this->translator->trans('Prestataire ajouté : ') . $prestataire->__toString());
                ++$this->nbsuccess;
718 719 720 721 722
                if (!$this->test) {
                    $this->em->persist($prestataire);
                    $this->em->flush();
                    $this->em->clear();
                }
Julien Jorry committed
723 724 725 726 727 728 729 730 731 732 733
            }

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

    private function importAdherent($csvRows)
    {
        // Iterate over the reader and write each row to the database
734
        // idmlc;groupe;email;prenom;nom;phone;mobile;adresse;cpostal;ville;cotisations
Julien Jorry committed
735
        $line = 1;
736
        $now = new DateTime();
Julien Jorry committed
737 738 739 740 741 742
        foreach ($csvRows as $row) {
            $hasError = false;
            if (1 == $line) {
                ++$line;
                continue;
            }
743
            // gc_collect_cycles();
744
            $idmlc = array_key_exists('idmlc', $row) ? $row['idmlc'] : '';
Julien Jorry committed
745 746 747 748 749 750 751 752 753 754 755
            $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
756
            if (empty($email)) {
Julien Jorry committed
757 758 759 760 761 762
                $this->addError($row, $line, 'email', $this->translator->trans("La colonne 'email' est obligatoire !"));
                ++$line;
                ++$this->nberrors;
                continue;
            }

763 764 765
            $adherent = null;
            if (!empty($idmlc)) {
                $adherent = $this->em->getRepository(Adherent::class)->findOneBy(['idmlc' => $idmlc]);
Julien Jorry committed
766
            }
767
            if (empty($adherent)) {
768
                $userFound = $this->em->getRepository(User::class)->findOneBy(['email' => $email]);
Julien Jorry committed
769 770 771
                if (!empty($userFound)) {
                    $adherent = $userFound->getAdherent();
                }
Julien Jorry committed
772
            }
773 774 775
            if (empty($adherent)) {
                $adherent = new Adherent();
                $user = $this->userManager->createUser();
Julien Jorry committed
776 777
                $user->setUsername($email);
                $user->setEmail($email);
778 779 780 781 782 783 784 785
                $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);
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 818 819
            } 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();
820
                    }
821
                    $this->addSuccess($row, $line, 'groupe', $this->translator->trans('Groupe ajouté : ') . $groupe);
822
                }
823
                if ($adherent->getGroupe() != $groupeFound) {
824 825
                    $adherent->setGroupe($groupeFound);
                }
826 827 828
            } else {
                $this->addWarning($row, $line, 'groupe', 'empty');
            }
Julien Jorry committed
829 830 831
            if (!$this->test) {
                $this->em->persist($adherent);
            }
832 833 834 835 836 837 838 839 840 841

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

Julien Jorry committed
909 910 911 912
            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
913 914 915 916
                if (!$this->test) {
                    if ($this->sendemail) {
                        $this->eventDispatcher->dispatch(MLCEvents::REGISTRATION_ADHERENT, new UserEvent($user, $this->getRequest()));
                    }
Julien Jorry committed
917 918
                }
            }
919 920 921
            $this->em->flush();
            $this->em->clear();
            gc_collect_cycles();
Julien Jorry committed
922 923 924 925 926 927
            ++$line;
        }
        ksort($this->errors);
        ksort($this->warnings);
    }

928
    private function importOperations($csvRows)
Julien Jorry committed
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 1003 1004
        // 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);
1005
            if (null === $exp) {
1006 1007 1008 1009 1010 1011
                $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);
1012 1013
            if (null === $dest) {
                $this->addError($row, $line, 'dest', $this->translator->trans('Le destinataire est introuvable !'));
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 1040 1041
                ++$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())) {
1042
                $this->addError($row, $line, 'type', $this->translator->trans('Le type de flux est invalide (types attendus : ' . implode(', ', FluxEnum::getAvailableTypes()) . ') !'));
1043 1044 1045 1046 1047 1048
                ++$this->nberrors;
                ++$line;
                continue;
            }
            $moyen = $row['moyen'];
            if (!in_array($moyen, MoyenEnum::getAvailableTypes())) {
1049
                $this->addError($row, $line, 'moyen', $this->translator->trans('Le moyen est invalide (moyens attendus : ' . implode(', ', MoyenEnum::getAvailableTypes()) . ') !'));
1050 1051 1052 1053
                ++$this->nberrors;
                ++$line;
                continue;
            }
Julien Jorry committed
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 1091 1092
            $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
1093
                    }
1094
                } catch (Exception $e) {
1095
                    $this->addError($row, $line, 'all', $this->translator->trans("L'enregistrement du flux a posé problème ! " . $e->getMessage()));
1096 1097 1098
                    ++$this->nberrors;
                    ++$line;
                    continue;
Julien Jorry committed
1099
                }
1100 1101
            } else {
                $this->addSuccess($row, $line, 'all', $this->translator->trans('Flux ajouté : ') . $flux->__toString());
Julien Jorry committed
1102 1103
            }
        }
1104
    }
Julien Jorry committed
1105

1106 1107 1108 1109
    private function getEntityFromData(string $type, string $idmlc, string $idNameOrEmail)
    {
        $entity = null;
        $idNameOrEmailSlug = $this->slugify($idNameOrEmail);
1110
        if ('prestataire' == $type) {
1111 1112 1113 1114 1115
            if (!empty($idNameOrEmail)) {
                $entity = $this->em->getRepository(Prestataire::class)->findOneBy(['slug' => $idNameOrEmailSlug]);
            } elseif (!empty($idmlc)) {
                $entity = $this->em->getRepository(Prestataire::class)->findOneBy(['idmlc' => $idmlc]);
            }
1116
        } elseif ('adherent' == $type) {
1117 1118 1119 1120 1121 1122 1123 1124
            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]);
            }
1125
        } elseif ('siege' == $type && 'siege' == $exp_id) {
1126
            $siege = $this->em->getRepository(Siege::class)->getTheOne();
1127
        } elseif ('groupe' == $type) {
1128 1129 1130 1131 1132
            if (!empty($idNameOrEmail)) {
                $entity = $this->em->getRepository(Groupe::class)->findOneBy(['slug' => $idNameOrEmailSlug]);
            } elseif (!empty($idmlc)) {
                $entity = $this->em->getRepository(Groupe::class)->findOneBy(['idmlc' => $idmlc]);
            }
1133
        } elseif ('comptoir' == $type) {
1134 1135 1136 1137 1138 1139 1140 1141
            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
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
    }

    /**
     * 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
1152
    private function importGestionnaires($row, $line, Usergroup $groupe)
Julien Jorry committed
1153 1154 1155
    {
        $cptGestionnaire = 1;
        $users = new ArrayCollection();
1156
        $usergroupe = $this->em->getRepository(Usergroup::class)->findOneByName('Adherent');
Julien Jorry committed
1157 1158 1159 1160 1161 1162
        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);
1163
                if (!$this->test) {
Julien Jorry committed
1164
                    $users[] = $userFound;
1165
                    $this->em->persist($userFound);
Julien Jorry committed
1166 1167
                } else {
                    $this->em->detach($userFound);
1168 1169
                }
                $this->addSuccess($row, $line, 'gestionnaire', $this->translator->trans('Rôle ' . $groupe . ' ajouté à l\'utilisateur ') . $userFound);
Julien Jorry committed
1170 1171 1172 1173 1174 1175 1176
            } 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
1177
                $user = new User(); // $this->userManager->createUser();
Julien Jorry committed
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
                $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;
1193 1194 1195
                $this->addSuccess($row, $line, 'gestionnaire', $this->translator->trans('Nouvel adhérent/gestionnaire' . $adherent . ' bien ajouté ligne : ') . $line);
                if (!$this->test) {
                    $this->em->persist($user);
1196
                    $this->userManager->updateUser($user);
1197 1198
                    $this->em->persist($adherent);
                    $this->em->flush();
1199 1200
                    // $this->em->clear();
                    gc_collect_cycles();
1201
                }
Julien Jorry committed
1202
            }
Julien Jorry committed
1203
            if (!$this->test && $this->sendemail) {
Julien Jorry committed
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 1252 1253
                $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)))
        );
    }
1254 1255 1256 1257 1258 1259 1260

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

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