<?php
namespace App\Controller\Client;
use App\Entity\Adresses\Adresse;
use App\Entity\Articles\Article;
use App\Entity\FO\Cron;
use App\Entity\Articles\Compta;
use App\Entity\Clients\Categorie;
use App\Entity\Clients\Client;
use App\Entity\Clients\HistoriqueClient;
use App\Entity\Clients\Type;
use App\Entity\FO\TacheCron;
use App\Entity\Ged\Fichier;
use App\Entity\GestionComerciale\ArticleCommande;
use App\Entity\GestionComerciale\Commande;
use App\Entity\Localisation\Zone;
use App\Entity\Notes\Note;
use App\Entity\Remises\Remise;
use App\Entity\Utilisateur\Utilisateur;
use App\Entity\Vehicules\VehiculeClient;
use App\Form\Clients\Client2Type;
use App\Form\Clients\ClientType;
use App\Form\Clients\SupprimerClientType;
use App\Library\Datatable\Util\Datatable;
use App\Model\GestionCommerciale\TypeDocumentCommercial;
use App\Security\Voter\EntityVoter;
use App\Service\Clients\ClientCategorieRemiseClientService;
use App\Service\Clients\ClientCategorieService;
use App\Service\Clients\ClientService;
use App\Service\Clients\DocumentClient;
use App\Service\FO\Logo;
use App\Service\GestionComerciale\AcompteService;
use App\Service\GestionComerciale\NumerotationDocumentService;
use App\Service\Localisation\ZoneService;
use App\Service\Utilisateur\ColonneTableauService;
use Doctrine\ORM\EntityManagerInterface;
use JMS\Serializer\SerializerBuilder;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class ClientController extends AbstractController
{
/**
* @Route("/client/recherche", name="dtc_client_recherche")
*/
public function rechercheAction(Request $request, EntityManagerInterface $em, PaginatorInterface $paginator, AcompteService $serviceAcompte)
{
$user = $this->getUser();
if ($user->getType()->getId() != 1 && $user->getType()->getId() != 3) {
throw new AccessDeniedException('Accès interdit à cette page.');
}
$q = $request->query->get('q');
$parent = $request->query->get('parent');
$repo = $em->getRepository(Client::class);
$repo_adresse = $em->getRepository(Adresse::class);
$results = $repo->getRechercheClient(trim($q), $parent);
$tabClient = [];
for ($i = 0; $i < count($results); $i++) {
if (is_null($results[$i]["cmp_id"]) or $results[$i]["cmp_id"] == 0) {
$c = $repo->find($results[$i]["id"]);
$montant = $serviceAcompte->getSoldeClient($c);
} else {
$montant = 0;
}
$results[$i]["avoir"] = round($montant, 2);
}
$pagination = $paginator->paginate(
$results,
$request->query->getInt('page', 1),
10
);
$pagination_results = $pagination->getItems();
if (count($pagination_results) > 0) {
for ($i = 0; $i < count($pagination_results); $i++) {
$client_obj = $repo->find($pagination_results[$i]["id"]);
$pagination_results[$i]["text"]=$pagination_results[$i]["libelle"];
if (is_object($client_obj)) {
$adresse = $repo_adresse->findOneBy(['client' => $client_obj, 'visible' => 1, 'facturationDefaut' => 1]);
$libelle_adresse = "";
if (is_object($adresse)) {
if (is_object($adresse->getCodePostal())) {
$libelle_adresse .= " ".$adresse->getCodePostal()->getCodePostal();
}
if (is_object($adresse->getVille())) {
$libelle_adresse .= " ".$adresse->getVille()->getTitre();
}
} else {
$adresse = $repo_adresse->findOneBy(['client' => $client_obj, 'visible' => 1]);
if (is_object($adresse) && is_object($adresse->getCodePostal())) {
$libelle_adresse .= " ".$adresse->getCodePostal()->getCodePostal();
}
if (is_object($adresse) && is_object($adresse->getVille())) {
$libelle_adresse .= " ".$adresse->getVille()->getTitre();
}
}
$pagination_results[$i]["libelle"] = trim($pagination_results[$i]["libelle"]." (".$pagination_results[$i]["reference"]." ".trim($libelle_adresse).")");
}
}
}
$option_placeholde = ["libelle" => "Sélectionnez", "id" => ""];
if ($request->query->getInt('page', 1) == 1) {
array_unshift($pagination_results, $option_placeholde);
}
$pagination->setItems($pagination_results);
$serializer = SerializerBuilder::create()->build();
return JsonResponse::fromJsonString($serializer->serialize($pagination, 'json'));
}
/**
* @Route("/client/search/", name="dtc_client_search")
*/
public function searchAction(Request $request, EntityManagerInterface $em)
{
$query = $request->query->get('q');
$results = $em->getRepository(Client::class)->findByRefOrName($query);
$datas = [];
foreach ($results as $result) {
$datas[] = $result;
}
$response = new JsonResponse();
$response->setData([
'items' => $datas,
]);
return $response;
}
/**
* @Route("/client/synchro-documents/{id}/{typeDocument}", name="dtc_client_synchro_documents")
*/
public function renduSynchroDocuments(Request $request,EntityManagerInterface $em, Client $client,$typeDocument): Response
{
$repo_cron= $em->getRepository(Cron::class);
$cron = $repo_cron->findOneBy(["client"=>$client,"tacheCron"=>97,"echec"=>0,"dateFin"=>null]);
$lancer_synchro = false;
$now = new \DateTime();
if (
$client->getDateSynchroDocumentsErp() === null ||
$client->getDateSynchroDocumentsErp() < (clone $now)->modify('-12 hours')
) {
$lancer_synchro = true;
}
$lancer_synchro = true;
return $this->render(
'Clients/Client/synchro_document.html.twig',
[
'lancer_synchro'=>$lancer_synchro,
'typeDocument'=>$typeDocument,
'cronId' => $cron ? $cron->getId() : null
]
);
}
/**
* @Route("/client/import-progress/{id}", name="import_progress")
*/
public function progress($id, EntityManagerInterface $em)
{
$cron = $em->getRepository(Cron::class)->find($id);
$status = "";
if(is_object($cron->getDateFin())) $status ="finished";
return $this->json([
'status' => $status,
'progress' => $cron->getProgression()
]);
}
/**
* @Route("/client/import-documents/{id}/{typeDocument}", name="dtc_client_import_documents")
*/
public function import(Client $client,$typeDocument="", EntityManagerInterface $em)
{
$repo_tache_cron = $em->getRepository(TacheCron::class);
$repo_cron = $em->getRepository(Cron::class);
$tache = $repo_tache_cron->find(97);
$derniersCron = $repo_cron->findBy(['tacheCron' => $tache,'client'=>$client], ['date' => 'DESC'], 1, 0);
$creer_cron = true;
$cron_id = 0;
if (count($derniersCron) > 0) {
if (is_object($derniersCron[0]) && $derniersCron[0]->getDateFin() == null) {
/*
$pid = $derniersCron[0]->getPid();
if (!file_exists("/proc/$pid")) {
$derniersCron[0]->setDateFin($dateTmp);
$derniersCron[0]->setEchec(true);
$em->persist($derniersCron[0]);
$em->flush();
}
*/
if (is_object($derniersCron[0]->getDateDebut()) && $derniersCron[0]->getDateDebut() < new \DateTime('-5 minutes')) {
$derniersCron[0]->setDateFin(new \DateTime());
$derniersCron[0]->setEchec(true);
$em->persist($derniersCron[0]);
$em->flush();
}
}
if (is_object($derniersCron[0]) && $derniersCron[0]->getDateFin() == null) {
$date = new \Datetime();
$libelle_cron = $derniersCron[0]->getLibelle()." Cron non terminé à ".$date->format("Y-m-d H:i:s");
$libelle_cron = substr($libelle_cron, strlen($libelle_cron) - 250);
$derniersCron[0]->setLibelle($libelle_cron);
$derniersCron[0]->setDescription($derniersCron[0]->getDescription()." Cron non terminé à ".$date->format("Y-m-d H:i:s"));
$em->persist($derniersCron[0]);
$em->flush();
$creer_cron = false;
$cron_id = $derniersCron[0]->getId();
}
}
if($creer_cron) {
$cron = new Cron();
$cron->setLibelle("Import des commandes depuis ERP DTC client_id:".$client->getId());
$cron->setClient($client);
$cron->setTacheCron($tache);
$cron->setEchec(false);
$cron->setProgression(rand(5, 15));
$em->persist($cron);
$em->flush();
$em->refresh($cron);
$cron_id = $cron->getId();
$cmd = sprintf(
'php %s/bin/console import:commandes %d %s %d > /dev/null 2>&1 &',
$this->getParameter('kernel.project_dir'),
$client->getId(),
$typeDocument,
$cron_id
);
exec($cmd, $output);
$pid = isset($output[0]) ? (int)$output[0] : null;
$cron->setPid($pid);
$em->persist($cron);
$em->flush();
}
return $this->json(['cronId' => $cron_id]);
}
/**
* @Route("/client/export", name="export_client")
*/
public function exportClient(EntityManagerInterface $em): Response
{
$user = $this->getUser();
if ($user->getType()->getId() != 1) {
throw new AccessDeniedException('Accès interdit à cette page.');
}
$users = $em->getRepository(Utilisateur::class)->findBy([
'type' => [4]
]);
$handle = fopen('php://temp', 'r+');
// BOM UTF-8 pour Excel
fwrite($handle, "\xEF\xBB\xBF");
// Entêtes
fputcsv($handle, ['id', 'email', 'nom','prenom','ref_client','nom_client','actif','api'], ';');
// Données
foreach ($users as $u) {
$client = "";
$ref_client = "";
if($u->getClient()) {
$client = $u->getClient()->getNom();
$ref_client = $u->getClient()->getReference();
$api = $u->getClient()->isStatutApi();
$actif = 1;
if(!is_null($u->getDateSuppression())) $actif=0;
fputcsv($handle, [
$u->getId(),
$u->getEmail(),
$u->getNom(),
$u->getPrenom(),
$ref_client,
$client,
$actif,
$api,
], ';');
}
}
rewind($handle);
$csvContent = stream_get_contents($handle);
fclose($handle);
$response = new Response($csvContent);
$filename = 'clients_' . date('Y-m-d_H-i-s') . '.csv';
$response->headers->set('Content-Type', 'text/csv; charset=UTF-8');
$response->headers->set(
'Content-Disposition',
'attachment; filename="' . $filename . '"'
);
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
return $response;
}
}