<?php
namespace App\Controller\Api\Immo;
use App\Service\DataSanitize;
use App\Service\Immo\CreateAgency;
use App\Service\Immo\Creator;
use App\Service\Immo\Data;
use League\Csv\InvalidArgument;
use League\Csv\Reader;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Exception;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use OpenApi\Annotations as OA;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* Class AdController
* @package App\Controller\Api\Immo
* @Route("/api/immo/ad", name="api_immo_ad_")
*/
class AdController extends AbstractController
{
/**
* Get file annonces from SELOGER
*
* @Route("/csv", name="csv", methods={"POST"})
* @OA\Response(
* response=200,
* description="Return list of JSON objects",
* )
* @OA\Tag(name="Immobilier")
*
* @param Request $request
* @param ParameterBagInterface $parameterBag
* @param DataSanitize $dataSanitize
* @param Creator $creator
* @param CreateAgency $creatorAgency
* @return Response
* @throws InvalidArgument
* @throws Exception
*/
public function adCSV(Request $request, ParameterBagInterface $parameterBag, DataSanitize $dataSanitize,
Creator $creator, CreateAgency $creatorAgency): Response
{
$type = Data::TYPE_CSV;
$dirname = $request->get('dirname');
$identifiant = $request->get('identifiant');
$getAll = $request->get('all') ?: false;
if(!$dirname || !$identifiant){
return new JsonResponse(['message' => 'Identification erronée.'], 400);
}
$file = $this->getFile($request->files->get('file'));
if(!($file instanceof UploadedFile)){
return $file;
}
// récupération des données du csv
$reader = Reader::createFromPath($file);
$reader->setDelimiter('#');
$records = $reader->getRecords();
// get agency info
$agency = $this->getAgency($parameterBag, $dirname, $identifiant, $creatorAgency);
if(!is_array($agency)){
return $agency;
}
// get list of ad
$ads = []; $ref = 0;
if(count($reader) != 0){
foreach ($records as $record) {
$record = $dataSanitize->cleaner($record);
$go = false;
if($getAll){
$go = true;
}else{
if($record[140] != "VENDU" && $record[140] != "LOUE" && $record[140] != "loué"
&& $record[140] != "SOUS OFFRE ACCEPTEE" && $record[140] != "SOUS OFFRE D ACHAT" && $record[139] != "OUI"
){
$go = true;
}
}
if($go){
if(count($record) === 295){
for($i = 1 ; $i<= 35 ; $i++){
$record[] = "";
}
}
$tmp = $creator->createAd($type, $record, $agency, $identifiant, $ref);
array_push($ads, $tmp);
}
$ref++;
}
}
return new JsonResponse($ads);
}
/**
* Get file annonces from APIMMO
*
* @Route("/apimmo", name="apimmo", methods={"POST"})
* @OA\Response(
* response=200,
* description="Return list of JSON objects",
* )
* @OA\Tag(name="Immobilier")
*
* @param Request $request
* @param ParameterBagInterface $parameterBag
* @param HttpClientInterface $client
* @param Creator $creator
* @param CreateAgency $creatorAgency
* @return Response
* @throws Exception
* @throws TransportExceptionInterface
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
*/
public function adAPIMMO(Request $request, ParameterBagInterface $parameterBag, HttpClientInterface $client,
Creator $creator, CreateAgency $creatorAgency): Response
{
$type = Data::TYPE_APIMMO;
$dirname = $request->get('dirname');
$identifiant = $request->get('identifiant');
$apiAgency = $request->get('apimmo_agency');
$apiProvider = $request->get('apimmo_provider');
$apiToken = $request->get('apimmo_token');
if(!$dirname || !$identifiant){
return new JsonResponse(['message' => 'Identification erronée.'], 400);
}
// récupération des données de l'api de apimmo
$response = $client->request("GET", "https://api.apimo.pro/agencies/" . $apiAgency . "/properties", [
'auth_basic' => [$apiProvider, $apiToken],
]);
$records = json_decode($response->getContent());
// get agency info
$agency = $this->getAgency($parameterBag, $dirname, $identifiant, $creatorAgency);
if(!is_array($agency)){
return $agency;
}
// get list of ad
$ads = []; $ref = 0;
if($records->total_items > 0){
foreach ($records->properties as $record) {
$tmp = $creator->createAd($type, $record, $agency, $identifiant, $ref);
array_push($ads, $tmp);
$ref++;
}
}
return new JsonResponse($ads);
}
private function getFile(?UploadedFile $file)
{
if(!$file){
return new JsonResponse(['message' => 'Fichier introuvable.'], 400);
}
if($file->getClientOriginalExtension() !== "csv"){
return new JsonResponse(['message' => 'Fichier invalide.'], 400);
}
return $file;
}
/**
* @throws Exception
*/
private function getAgencyData($fileAgences, $dirname, $identifiant, CreateAgency $creatorAgency): array
{
$readerXlsx = IOFactory::createReader("Xlsx");
$spreadsheet = $readerXlsx->load($fileAgences);
$agences = $spreadsheet->getActiveSheet()->toArray();
$agency = null; // on se base sur les agences du fichier excel, s'il l'agence n'existe pas, on en créé une vierge
foreach($agences as $a){
if($agency == null && $a[1] === $dirname){
$agency = $a;
}
}
return $creatorAgency->create($agency, $dirname, $identifiant);
}
/**
* @throws Exception
*/
private function getAgency(ParameterBagInterface $parameterBag, $dirname, $identifiant, CreateAgency $creatorAgency)
{
$fileAgences = $parameterBag->get('kernel.project_dir') . '/documents/init/agences.xlsx';
if(!file_exists($fileAgences)){
return new JsonResponse(['message' => 'Agences introuvable.'], 400);
}
return $this->getAgencyData($fileAgences, $dirname, $identifiant, $creatorAgency);
}
}