src/Controller/MainController.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\DeclarationAnnuelle;
  4. use App\Entity\Ecriture;
  5. use App\Entity\Immeuble;
  6. use App\Entity\Local;
  7. use App\Entity\User;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Doctrine\ORM\Mapping\Entity;
  10. use League\Csv\Info;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Core\Security;
  17. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  18. use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
  19. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  20. use Symfony\Component\Serializer\Serializer;
  21. use League\Csv\Reader;
  22. use League\Csv\Statement;
  23. use League\Csv\Writer;
  24. use Symfony\Component\Serializer\SerializerInterface;
  25. use Symfony\Component\Validator\Constraints\Json;
  26. class MainController extends AbstractController
  27. {
  28.     #[Route('/'name'app_main')]
  29.     public function index(): Response
  30.     {
  31.         return $this->render('main/index.html.twig', [
  32.             'controller_name' => 'MainController',
  33.         ]);
  34.     }
  35.     #[Route('/api/uploads/{type}'name'uploads')]
  36.     public function uploads(Request $request$type)
  37.     {
  38.         $files $request->files->get($type);
  39.         $userId $this->getUser()->getId();
  40.         $filesOut = [];
  41.         /** @var \Symfony\Component\HttpFoundation\File\File $file */
  42.         foreach($files as $file) {
  43.             $ext $file->getClientOriginalExtension();
  44.             $name uuid_create() . '.' $ext;
  45.             $file $file->move('uploads/docs/' $userId '/' $type $name  );
  46.             $filesOut[] = 'uploads/docs/' $userId '/' $type '/' $name ;
  47.         }
  48.         return new JsonResponse($filesOut);
  49.     }
  50.     #[Route('/api/ecritures/preview'name'previewecriture')]
  51.     public function previewEcriture(Request $requestSerializerInterface $serializer)
  52.     {
  53.         $obj $serializer->deserialize($request->getContent(), Ecriture::class, 'json');
  54.         $obj->setId(999999);
  55.         $response = new Response($serializer->serialize($obj'json'));
  56.         $response->headers->set('Content-type''application/json');
  57.         return $response;
  58.     }
  59.     #[Route('/api/declaration_annuelles_getcurrent'name'annuelle_current')]
  60.     public function getCurrentDeclaration(Request $requestSerializerInterface $serializerEntityManagerInterface $manager)
  61.     {
  62.         $user $manager->find(User::class, $request->query->get('user_id'));
  63.         $declaration $manager->getRepository(DeclarationAnnuelle::class)->findOneBy(['annee' => date('Y'), 'user' => $user]);
  64.         if (!$declaration) {
  65.             $declaration = new DeclarationAnnuelle();
  66.             $declaration->setUser($user);
  67.             $manager->persist($declaration);
  68.             $manager->flush();
  69.         }
  70.         $response = new Response($serializer->serialize($declaration'json'));
  71.         $response->headers->set('Content-type''application/json');
  72.         return $response;
  73.     }
  74.     #[Route('/api/ecritures/compare'name'compareecriture')]
  75.     public function compareEcriture(Request $requestEntityManagerInterface $manager)
  76.     {
  77.         $data = ['find' => false];
  78.         $datas json_decode($request->getContent(),true);
  79.         $dateEffectif date_create_from_format('Y/m/d'$datas['dateEffectif']);
  80.         $find $manager->getRepository(Ecriture::class)->compare([
  81.             'dateEffectif' => $dateEffectif,
  82.             'user' => $datas['user'],
  83.             'montant' => $datas['montant']
  84.         ]);
  85.         $data['find'] = !!$find;
  86.         return new JsonResponse($data);
  87.     }
  88.     #[Route('/api/downloads_profil/{user}'name'downloads_profil')]
  89.     public function downloadProfil($userRequest $requestEntityManagerInterface $manager)
  90.     {
  91.         // TODO : finir
  92.         $user $manager->find(User::class, $user);
  93.         $file uniqid() . '-' $user->getId();
  94.         $fullpath'cache/'.$file.'.zip';
  95.         touch($fullpath);
  96.         $data['link'] = '/'.$fullpath;
  97.         return new JsonResponse($data);
  98.     }
  99.     private function detectCsvProvider($data) {
  100.         if (strpos($data[0][0], 'Téléchargement du ') > -1) return 'CA';
  101.     }
  102.     private function handleProviderCA($data, &$step) {
  103.         $lineToSkip 10;
  104.         $headers = [
  105.             'Date''Libellé''Débit euros''Crédit euros'
  106.         ];
  107.         $labelToKeep 1;
  108.         // On prend la deuxième ligne en libelle
  109.         $data array_slice($data10);
  110.         $data array_map(function($item) {
  111.             $date date_create_from_format('d/m/Y'$item[0]);
  112.             $item[2] = str_replace([' '' '], ''$item[2]);
  113.             $item[3] = str_replace([' '' '], ''$item[3]);
  114.             $item[2] = str_replace([','], '.'$item[2]);
  115.             $item[3] = str_replace([','], '.'$item[3]);
  116.             $montant = ($item[2]) ? floatval($item[2]) * -floatval($item[3]) ;
  117.             $libelle $item[1];
  118.             $libelle explode("\n"$libelle);
  119.             if (count($libelle) > 1) {
  120.                 $libelle $libelle[1];
  121.             } else {
  122.                 $libelle implode(' '$libelle);
  123.             }
  124.             $findFournisseurs = [];
  125.             // TODO : finir
  126.             return [
  127.                 'nom' => trim($libelle),
  128.                 'montant' => $montant,
  129.                 'description' => $item[1],
  130.                 'dateReglement'    => $date->format('Y/m/d'),
  131.                 'dateEffectif'    => $date->format('Y/m/d'),
  132.                 'hasReglement' => true,
  133.                 'rapprochement' => $findFournisseurs,
  134.                 'id' => null
  135.             ];
  136.         }, $data);
  137.         return [
  138.             'step' => $step,
  139.             'steps' => count($data),
  140.             'output' => $data
  141.         ];
  142.     }
  143.     #[Route('/api/launch_wizard'name'launch_wizard')]
  144.     public function launchWizard(Request $requestEntityManagerInterface $manager)
  145.     {
  146.         $file $request->query->get('file');
  147.         $reader Reader::createFromPath($file'r');
  148.         $resultDelimiter Info::getDelimiterStats($reader, [','';'], 1);
  149.         $delimiter array_search(max($resultDelimiter), $resultDelimiter) ;
  150.         $reader->setDelimiter($delimiter);
  151.         $results $reader->getRecords();
  152.         $results iterator_to_array($resultstrue);
  153.         $provider $this->detectCsvProvider($results);
  154.         $callable =  'handleProvider' $provider;
  155.         $step1;
  156.         if (!is_callable([$this$callable])) {
  157.             return new JsonResponse(['error' => 'Prestataire bancaire pas encore implémenté']);
  158.         }
  159.         $data = [];
  160.         $data $this->$callable($results$step);
  161.         return new JsonResponse($data);
  162.     }
  163.     #[Route('/api/ecritures/bulk_edit'name'bulk')]
  164.     public function bulkEdit(Request $requestEntityManagerInterface $manager)
  165.     {
  166.         $datas json_decode($request->getContent(),true);
  167.         foreach ($datas['ids'] as $id) {
  168.             $reference $manager->find(Ecriture::class, $id);
  169.             if ($request->query->get('type') == 'blockAt') {
  170.                 $reference->setBlockAt(new \DateTimeImmutable());
  171.                 $manager->persist($reference);
  172.             }
  173.             if ($request->query->get('type') == 'archivedAt') {
  174.                 $reference->setArchivedAt(new \DateTimeImmutable());
  175.                 $manager->persist($reference);
  176.             }
  177.             if ($request->query->get('type') == 'delete') {
  178.                 $manager->remove($reference);
  179.             }
  180.             $manager->flush();
  181.         }
  182.         return new JsonResponse(['action' => true]);
  183.     }
  184.     #[Route('/api/search'name'search')]
  185.     public function search(Request $requestEntityManagerInterface $entityManager)
  186.     {
  187.         /** @var mixed[] $data */
  188.         $data = [];
  189.         // local
  190.         // immeuble
  191.         // user ==> si comptable
  192.         // employés si comptable et ROLE ADMIN
  193.         // cabinet ==> psa besoin, un comptable n'a normalement qu'un seul cabinet
  194.         /** @var User $user */
  195.         $user $this->getUser();
  196.         //  todo: chercher pour les clientx normaux
  197.         if ($user->getType() != "compta") die();
  198.         /** @var \App\Entity\Cabinet $cabinet */
  199.         $cabinet $user->getCabinet();
  200.         $search $request->query->get('q');
  201.         /** @var \App\Repository\UserRepository $userRepository */
  202.         $userRepository $entityManager->getRepository(User::class);
  203.         if ($this->isGranted('ROLE_GESTION_COMPTABLE')) {
  204.             $data['employes'] = $userRepository->findEmployeByCabinet($search$cabinet->getId(), $this->isGranted('ROLE_GESTION_COMPTABLE'));
  205.         }
  206.         $data['clients'] = $userRepository->findClientByCabinet($search$cabinet->getId(), $this->isGranted('ROLE_GESTION_COMPTABLE'));
  207.         $data['immeubles'] = $entityManager->getRepository(Immeuble::class)->findByCabinet($search$cabinet->getId(), $this->isGranted('ROLE_GESTION_COMPTABLE'));
  208.         $data['locaux'] = $entityManager->getRepository(Local::class)->findByCabinet($search$cabinet->getId(), $this->isGranted('ROLE_GESTION_COMPTABLE'));
  209.         $dataOutput = [];
  210.         foreach ($data as $key => $d) {
  211.             foreach ($d as $arr) {
  212.                 $arr['typeElement'] = $key;
  213.                 $dataOutput[] = $arr;
  214.             }
  215.         }
  216.         /*
  217.         $dataTmp = $serializer->normalize($data, 'json',  [
  218.             AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT => 0
  219.         ]);
  220.         foreach($dataTmp as $type => $element) {
  221.             foreach ($element as $el) {
  222.                 $el['typeElement'] = $type;
  223.                 $dataOutput[] = $el;
  224.             }
  225.         }
  226.         */
  227.         return new JsonResponse($dataOutput);
  228.     }
  229.     #[Route('/api/ecritures_download/{client}'name'ecritures_download')]
  230.     public function downloadEcriture(Request $requestEntityManagerInterface $entityManager$client)
  231.     {
  232.         $reader Reader::createFromPath('plan_comptable.csv''r');
  233.         $reader->setDelimiter('    ');
  234.         $results $reader->getRecords();
  235.         $planComptable = [];
  236.         foreach ($results as $result) {
  237.             $code str_pad($result[0], 7'0');
  238.             $planComptable[$code] = $result[2] ;
  239.         }
  240.             //do something here
  241.         /** @var User $user */
  242.         $user $entityManager->getRepository(User::class)->find($client);
  243.         $locals $user->getLocals();
  244.         $ecritures $user->getExportEcritureDernierExcercice();
  245.         $file uniqid();
  246.         $csv Writer::createFromFileObject(new \SplFileObject('cache/' $file.'.csv''a+'), 'w+');
  247.         $headers = [
  248.             'N° Comptes',
  249.             'Intitulé de comptes',
  250.             'Solde compta 31-dec',
  251.             'Déd./Réint. RF',
  252.             'Augmentation',
  253.             'Diminution',
  254.             'Revenus fonctiers',
  255.         ];
  256.         foreach ($locals as $local) {
  257.             $headers[] = $local->getAdresse();
  258.         }
  259.         $csv->insertOne($headers);
  260.         foreach ($ecritures as $ecriture) {
  261.             $numerCompte $ecriture['numeroCompte'];
  262.             $intitule '';
  263.             if (isset($planComptable[$numerCompte])) {
  264.                 $intitule $planComptable[$numerCompte];
  265.             }
  266.             if (!$intitule) {
  267.                 $pad '';
  268.                 $numsec $numerCompte;
  269.                 while(!$intitule && strlen($pad) < ) {
  270.                     $pad .= '0';
  271.                     $numsec substr($numsec0strlen($numsec) -);
  272.                     if (isset($planComptable[$numsec $pad])) {
  273.                         $intitule $planComptable[$numsec $pad];
  274.                     }
  275.                 }
  276.             }
  277.             $csv->insertOne([
  278.                 $numerCompte,
  279.                 $intitule,
  280.                 ]
  281.             );
  282.         }
  283. // We insert the CSV header
  284.         $csv->insertOne(['firstname''lastname''email']);
  285. // Because you are providing the filename you don't have to
  286. // set the HTTP headers Writer::output can
  287. // directly set them for you
  288. // The file is downloadable
  289.       //  rename($file .'.csv', 'cache/' . $file.'.csv');
  290.         $data['link'] = '/cache/'.$file.'.csv';
  291.         return new JsonResponse($data);
  292.     }
  293. }
  294. // TODO : Fix Invalid credentials. translation