<?php
namespace App\Controller;
use App\Entity\SignedContract;
use App\Entity\User;
use App\Entity\CompanyData;
use App\Enum\Role;
use App\Enum\TypeSignedContract;
use App\Event\ClientUpdatedEvent;
use App\Form\ClientProfilType;
use App\Form\ClientType;
use App\Repository\JobRepository;
use App\Service\ConfidentialityService;
use App\Service\ContractService;
use App\Service\CreditService;
use App\Service\PdfService;
use App\Enum\Note;
use App\Service\UtilsService;
use Doctrine\ORM\EntityManagerInterface;
use App\Enum\TypePack;
use PHPUnit\Util\Json;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Repository\UserRepository;
use App\Service\UserService;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use GuzzleHttp\Client;
use App\Event\ClientDeleteWpEvent;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use App\Entity\Company;
use App\Entity\CreditHistory;
use App\Service\FrontAPIService;
use App\Repository\CompanyRepository;
use App\Repository\CampaignRepository;
use App\Service\DynamicHostService;
use Twig\Environment;
use App\Form\NoteUserType;
use App\Entity\NoteUser;
class ClientController extends AbstractController
{
public function __construct(
private FrontAPIService $frontAPIService,
private DynamicHostService $dynamicHostService,
private EntityManagerInterface $entityManager,
){}
/**
* Displays all client deleted
* Only admin views this interface
* @param UserRepository $userRepository
* @return Response
*/
#[Route('/admin/clients/deleted', name: 'client_deleted', methods: ['GET'])]
#[Route('/admin/gestionnaires/deleted', name: 'client_gestionnaires_deleted', methods: ['GET'])]
public function deleted(UserRepository $userRepository,DynamicHostService $dynamicHostService,Request $request): Response
{
if ( $request->get('_route') === 'client_gestionnaires_deleted' && !in_array(Role::ROLE_ADMIN_AGENCY->value,$this->getUser()->getRoles())) {
throw new \NotFoundHttpException('La page que vous demandez est introuvable.');
}
$list = $userRepository->findByDeleted(1);
$company = $dynamicHostService->getCompany();
if (null !== $company ) {
$list = $userRepository->getClientDeletedCompany($company);
}
return $this->render('client/deleted.html.twig', [
'clients' => $list
]);
}
#[Route('/admin/client/reactivated/{id}', name: 'client_toggle_availabilty_status_deleted')]
public function toggleAvailabilityStatusDeleted(User $user, EntityManagerInterface $entityManager): Response
{
$user->setDeleted(0);
$entityManager->flush();
$this->addFlash(
type: 'success',
message: 'Le client '.$user.' a bien été réactivé'
);
return $this->redirectToRoute('client_deleted');
}
#[Route('/admin/client/activate/{id}/{company_id}', name: 'client_activate')]
public function clientActivation(string $id,string $company_id,UserRepository $userRepository, EntityManagerInterface $entityManager,Request $request): Response
{
$agency = !is_null($request->query->get('agency')) ? true : false;
$user = $userRepository->findOneBy(['id'=>$id]);
$user->setEnabled(true);
$entityManager->flush();
$this->addFlash(
type: 'success',
message: 'Le client '.$user.' a bien été activé'
);
if ($agency) {
return $this->redirectToRoute('agency_edit',['id'=>$company_id]);
}
return $this->redirectToRoute('company_edit',['id'=>$company_id]);
}
/**
* @param UserRepository $userRepository
* @return Response
*/
#[Route('/admin/clients', name: 'client_index', methods: ['GET'])]
#[Route('/admin/gestionnaires', name: 'client_gestionnaire_index', methods: ['GET'])]
public function index(UserRepository $userRepository,Request $request,DynamicHostService $dynamicHostService): Response
{
// if ( $request->get('_route') === 'client_gestionnaire_index' && !in_array(Role::ROLE_ADMIN_AGENCY->value,$this->getUser()->getRoles())) {
// throw new \NotFoundHttpException('La page que vous demandez est introuvable.');
// }
$role = Role::ROLE_CLIENT->value;
$observer = Role::ROLE_OBSERVER->value;
$validator = Role::ROLE_VALIDATOR->value;
$roleClientAdmin = Role::ROLE_CLIENT_ADMIN->value;
$author = Role::ROLE_AUTHOR->value;
$editor = Role::ROLE_EDITOR->value;
//for adminAgency only
if (in_array(Role::ROLE_ADMIN_AGENCY->value,$this->getUser()->getRoles())) {
$company = $this->getUser()->getCompany();
$return = [
'clients' => $userRepository->findByRoleClientsByCompany('ROLE_SUBCONTRACTOR','ROLE_BOT','ROLE_MANAGER',$company),
];
if ($request->get('_route') === 'client_gestionnaire_index') {
$return = [
'clients' => $userRepository->findGestionnaireByCompany('ROLE_MANAGER',$company),
];
}
}
//for admin only
if (in_array(Role::ROLE_ADMIN->value,$this->getUser()->getRoles()) or (in_array(Role::ROLE_MANAGER->value,$this->getUser()->getRoles()) and ($this->getUser()?->getCompany()?->isTypeCompany() === false) or $this->getUser()?->getCompany()?->isTypeCompany() == null) ) {
$return = [
'clients' => $userRepository->findByRoleClients($role, $observer, $roleClientAdmin,$validator,$author, $editor ),
];
if ($request->get('_route') === 'client_gestionnaire_index') {
$return = [
'clients' => $userRepository->findGestionnaireMyFlow('ROLE_MANAGER'),
];
}
}else if ((in_array(Role::ROLE_MANAGER->value,$this->getUser()->getRoles()))) {
$return = [
'clients' => $userRepository->findByRoleClients($role, $observer, $roleClientAdmin,$validator,$author, $editor ),
];
}
$template = $request->get('_route') === 'client_gestionnaire_index' ? "client/index_agency.html.twig" : "client/index.html.twig";
return $this->render($template, $return);
}
/**
* @param User|null $user
* @param Request $request
* @param UserService $userService
* @param UserPasswordHasherInterface $hasher
* @return Response
*/
#[Route('/admin/client/ajouter', name: 'client_new', methods: ['GET','POST'])]
#[Route('/admin/gestionnaires/ajouter', name: 'client_gestionaires_new', methods: ['GET','POST'])]
#[Route('/admin/client/{id}', name: 'client_edit', methods: ['GET','POST'])]
#[Route('/admin/gestionnaires/{id}', name: 'client_gestionaires_edit', methods: ['GET','POST'])]
public function handleClient(User $user = null, Request $request, UserService $userService, UserPasswordHasherInterface $hasher, EventDispatcherInterface $dispatcher,DynamicHostService $dynamicHostService,UserRepository $userRepository): Response
{
if (null !== $user and in_array('ROLE_MANAGER', $user->getRoles()) and $request->get('_route') === 'client_edit') {
return $this->redirectToRoute('client_gestionaires_edit', ['id' => $user->getId()], Response::HTTP_SEE_OTHER);
}
$typeAction ='edit';
$isadminAgency = false;
$isManager = false;
if (in_array("ROLE_ADMIN_AGENCY", $this->getUser()->getRoles())) {
$isadminAgency = true;
}
if (in_array("ROLE_MANAGER", $this->getUser()->getRoles())) {
$isManager = true;
}
if ($user === null){
$typeAction = 'new';
$user = new User();
if (in_array("ROLE_ADMIN_AGENCY", $this->getUser()->getRoles())) {
$user->setCompany($this->getUser()->getCompany());
$isadminAgency = true;
}
}
$isCreationOfGestionary = false;
if ($request->get('_route') === 'client_gestionaires_new' or $request->get('_route') === 'client_gestionaires_edit') {
$isCreationOfGestionary = true;
}
$form = $this->createForm(ClientType::class, $user,[
'isadminAgency'=>$isadminAgency,
'isManager'=>$isManager,
'isCreationOfGestionary'=>$isCreationOfGestionary,
'url'=>$request->get('_route'),
'mail_alias_default' => implode(',', $user->getMailAlias() ?? [])
]);
$form->handleRequest($request);
$company = $dynamicHostService->getCompany();
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$data = $form->getData();
$dataInMapped = $request->request->all();
$note = $dataInMapped['note_user']['content'] ?? null;
$notePrivate = $dataInMapped['note_user_private']['content'] ?? null;
if (!is_null($note) and !empty($note)) {
$newNote = new NoteUser();
$newNote->setContent($note);
$newNote->setCreatedAt(new \DateTime());
$newNote->setType(Note::NOTE_PUBLIC->value);
$newNote->setUserToCommented($this->getUser());
$entityManager->persist($newNote);
$entityManager->flush();
$data->addNoteUser($newNote);
}
if (!is_null($notePrivate) and !empty($notePrivate) ) {
$newNote = new NoteUser();
$newNote->setContent($notePrivate);
$newNote->setCreatedAt(new \DateTime());
$newNote->setUserToCommented($this->getUser());
$newNote->setType(Note::NOTE_PRIVATE->value);
$entityManager->persist($newNote);
$entityManager->flush();
$data->addNoteUser($newNote);
}
$emailsString = $form->get('mailAliasOtherForm')->getData(); // Champ non mappé
if (!is_null($emailsString) and !empty($emailsString)) {
$emailsArray = array_map('trim', explode(',', $emailsString));
if (is_array($emailsArray) and !empty($emailsString)) {
$data->setMailAlias($emailsArray);
}
}
$userExistInSameDomaine = $userRepository->getUniqUserByCompanyByEmailForSubClientManager($user->getEmail(),$company);
if (!is_null($userExistInSameDomaine) and ($request->get('_route') === 'client_new' or $request->get('_route') === 'client_gestionaires_new')){
$this->addFlash('error', "L'utilisateur que vous tentez de créer existe déjà.");
return $this->redirectToRoute('sub_contractor_new', [], Response::HTTP_SEE_OTHER);
}
if ($request->get('_route') === 'client_new' or $request->get('_route') === 'client_gestionaires_new') {
if ($form->getData()->getRoles()[0] == 'ROLE_CLIENT_ADMIN'){
$role = Role::ROLE_CLIENT_ADMIN->value;
}
elseif($form->getData()->getRoles()[0] == 'ROLE_CLIENT'){
$role = Role::ROLE_CLIENT->value;
}
else{
$role = Role::ROLE_AUTHOR->value;
//changement de Role pour manager et administrateur pour agence
if ($form->getData()->getRoles()[0] == 'ROLE_MANAGER') {
$role = Role::ROLE_MANAGER->value;
}
if ($form->getData()->getRoles()[0] == 'ROLE_ADMIN_AGENCY') {
$role = Role::ROLE_ADMIN_AGENCY->value;
}
}
$password = $userService->generatePassword();
$hashedPassword = $hasher->hashPassword($user, $password);
$user->setRoles([$role])->setIsNewClient(false);
if(empty($form->getData()->getPassword())) {
$user->setPassword($hashedPassword)
->setEnabled(false);
}
$entityManager->persist($user);
$msg = $request->get('_route') === 'client_new' ? 'Le client a bien été ajouté' : 'Le gestionnaire a bien été ajouté';
$this->addFlash('success', $msg);
$notification = true;
//si pas de notification par chat tout les jours alors mettre par défaut.
$freqNotificationEverytime = $form->getData()->getFreqNotificationEverytime();
if(!in_array("0", $freqNotificationEverytime)){
$freqNotificationEverytime[] = 0;
$form->getData()->setFreqNotificationEverytime($freqNotificationEverytime);
}
} else {
$msg = $request->get('_route') === 'client_edit' ? 'Le client a bien été modifié' : 'Le gestionnaire a bien été modifié';
$this->addFlash('success', $msg);
$notification = false;
}
$file = $form->get('picture')->getData();
if ($file!=null) {
// $destination = $this->getParameter('file_profil_directory');
// if(!empty(trim($user->getPictureName())) && !is_null($user->getPictureName()) && file_exists("$destination/{$user->getPictureName()}") ){
// unlink("$destination/{$user->getPictureName()}");
// }
$user->setPicture($form->get('picture')->getData());
}
$entityManager->flush();
$user->setPicture(null);
$event = new ClientUpdatedEvent($user, $notification);
$dispatcher->dispatch($event, ClientUpdatedEvent::NAME);
if($this->isGranted("ROLE_CLIENT_ADMIN") and $typeAction == "edit"){
if (!is_null($user->getCompany())) {
return $this->redirectToRoute('company_edit', ['id' => $user->getCompany()->getId()], Response::HTTP_SEE_OTHER);
}else{
return $this->redirectToRoute('mission_index', [], Response::HTTP_SEE_OTHER);
}
}
return $this->redirectToRoute('client_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('client/handle.html.twig', [
'form' => $form,
'user' => $user,
'type_action' => $typeAction,
'isCreationOfGestionary' => $isCreationOfGestionary,
]);
}
/**
* @param Request $request
* @param UserRepository $userRepository
* @return JsonResponse
*/
#[Route('/api/clients/search', name: 'api_clients_search')]
public function apiSearch(Request $request, UserRepository $userRepository,CompanyRepository $companyRepository)
{
$isAdmin = false;
$user = $request->query->get('userId') != null ? $userRepository->findOneBy(['id'=>$request->query->get('userId')]) : $this->getUser();
//determine if root or client admin
if (in_array("ROLE_ADMIN", $user->getRoles())) {
$isAdmin = true;
}
$query = $request->query->get('query');
$query = trim($query);
if ($request->query->get('client') == 2) {
return new JsonResponse([
'clients' => $userRepository->apiQuerySearchProject($query,false,$isAdmin),
]);
}else{
$companyClient = null;
if ($request->query->get('client') == 1){
$role = 'ROLE_CLIENT';
if ($request->query->get('companyId')) {
$companyClient = $companyRepository->find($request->query->get('companyId'));
}
}else{
$role = 'ROLE_SUBCONTRACTOR';
}
}
//dd( $userRepository->apiQuerySearch($query, $role,false,$isAdmin,$companyClient));
return new JsonResponse([
'clients' => $userRepository->apiQuerySearch($query, $role,false,$isAdmin,$companyClient),
]);
}
#[Route('/api/clients/cgv/cgu', name: 'api_clients_cgv_cgu', methods: ['GET'])]
public function CguClient(JobRepository $jobRepository,UtilsService $utilsService, SerializerInterface $serializer,DynamicHostService $dynamicHostService,ParameterBagInterface $parameterBagInterface, ContractService $contractService,Environment $twig,PdfService $pdfService): JsonResponse
{
$userData = [
'cgu'=> $contractService->getCGU(null),
'cguClient'=> $contractService->getCGU(null, null, 'client'),
'cgv'=>$contractService->getCGV(null)
];
return new JsonResponse($userData,
Response::HTTP_OK,
[],
);
}
#[Route('/api/clients/creation', name: 'api_clients_creation', methods: ['GET'])]
public function createClients(JobRepository $jobRepository,UtilsService $utilsService, SerializerInterface $serializer,DynamicHostService $dynamicHostService,ParameterBagInterface $parameterBagInterface, ContractService $contractService,Environment $twig,PdfService $pdfService,EntityManagerInterface $entityManager): JsonResponse
{
$user = new User();
$user->setUserData(null);
$user->setEmail(uniqid());
$user->setRoles(['ROLE_SUBCONTRACTOR']);
$user->setDeleted(true);
$user->setEnabled(false);
$entityManager->persist($user);
$entityManager->flush();
return new JsonResponse([
'id' => $user->getId(),
]);
}
#[Route('/api/clients/creation/role/client', name: 'api_clients_creation_role_client', methods: ['GET'])]
public function createClientsWithRoles(JobRepository $jobRepository,UtilsService $utilsService, SerializerInterface $serializer,DynamicHostService $dynamicHostService,ParameterBagInterface $parameterBagInterface, ContractService $contractService,Environment $twig,PdfService $pdfService,EntityManagerInterface $entityManager): JsonResponse
{
$user = new User();
$user->setUserData(null);
$user->setEmail(uniqid());
$user->setDeleted(true);
$user->setRoles(['ROLE_CLIENT']);
$user->setEnabled(false);
$entityManager->persist($user);
$entityManager->flush();
return new JsonResponse([
'id' => $user->getId(),
]);
}
#[Route('/api/clients/{id}', name: 'api_clients', methods: ['GET'])]
public function apiClients(User $user,JobRepository $jobRepository,UtilsService $utilsService, SerializerInterface $serializer,DynamicHostService $dynamicHostService,ParameterBagInterface $parameterBagInterface, ContractService $contractService,Environment $twig,PdfService $pdfService): JsonResponse
{
if ($user->isEnabled()) {
return new JsonResponse([
'alreadyEnabled' => true,
]);
}
$company = $dynamicHostService->getCompany($user) ;
$backUrl = $company instanceof Company ? $company->getDomaineName() : $parameterBagInterface->get('back_website_url');
$userData = [
'lastname'=> $user->getLastname(),
'firstname'=>$user->getFirstname(),
'email'=>$user->getEmail(),
'cellphone'=>$user->getCellPhone(),
'billingMethod'=>$user->getBillingMethod(),
'gender'=>$user->getGender(),
'dailyRate'=>$user->getDailyRate(),
'userData'=>[
'stateCompany'=> $user->getUserData()?->getStateCompany(),
'status'=> $user->getUserData()?->getStatus(),
'country'=> $user->getUserData()?->getCountry(),
'siren'=> $user->getUserData()?->getSiren(),
'intracommunityTva'=> $user->getUserData()?->getIntracommunityTva(),
'address'=> $user->getUserData()?->getAddress(),
'rIB'=> $user->getUserData()?->getRIB(),
'accountOwner'=> $user->getUserData()?->getAccountOwner(),
'iBAN'=> $user->getUserData()?->getIBAN(),
'bicSwift'=> $user->getUserData()?->getBicSwift(),
'spokenLanguages'=> $user->getUserData()?->getSpokenLanguages(),
'companyName'=> $user->getUserData()?->getCompanyName(),
'tva'=> $user->getUserData()?->getTva(),
],
'salary'=>$user->getSalary(),
'cgu'=> $contractService->getCGU($user),
'cguClient'=> $contractService->getCGU($user, null, 'client'),
'cgv'=>$contractService->getCGV($user),
'jobs'=> $user->getJobs()!=null ? array_map(function($job){
return $job->getId();
},($user->getJobs())->toArray()) : [],
'jobsAgency'=> $utilsService->getIds($jobRepository->findByAgency($company)),
'link'=>[
'cguSubcontractor'=> $company instanceof Company ? "$backUrl/condition-generale/{$company->getId()}-cgu-sous-traitant" : $contractService->getLinkMyFlowCGUSubcontractor(),
'cguClient'=> $company instanceof Company ? "$backUrl/condition-generale/{$company->getId()}-cgu-client" : $contractService->getLinkMyFlowCGUClient(),
'cgv'=> $company instanceof Company ? "$backUrl/condition-generale/{$company->getId()}-cgv" : $contractService->getLinkMyFlowCGV(),
],
'agency'=>[
'name'=> $company instanceof Company ? $company->getName() : '',
'id'=> $company instanceof Company ? $company->getId() : ''
],
'contractSubClient'=>$twig->render(
$pdfService->getLinkTwigToGenerateContratBetweenAgenceAndSubcontractor($user),
$pdfService->getParamsToGenerateContratBetweenAgenceAndSubcontractor($user)
),
];
return new JsonResponse($userData,
Response::HTTP_OK,
[],
);
}
#[Route('/api/clients/{id}', name: 'api_edit_client', methods: ['POST'])]
public function apiEditClient(User $user, ConfidentialityService $confidentialityService, Request $request, UserPasswordHasherInterface $passwordHasher, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher): JsonResponse
{
$user->setFirstname($request->request->get('firstname'));
$user->setLastname($request->request->get('lastname'));
$user->setCellPhone($request->request->get('cellPhone'));
$user->setEnabled(true);
$user->setGender($request->request->get('gender'));
$hashedPassword = $passwordHasher->hashPassword($user, $request->request->get('password'));
$user->setPassword($hashedPassword);
$entityManager->persist($user);
$entityManager->flush();
$event = new ClientUpdatedEvent($user, false, $request->request->get('password'), true);
$dispatcher->dispatch($event, ClientUpdatedEvent::NAME);
$confidentialityService->addSignedContractForClient($user, true, false, true);
return new JsonResponse(['result' => 'success']);
}
#[Route('/api/clients/external/{id}', name: 'api_edit_external_client', methods: ['POST'])]
public function apiEditExternalClient(User $user, Request $request, UserPasswordHasherInterface $passwordHasher, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher,ConfidentialityService $confidentialityService): JsonResponse
{
$user->setFirstname($request->request->get('firstname'));
$user->setLastname($request->request->get('lastname'));
$user->setEmail($request->request->get('email'));
$user->setCellPhone($request->request->get('cellPhone'));
$user->setEnabled(true);
$user->setGender($request->request->get('gender'));
$user->setDeleted(false);
$hashedPassword = $passwordHasher->hashPassword($user, $request->request->get('password'));
$user->setPassword($hashedPassword);
$entityManager->flush();
$event = new ClientUpdatedEvent($user, false, $request->request->get('password'), true);
$dispatcher->dispatch($event, ClientUpdatedEvent::NAME);
$confidentialityService->addSignedContractForClient($user,true,false,true);
return new JsonResponse(['result' => 'success']);
}
#[Route('/api/clients/external/company/{id}', name: 'api_edit_external_company_client', methods: ['POST'])]
public function apiEditExternalCompanyClient(User $user, Request $request,CreditService $creditService, UserPasswordHasherInterface $passwordHasher, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher,CompanyRepository $companyRepository,ConfidentialityService $confidentialityService): JsonResponse
{
//infos company
$adresse = $request->request->get('adresse');
$country = $request->request->get('pays');
$rcs = $request->request->get('rcs');
$state = $request->request->get('state');
//end infos company
$logo = $request->request->get('logo');
$companyExist = true;
$company = $companyRepository->findOneByName($request->request->get('company_name'));
if (is_null($company)) {
$companyExist = false;
$company = new Company();
}
$company->setName($request->request->get('company_name'));
$company->setCreatedAt(new \DateTime());
$company->setSiren($request->request->get('siren'));
$company->setCostOfDiscountedCredit(0);
$company->setEnabled(true);
$company->setContract(3);
$company->setCustomerDiscount(0);
if (!is_null($request->request->get('logo')) and !$companyExist) {
//upload image company
$frontWebSiteUrlLogo = $this->getParameter('front_website_url_upload_logo_company').$logo;
$dirLogoCompany = $this->getParameter('dir_logo_company_kernel').$logo;
if($this->transfertLogo($frontWebSiteUrlLogo,$dirLogoCompany))
$company->setLogoName($logo);
}
if ($companyExist == false) {
$entityManager->persist($company);
$entityManager->flush();
$creditHistory = new CreditHistory();
$creditHistory->setCompany($company)
->setName("Facturation individuelle")
->setTypePack(TypePack::CASH->value)
->setIdentifier($creditService->getNewReference())
->setOrderedBy($user);
$entityManager->persist($creditHistory);
$entityManager->flush();
$this->sharedResourceCategoryService->setDefaultSharedResourceCategory($company);
}
$user->setCompany($company) ;
$entityManager->persist($user);
$entityManager->flush();
$response = $this->frontAPIService->pushCompanyToFront($company);
if (null !== $response && null === $company->getFrontId()) {
$company->setFrontId($response['id']);
$entityManager->persist($company);
$entityManager->flush();
}
//add data company
if ($companyExist == false) {
$companyData = new CompanyData();
$companyData->setCountry($country)
->setAddress($adresse)
->setRcs($rcs)
->setState($state);
$entityManager->persist($companyData);
$company->setCompanyData($companyData);
$entityManager->persist($company);
$entityManager->flush();
}
//mise a jour de l'utilisateur sur wordpress
$this->frontAPIService->pushClientToFront($user, null);
//link to user
$confidentialityService->addSignedContractForClient($user,true,false,true);
return new JsonResponse(['result' => 'success']);
}
public function transfertLogo($logoDir,$dirDest){
$imageUrl = $logoDir;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $imageUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Erreur cURL : ' . curl_error($ch);
return false;
} else {
$localFilePath = $dirDest;
try{
file_put_contents($localFilePath, $response);
}catch(\Exception $e){
return false;
}
}
curl_close($ch);
return true;
}
#[Route('/admin/client/{id}/{availabilty<enable|disable>}', name: 'client_toggle_availabilty')]
#[Route('/admin/client_gestionnaire/{id}/{availabilty<enable|disable>}', name: 'client_gestionnaire_toggle_availabilty')]
public function toggleAvailability(User $user, EntityManagerInterface $entityManager,Request $request): Response
{
$user->setEnabled(!$user->isEnabled());
$entityManager->flush();
$this->addFlash(
type: 'success',
message: 'Le client '.$user.' a bien été '. ($user->isEnabled() ? 'activé' : 'désactivé')
);
$route = $request->get('_route') === 'client_toggle_availabilty' ? 'client_index': 'client_gestionnaire_index';
return $this->redirectToRoute($route);
}
#[Route('/admin/client/{id}/invitation', name: 'client_send_another_invitation')]
public function sendAnotherInvitation(EventDispatcherInterface $dispatcher, User $user): Response
{
$event = new ClientUpdatedEvent($user, true, null, false, false);
$dispatcher->dispatch($event, ClientUpdatedEvent::NAME);
$this->addFlash(
type: 'success',
message: 'L\'email d\'invitation a bien été envoyé'
);
return $this->redirectToRoute('client_index');
}
#[Route('/admin/client/{id}/supprimer', name: 'client_remove', methods: ['GET','POST'])]
#[Route('/admin/gestionnaires/{id}/supprimer', name: 'client_gestionnaire_remove', methods: ['GET','POST'])]
public function deleteClient(User $user,UserService $userService, EntityManagerInterface $entityManager,EventDispatcherInterface $dispatcher,ParameterBagInterface $parameterBag,Request $request)
{
$event = new ClientDeleteWpEvent($userService->delete($user), $parameterBag);
$dispatcher->dispatch($event, ClientDeleteWpEvent::NAME);
$txt = "client";
$route = 'client_index';
if ( $request->get('_route') === 'client_gestionnaire_remove'){
$txt = "gestionnaire";
$route = "client_gestionnaire_index";
}
$this->addFlash(
'success',
"Le {$txt} a bien été supprimé"
);
return $this->redirect($request->headers->get('referer')) ? $this->redirect($request->headers->get('referer')) : $this->redirectToRoute($route);
}
#[Route('/mon-profil-client', name: 'my_profil_client', methods: ['GET','POST'])]
public function Profil(Request $request, EntityManagerInterface $entityManager, UserPasswordHasherInterface $hasher,EventDispatcherInterface $dispatcher): Response
{
$user = $this->getUser();
$form = $this->createForm(ClientProfilType::class, $user,['isadmin'=>$this->isGranted(Role::ROLE_ADMIN->value)]);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
if (!empty($form->getData()->getPlainPassword())){
$hashedPassword = $hasher->hashPassword($user, $form->getData()->getPlainPassword());
$user->setPassword($hashedPassword);
}
$file = $form->get('picture')->getData();
if ($file!=null) {
$destination = $this->getParameter('file_profil_directory');
try {
if(!empty(trim($user->getPictureName())) && !is_null($user->getPictureName())){
unlink("$destination/{$user->getPictureName()}");
}
} catch (\Throwable $th) {
}
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$originalFilename = str_replace(' ','-',$originalFilename);
//$originalFilename = preg_replace('/[^A-Za-z0-9 ]/', '', $originalFilename);
$originalFilename = $this->replaceAllSpecialCharFromString($originalFilename);
$newFilename = $originalFilename .uniqid().'.' . $file->guessExtension();
$file->move(
$destination,
$newFilename
);
$user->setPictureName($newFilename);
}
$user->setPicture(null);
$entityManager->persist($user);
$entityManager->flush();
$event = new ClientUpdatedEvent($user, false);
$dispatcher->dispatch($event, ClientUpdatedEvent::NAME);
if($request->request->get('remove-my-account')!=null){
return $this->redirectToRoute('my_profil_client',[
'confirm_account_deleted'=> true,
]);
}
$this->addFlash(
'success',
'Votre profil a bien été modifié'
);
return $this->redirectToRoute('my_profil_client');
} elseif ($form->isSubmitted()) {
$this->addFlash(
'error',
'Merci de corriger les erreurs',
);
}
return $this->renderForm('client/profil.html.twig', [
'form' => $form,
]);
}
#[Route('/admin/client/{id}/renvoie-email-inscription', name: 'client_resend_registration_email', methods: ['GET','POST'])]
public function resendRegistrationEmail(Request $request, User $user, EventDispatcherInterface $dispatcher)
{
$event = new ClientUpdatedEvent($user, true);
$dispatcher->dispatch($event, ClientUpdatedEvent::NAME);
$this->addFlash(
type: 'success',
message: 'L\'email d\'inscription a bien été envoyé',
);
return $this->redirect($request->headers->get('referer'));
}
#[Route('/my-subcontractor-interlocutors/{userId}', name: 'my_subcontractor_interlocutors', methods: ['GET'])]
public function showInterlocutors(string $userId, UserRepository $userRepository, CampaignRepository $campaignRepository): Response
{
$agency = $this->dynamicHostService->getCompany($this->getUser());
$nbYearMax = 3;
$user = $userRepository->find($userId);
$campaigns = $campaignRepository->findAllInterlocutors($user, $nbYearMax);
$userManagerAndAdminAgency = $agency != null && $user!= null ? $userRepository->getManagerAndAdminAgency($agency, $user) : [];
$allParticipantsMail = [];
$allParticipants = [];
foreach ($campaigns as $campaign) {
foreach ($campaign->getMissions() as $mission) {
foreach ($mission->getParticipants() as $participant) {
if ($participant->getRole() == Role::ROLE_SUBCONTRACTOR) {
if (!in_array($participant->getUser()->getEmail(), $allParticipantsMail)) {
$allParticipantsMail[] = $participant->getUser()->getEmail();
$allParticipants[] = $participant;
}
}
}
}
}
return $this->renderForm('client/interlocutors.html.twig', [
'subcontractors' => $allParticipants,
'user_manager_and_admin_agency' => $userManagerAndAdminAgency,
'is_agency'=> $agency == null ? false : true
]);
}
private function replaceAllSpecialCharFromString($values){
$string = str_replace(
['à', 'á', 'â', 'ã', 'ä', 'å', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ'],
['a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y'],
$values
);
return preg_replace('/[^A-Za-z0-9\- ]/', '', $string);
}
#[Route('/note-client-modified/{id}-{idUser}', name: 'note_client_modified', methods: ['GET','POST'])]
public function noteModification(NoteUser $note,$idUser, Request $request,EntityManagerInterface $entityManager): Response
{
$content = $request->request->get('info_mission_edit')['content'];
if (!is_null($content) and !empty($content)) {
$note->setContent($content);
$entityManager->persist($note);
$entityManager->flush();
}
$this->addFlash(
type: 'success',
message: 'Modification effectuée'
);
return $this->redirectToRoute('client_edit',['id'=>$idUser]);
}
#[Route('/note-client-deleted/{id}-{idUser}', name: 'note_client_deleted', methods: ['GET','POST'])]
public function noteDeleted(NoteUser $note,$idUser, Request $request,EntityManagerInterface $entityManager): Response
{
$entityManager->remove($note);
$entityManager->flush();
$this->addFlash(
type: 'success',
message: 'Suppression effectuée'
);
return $this->redirectToRoute('client_edit',['id'=>$idUser]);
}
}