ImportController.php 39.4 KB
Newer Older
Damien Moulard committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<?php
namespace App\Controller;

use App\Entity\Adherent;
use App\Entity\ContactComptoir;
use App\Entity\ContactPrestataire;
use App\Entity\Comptoir;
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;
20
use App\Entity\Flux;
21
use App\Entity\TypePrestataire;
Damien Moulard committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
use App\Enum\ImportEnum;
use App\Enum\MoyenEnum;
use App\Events\MLCEvents;
use App\Form\Type\ImportFormType;
use Gedmo\Sluggable\Util as Sluggable;
use Behat\Transliterator\Transliterator;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Util\TokenGeneratorInterface;
use FOS\UserBundle\Util\UserManipulator;
use Sonata\AdminBundle\Controller\CRUDController;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Translation\TranslatorInterface;
42
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
Damien Moulard committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

class ImportController extends CRUDController
{
    protected $siege;
    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;
60
    protected $eventDispatcher;
Damien Moulard committed
61

62 63 64 65 66 67
    public function __construct(EntityManagerInterface $em,
                                Security $security,
                                UserManagerInterface $userManager,
                                TranslatorInterface $translator,
                                TokenGeneratorInterface $tokenGenerator,
                                EventDispatcherInterface $eventDispatcher)
Damien Moulard committed
68 69 70 71 72 73 74 75 76 77 78 79
    {
        $this->header = null;
        $this->warnings = array();
        $this->errors = array();
        $this->nberrors = 0;
        $this->nbsuccess = 0;
        $this->lineErrors = array();
        $this->em = $em;
        $this->security = $security;
        $this->userManager = $userManager;
        $this->translator = $translator;
        $this->tokenGenerator = $tokenGenerator;
80
        $this->eventDispatcher = $eventDispatcher;
Damien Moulard committed
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
        $this->siege = null;
        $this->sendemail = false;
    }

    public function createAction()
    {
        $this->siege = $this->em->getRepository(Siege::class)->findOneById(1);
        $import = new Import();
        $import->setUser($this->getUser());
        $form = $this->createForm(ImportFormType::class, $import);
        $form->handleRequest($this->getRequest());

        if ($form->isSubmitted() && $form->isValid()) {
            $import = $form->getData();
            $media = $import->getMedia();
            $type = $import->getType();
            $this->sendemail = (bool)$import->getSendemail();

            // Sauvegarder l'import en base de données avant l'essai d'import
            $this->em->persist($import);
            $this->em->flush();
            $idimport = $import->getId();

104 105
            try {
                $this->importFromCSV($type, $media);
Damien Moulard committed
106

107 108
                $import = $this->em->getRepository(Import::class)->findOneById($idimport);
                $import->setEnabled(true);
Damien Moulard committed
109

110 111 112 113 114 115 116
                $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();
Damien Moulard committed
117

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
                if (empty($this->errors)) {
                    $this->addFlash(
                        'success',
                        'Import effectué avec succès !'
                    );
                } else {
                    $this->addFlash(
                        'error',
                        "Il y a eu des erreurs lors de l'import !"
                    );
                }
                return $this->redirect($this->admin->generateUrl('show', array('id' => $import->getId())));
            } catch (\Exception $e) {
                return $this->renderWithExtraParams('admin/import_error.html.twig', [
                    'action' => 'list',
                    'error' => $e->getMessage(),
                ]);
Damien Moulard committed
135 136
            }
        }
137

Damien Moulard committed
138 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 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 231 232 233 234 235 236 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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
        return $this->renderWithExtraParams('admin/import.html.twig', array(
            'action' => 'list',
            'form' => $form->createView(),
            'errors' => $this->errors,
            'warnings' => $this->warnings,
            'success' => $this->success,
            'linkcsverror' => (count($this->lineErrors) > 0)?$this->generateUrl('getcsv', array('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));
        $this->header = implode(';', array_values($csvRows[0]));

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

        if ($type == ImportEnum::IMPORT_ADHERENT) {
            $result = $this->importAdherent($csvRows);
        } elseif ($type == ImportEnum::IMPORT_PRESTATAIRE) {
            $result = $this->importPrestataire($csvRows);
        } elseif ($type == ImportEnum::IMPORT_GROUPE) {
            $result = $this->importGroupe($csvRows);
        } elseif ($type == ImportEnum::IMPORT_COMPTOIR) {
            $result = $this->importComptoir($csvRows);
        } else {
            // Ne devrait jamais arriver, mais sait-on jamais !
            $this->errors['error'] = $this->translator->trans('Choisir un type de données à importer !');
        }

        return $result;
    }

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

    private function importComptoir($csvRows)
    {
        // Iterate over the reader and write each row to the database
        //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
        $line = 1;
        foreach ($csvRows as $row) {
            if ($line == 1) {
                $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;
            }
            $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(array('slug' => $this->slugify($groupe)));
            if (empty($groupeFound)) {
                $groupeFound = new Groupe();
                $groupeFound->setName($groupe);
                $groupeFound->setSiege($this->siege);
                $this->em->persist($groupeFound);
                $this->addSuccess($row, $line, 'groupe', $this->translator->trans('Groupe ajouté : ').$groupe);
            }
            $comptoir = $this->em->getRepository(Comptoir::class)->findOneBy(array('slug' => $this->slugify($nom), 'groupe' => $groupeFound));
            if (empty($comptoir)) {
                $comptoir = new Comptoir();
                $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);
                    $geolocFound->setCpostal(intval($cpostal));
                    $geolocFound->setVille($ville);
                    if (!empty($latitude) && !empty($longitude)) {
                        $geolocFound->setLat((float)$latitude);
                        $geolocFound->setLon((float)$longitude);
                    }
                    $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] : '';
                    $contactC = new ContactComptoir();
                    $contactC->setComptoir($comptoir);
                    $contactC->setEnabled(true);
                    $contactC->setName($contact);
                    $contactC->setTel($phone);
                    $contactC->setEmail($email);
                    $this->em->persist($contactC);
                    ++$cptContact;
                }

                // Importer les gestionnaires de comptoir s'ils existent
                $groupeGestionnaire = $this->em->getRepository(Usergroup::class)->findOneByName('Comptoir');
                $gestionnaires = $this->importGestionnaires($row, $groupeGestionnaire);
                $comptoir->setGestionnaires($gestionnaires);

                $this->addSuccess($row, $line, 'comptoir', $this->translator->trans('Comptoir ajouté : ').$nom);
                $this->nbsuccess++;
                $this->em->persist($comptoir);
                $this->em->flush();
                $this->em->clear();
            } 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
        // nom;description;compte;gestionnaire_email1;gestionnaire_nom1;gestionnaire_prenom1;gestionnaire_phone1;gestionnaire_mobile1
        $line = 1;
        foreach ($csvRows as $row) {
            if ($line == 1) {
                $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;
            }
            $description = array_key_exists("description", $row) ? $row['description'] : '';
            $compte = array_key_exists("compte", $row) ? $row['compte'] : '';
            $groupe = $this->em->getRepository(Groupe::class)->findOneBy(array('slug' => $this->slugify($name)));
            if (empty($groupe)) {
                $groupe = new Groupe();
                $groupe->setSiege($this->em->getRepository(Siege::class)->findOneById(1));
                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');
                $gestionnaires = $this->importGestionnaires($row, $groupeGestionnaire);
                $groupe->setGestionnaires($gestionnaires);

                $this->addSuccess($row, $line, 'groupe', $this->translator->trans('Groupe ajouté : ').$name);
                $this->em->persist($groupe);
                $this->nbsuccess++;
                $this->em->flush();
                $this->em->clear();
            } 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);
    }

    private function importPrestataire($csvRows)
    {
354 355
        $operateur = $this->getUser();
        $operateur_id = $operateur->getId();
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
        $line = 0;

        /**
         * Iterate over the reader and write each row to the database.
         * Each row has at least 6 required columns.
         *
         * Row format: groupe;adresse;cpostal;ville;raison;ecompte;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
         */
        $requiredColumns = [
            'groupe', 'raison', 'siret', 'adresse', 'cpostal', 'ville',
        ];

        $warningColumns = [
            'metier', 'statut', 'responsable', 'iban', 'web', 'horaires', 'description', 'ecompte',
        ];

        $columns = array_fill_keys(
            array_merge($requiredColumns, $warningColumns, ['rubriques', 'tags', 'tauxreconversion', 'cotisations']),
            null
        );

Damien Moulard committed
380 381
        foreach ($csvRows as $row) {
            $hasError = false;
382 383 384 385
            $line++;

            // The header is ignored
            if ($line === 1) {
Damien Moulard committed
386 387
                continue;
            }
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

            // Add the missing columns to the current row (with a null value).
            $row += $columns;

            /**
             * Check the required columns.
             * If one is not present or empty => add an error and go to the next line.
             */
            foreach ($requiredColumns as $column) {
                if (! $row[$column]) {
                    $this->addError($row, $line, $column,
                        $this->translator->trans('prestataire.column_required', [$column], 'import')
                    );
                    $hasError = true;
                }
Damien Moulard committed
403
            }
404 405

            if ($hasError) {
Damien Moulard committed
406 407 408 409
                $this->nberrors++;
                continue;
            }

410 411 412 413 414 415 416 417 418
            /**
             * If it doesn't exist yet, create and fill a Prestataire.
             * Otherwise => error!
             */
            $prestataire = $this->em->getRepository(Prestataire::class)->findOneBy([
                'slug' => $this->slugify($row['raison'])
            ]);

            if (!$prestataire) {
Damien Moulard committed
419 420
                $prestataire = new Prestataire();

421 422 423 424 425 426 427 428 429 430 431
                // Actually, each new Prestataire will have the 'prestataire' as TypePrestataire
                // @TODO: add a column 'type' in the CSV file (to choose a TypePrestataire)?
                $prestataire->setTypePrestataire($this->em->getRepository(TypePrestataire::class)->findOneBy([
                    'slug' => 'prestataire'
                ]));

                foreach ($requiredColumns as $column) {
                    // Special processings for these fields => so we skip them
                    if (in_array($column, ['groupe', 'adresse', 'cpostal', 'ville'])) continue;

                    $prestataire->{'set'.ucfirst($column)}($row[$column]);
Damien Moulard committed
432
                }
433 434 435 436

                // Special processing for the 'ecompte' field
                if ($e =& $row['ecompte']) {
                    $e = $this->tofloat($e);
Damien Moulard committed
437
                }
438 439 440 441 442 443 444

                foreach ($warningColumns as $column) {
                    if ($row[$column]) {
                        $prestataire->{'set'.ucfirst($column)}($row[$column]);
                    } else {
                        $this->addWarning($row, $line, $column, 'empty');
                    }
Damien Moulard committed
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

                /**
                 * If one or many Contacts are present, we create them for the Prestataire.
                 * If a phone or an email is defined, the associated 'contact' field must be defined too!
                 */
                for ($i = 1; $i < 10; $i++) {
                    $name  = $row["contact$i"] ?? null;
                    $phone = $row["phone$i"]   ?? null;
                    $email = $row["email$i"]   ?? null;

                    if ($name) {
                        $contact = new ContactPrestataire();
                        $contact->setPrestataire($prestataire);
                        $contact->setEnabled(true);
                        $contact->setName($name);
                        $contact->setTel($row["phone$i"] ?? '');
                        $contact->setEmail($row["email$i"] ?? '');

                        $this->em->persist($contact);
                    } elseif ($phone || $email) {
                        $this->addError($row, $line, "contact$i",
                            $this->translator->trans('prestataire.column_required', ["contact$i"], 'import')
                        );
                        $hasError = true;
                    }
Damien Moulard committed
471 472
                }

473 474 475
                if ($hasError) {
                    $this->nberrors++;
                    continue;
Damien Moulard committed
476
                }
477

Damien Moulard committed
478 479 480 481 482
                // Importer les gestionnaires du prestataire s'ils existent
                $groupeGestionnaire = $this->em->getRepository(Usergroup::class)->findOneByName('Prestataire');
                $gestionnaires = $this->importGestionnaires($row, $groupeGestionnaire);
                $prestataire->setUsers($gestionnaires);

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
                /**
                 * If no Groupe object exists for the 'groupe' field, we create one.
                 * Note: at this point, the 'groupe' field is necessarily not empty (because it was required above).
                 */
                $groupe = $row['groupe'];
                $groupeObj = $this->em->getRepository(Groupe::class)->findOneBy(['name' => $groupe]);

                if (! $groupeObj) {
                    $groupeObj = new Groupe();
                    $groupeObj->setName($groupe);
                    $groupeObj->setSiege($this->siege);
                    $this->em->persist($groupeObj);
                    $this->addSuccess($row, $line, 'groupe',
                        $this->translator->trans('prestataire.groupe_notfound_created', [$groupe], 'import')
                    );
Damien Moulard committed
498
                }
499 500 501
                $prestataire->setGroupe($groupeObj);

                if ($cotisations = $row['cotisations']) {
Damien Moulard committed
502
                    $cotisationArray = explode(',', $cotisations);
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
                    foreach ($cotisationArray as $cotisationDetails) {
                        $cotisation = new CotisationPrestataire();
                        $now = new DateTime();
                        $cotisation->setReference('Import du '.$now->format('d/m/Y H:i'));
                        $cotisation->setOperateur($operateur);
                        $cotisation->setRole('ROLE_SUPER_ADMIN');
                        $cotisation->setExpediteur($prestataire);
                        $cotisation->setMoyen(MoyenEnum::MOYEN_AUTRE);
                        $cotisationDetailsArray = explode(':', $cotisationDetails);
                        if (count($cotisationDetailsArray) == 1) {
                            $cotisation->setMontant(intval($cotisationDetails[0]));
                            $cotisation->getCotisationInfos()->setDebut($now);
                            $cotisation->getCotisationInfos()->setFin(new DateTime('+ 1 year'));
                        } else {
                            $cotisation->setMontant(intval($cotisationDetailsArray[0]));
                            $cotisation->getCotisationInfos()->setAnnee(intval($cotisationDetailsArray[1]));
                            $cotisation->getCotisationInfos()->setDebut(DateTime::createFromFormat('Ymd', intval($cotisationDetailsArray[1]).'0101'));
                            $cotisation->getCotisationInfos()->setFin(DateTime::createFromFormat('Ymd', intval($cotisationDetailsArray[1]).'1231'));
Damien Moulard committed
521
                        }
522 523
                        $this->em->persist($cotisation);
                        $this->addSuccess($row, $line, 'cotisations', $this->translator->trans('Cotisation ajouté : ').$groupe);
Damien Moulard committed
524 525 526 527
                    }
                } else {
                    $this->addWarning($row, $line, 'cotisations', 'empty');
                }
528 529

                if ($rubriques = $row['rubriques']) {
Damien Moulard committed
530 531 532 533 534 535 536 537 538
                    $rubriquesArray = explode(',', $rubriques);
                    foreach ($rubriquesArray as $rubrique) {
                        $rubriquesFound = $this->em->getRepository(Rubrique::class)->findOneBy(array('slug' => $this->slugify($rubrique)));
                        if (empty($rubriquesFound)) {
                            $rubriquesFound = new Rubrique();
                            $rubriquesFound->setName($rubrique);
                            $this->em->persist($rubriquesFound);
                            $this->addSuccess($row, $line, 'rubrique', $this->translator->trans('Rubrique ajoutée : ').$rubrique);
                        }
539
                        $prestataire->addRubrique($rubriquesFound);
Damien Moulard committed
540 541 542 543
                    }
                } else {
                    $this->addWarning($row, $line, 'rubriques', 'empty');
                }
544 545

                if ($tags = $row['tags']) {
Damien Moulard committed
546 547 548 549 550 551 552 553 554 555 556 557 558
                    $tagsArray = explode(',', $tags);
                    foreach ($tagsArray as $tag) {
                        $tagsFound = $this->em->getRepository(EtatPrestataire::class)->findOneBy(array('slug' => $this->slugify($tag)));
                        if (empty($tagsFound)) {
                            $tagNew = new EtatPrestataire();
                            $tagNew->setName($tag);
                            $this->em->persist($tagNew);
                            $this->addSuccess($row, $line, 'tag', $this->translator->trans('Tag ajouté : ').$tag);
                        }
                    }
                } else {
                    $this->addWarning($row, $line, 'tags', 'empty');
                }
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577

                /**
                 * Add a Geoloc for this Prestataire.
                 * At this point, 'adresse', 'cpostal' and 'ville' fields exist and are not empty.
                 */
                $geoloc = new Geoloc();
                $geoloc->setEnabled(true);
                $geoloc->setAdresse($row['adresse']);
                $geoloc->setCpostal($row['cpostal']);
                $geoloc->setVille($row['ville']);

                $geolocP = new GeolocPrestataire();
                $geolocP->setName('Adresse');
                $geolocP->setPrestataire($prestataire);
                $geolocP->setGeoloc($geoloc);
                $this->em->persist($geolocP);

                $prestataire->setGeolocs([$geolocP]);

Damien Moulard committed
578
            } else {
579 580 581
                $this->addError($row, $line, 'raison',
                    $this->translator->trans('prestataire.already_exists', [$row['raison']], 'import')
                );
Damien Moulard committed
582 583 584
                $this->nberrors++;
                $hasError = true;
            }
585

Damien Moulard committed
586 587 588 589
            if (!$hasError) {
                $this->em->persist($prestataire);
                $this->em->flush();
                $this->em->clear();
590

591
                // em is fully cleared: we need to refetch entities we get from em during process
592 593
                $operateur = $this->em->getRepository(User::class)->findOneById($operateur_id);
                $this->siege = $this->em->getRepository(Siege::class)->findOneById(1);
Damien Moulard committed
594

595 596 597 598 599
                $this->addSuccess($row, $line, 'user',
                    $this->translator->trans('prestataire.added', [(string) $prestataire], 'import')
                );
                $this->nbsuccess++;
            }
Damien Moulard committed
600
        }
601

Damien Moulard committed
602 603 604 605 606 607
        ksort($this->errors);
        ksort($this->warnings);
    }

    private function importAdherent($csvRows)
    {
608 609 610
        // Batch operations with doctrine require some workaround
        $operateur = $this->getUser();
        $operateur_id = $operateur->getId();
Damien Moulard committed
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
        // Iterate over the reader and write each row to the database
        // groupe;firstname;lastname;email;phone;mobile;adresse;cpostal;ville;ecompte
        $line = 1;
        foreach ($csvRows as $row) {
            $hasError = false;
            if ($line == 1) {
                $line++;
                continue;
            }
            $groupe = array_key_exists("groupe", $row) ? $row['groupe'] : '';
            $firstname = array_key_exists("firstname", $row) ? $row['firstname'] : '';
            $lastname = array_key_exists("lastname", $row) ? $row['lastname'] : '';
            $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'] : '';
            $ecompte = array_key_exists("ecompte", $row) ? $row['ecompte'] : '';
            $cotisations = array_key_exists("cotisations", $row) ? $row['cotisations'] : '';

            if (!(array_key_exists("email", $row))) {
                $this->addError($row, $line, 'email', $this->translator->trans("La colonne 'email' est obligatoire !"));
                $line++;
                $this->nberrors++;
                continue;
            }

            $adherent = new Adherent();
            $user = $this->userManager->createUser();
            $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);

            if (!empty($firstname)) {
                $user->setFirstname($firstname);
            } else {
                $this->addWarning($row, $line, 'firstname', 'empty');
            }
            if (!empty($lastname)) {
                $user->setLastname($lastname);
            } else {
                $this->addWarning($row, $line, 'lastname', 'empty');
            }
            if (!empty($email)) {
                $userFound = $this->em->getRepository(User::class)->findOneBy(array('email' => $email));
                if (!empty($userFound)) {
                    $hasError = true;
                    $this->addError($row, $line, 'email', $this->translator->trans("L'email est déjà utilisé !"));
                    $line++;
                    $this->nberrors++;
                    continue;
                } else {
                    $user->setEmail($email);
                    $user->setUsername($email);
                }
            } else {
                $this->addWarning($row, $line, 'email', 'empty');
            }
            if (!empty($phone)) {
                $user->setPhone($phone);
            } else {
                $this->addWarning($row, $line, 'phone', 'empty');
            }
            if (!empty($mobile)) {
                $user->setMobile($mobile);
            } else {
                $this->addWarning($row, $line, 'mobile', 'empty');
            }
            if (!empty($ecompte)) {
                $adherent->setEcompte($this->tofloat($ecompte));
            } else {
                $this->addWarning($row, $line, 'ecompte', 'empty');
            }
            if (!empty($groupe)) {
                $groupeFound = $this->em->getRepository(Groupe::class)->findOneBy(array('name' => $groupe));
                if (empty($groupeFound)) {
                    $groupeFound = new Groupe();
                    $groupeFound->setName($groupe);
                    $groupeFound->setSiege($this->siege);
                    $this->em->persist($groupeFound);
                    $this->addSuccess($row, $line, 'groupe', $this->translator->trans('Groupe ajouté : ').$groupe);
                }
                $adherent->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 CotisationAdherent();
                        $now = new DateTime();
                        $cotisation->setReference('Import du '.$now->format('d/m/Y H:i'));
710
                        $cotisation->setOperateur($operateur);
Damien Moulard committed
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
                        $cotisation->setRole('ROLE_ADHERENT');
                        $cotisation->setExpediteur($adherent);
                        $cotisation->setMoyen(MoyenEnum::MOYEN_AUTRE);
                        $cotisationDetailsArray = explode(':', $cotisationDetails);
                        if (count($cotisationDetailsArray) == 1) {
                            $cotisation->setMontant(intval($cotisationDetails));
                            $cotisation->getCotisationInfos()->setDebut($now);
                            $cotisation->getCotisationInfos()->setFin(new DateTime('+ 1 year'));
                        } else {
                            $cotisation->setMontant(intval($cotisationDetailsArray[0]));
                            $cotisation->getCotisationInfos()->setAnnee(intval($cotisationDetailsArray[1]));
                            $cotisation->getCotisationInfos()->setDebut(DateTime::createFromFormat('Ymd', intval($cotisationDetailsArray[1]).'0101'));
                            $cotisation->getCotisationInfos()->setFin(DateTime::createFromFormat('Ymd', intval($cotisationDetailsArray[1]).'1231'));
                        }
                        $this->em->persist($cotisation);
726
                        $this->addSuccess($row, $line, 'cotisations', $this->translator->trans('Cotisation ajoutée : ').$groupe);
Damien Moulard committed
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
                    }
                }
            } else {
                $this->addWarning($row, $line, 'cotisations', 'empty');
            }
            if (!empty($adresse) || !empty($cpostal) || !empty($ville)) {
                $geolocFound = new Geoloc();
                $geolocFound->setAdresse($adresse);
                $geolocFound->setCpostal(intval($cpostal));
                $geolocFound->setVille($ville);
                $adherent->setGeoloc($geolocFound);
            }
            if (!$hasError) {
                $this->addSuccess($row, $line, 'user', $this->translator->trans('Utilisateur bien ajouté : ').$user->__toString());
                $this->nbsuccess++;
                $user->setPasswordRequestedAt(new \DateTime());
                $this->userManager->updateUser($user);
                if ($this->sendemail) {
                    $this->eventDispatcher->dispatch(MLCEvents::REGISTRATION_ADHERENT, new UserEvent($user, $this->getRequest()));
                }
                $this->em->flush();
                $this->em->clear();
749 750
                // em is fully cleared: we need to refetch entities we get from em during process
                $operateur = $this->em->getRepository(User::class)->findOneBy(array('id' => $operateur_id));
Damien Moulard committed
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 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 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
            }

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

    /**
     * Open and parse .CSV file
     * @param  string  $filePath        Path of the file
     * @param  string  $fileName        Name of the file
     * @param  boolean $ignoreFirstLine If true, ignore first line
     * @return array  Array of parsed values with array's key = firstline
     */
    private function parseCSV($filePath, $fileName, $ignoreFirstLine = false)
    {
        $csv = new \SplFileObject($filePath.'/'.$fileName);

        $rows = array();
        $firstline = null;
        if (($handle = fopen($csv->getRealPath(), "r")) !== false) {
            $i = 0;
            while (($data = fgetcsv($handle, null, ";")) !== false) {
                $i++;
                if ($i == 1) {
                    $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;
    }

    /**
     * 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
     */
    private function importGestionnaires($row, Usergroup $groupe)
    {
        $cptGestionnaire = 1;
        $users = new ArrayCollection();
        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(array('email' => $email));
            if (!empty($userFound)) {
                $userFound->addPossiblegroup($groupe);
                $users[] = $userFound;
                $this->em->persist($userFound);
            } 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] : '';
                $user = $this->userManager->createUser();
                $user->setConfirmationToken($this->tokenGenerator->generateToken());
                $user->setEnabled(true);
                $user->setPassword(md5(random_bytes(10)));
                $usergroupe = $this->em->getRepository(Usergroup::class)->findOneByName('Adhérent');
                $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($user->getName());
                $users[] = $user;
                $this->em->persist($user);
            }
            if ($this->sendemail) {
                $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 ($err == 'empty') {
            $errString = $this->translator->trans('Valeur vide !');
            $this->warnings[$line][$key] ='['.$errString.' ]';
        } elseif ($err == 'invalid') {
            $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)))
        );
    }
}