<?php
namespace App\Controller;
use Pusher\Pusher;
use App\Entity\Role;
use App\Entity\User;
use App\Entity\Report;
use DateTimeImmutable;
use GuzzleHttp\Client;
use App\Entity\Message;
use App\Entity\Payment;
use App\Entity\Platform;
use App\Entity\WaitMessage;
use App\Entity\Conversation;
use App\Controller\NotificationController;
use App\DBAL\MultiDbConnectionWrapper;
use Psr\Log\LoggerInterface;
use App\Service\EntityService;
use App\Service\PusherService;
use App\Service\ProfileService;
use App\Service\RequestService;
use App\Service\EntityValidator;
use App\Service\LanguageService;
use App\Service\SupAndOpService;
use App\Repository\GifRepository;
use Symfony\Component\Mime\Email;
use App\Repository\NoteRepository;
use App\Repository\RoleRepository;
use App\Repository\UserRepository;
use App\Service\PaginationService;
use Symfony\Component\Yaml\Dumper;
use App\Service\sendMessageService;
use App\Service\WaitMessageService;
use App\Repository\ProfilRepository;
use App\Repository\ReportRepository;
use App\Repository\MeetingRepository;
use App\Repository\MessageRepository;
use App\Repository\PaymentRepository;
use App\Service\MessageOnHoldService;
use App\Repository\LanguageRepository;
use App\Repository\PlatformRepository;
use App\Service\ReceiveMessageService;
use App\Service\EntityValidatorService;
use App\Repository\ProfilTypeRepository;
use Doctrine\ORM\EntityManagerInterface;
use App\Repository\InformationRepository;
use App\Repository\MessageTypeRepository;
use App\Repository\WaitMessageRepository;
use App\Repository\ConversationRepository;
use App\Repository\PhotoRequestRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\MessageTeaserOrHoldRepository;
use App\Repository\SentMessageTeaserOrHoldRepository;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use App\Repository\PhotoRepository;
use App\Repository\TypeMessageRepository;
use App\Repository\RateRepository;
#[Route('/api', name: 'api_')]
class UserController extends AbstractController
{
private $notificationController;
private $photoRepository;
private $paymentRepository;
private $receiveMessageService;
private $jwtTokenManager;
private $userRepository;
private $userPasswordHasherInterface;
private $roleRepository;
private $gifRepository;
private $entityManagerInterface;
private $entityValidatorService;
private $profilRepository;
private $requestService;
private $conversationRepository;
private $profileService;
private $pusherService;
private $profilTypeRepository;
private $messageRepository;
private $serializer;
private $waitMessageRepository;
private $photoRequestRepository;
private $waitMessageService;
private $entityService;
private $reportRepository;
private $logger;
private $messageOnHoldService;
private $sendMessageService;
private $languageRepository;
private const ADMIN = 'administrator';
private const SUPERVISOR = 'supervisor';
private const OPERATOR = 'operator';
private const QC = 'qualitycontroller';
private const ACCOUNTANT = 'accountant';
private $platformRepository;
private $languageService;
private $tokenStorageInterface;
private $paginator;
private $sentMessageTeaserOrHoldRepository;
private $messageTeaserOrHoldRepository;
private $messageTypeRepository;
private $sendPusherService;
private $noteRepository;
private $meetingRepository;
private $informationRepository;
private $typeMessageRepository;
private $rateRepository;
public function __construct(RateRepository $rateRepository, NotificationController $notificationController,TypeMessageRepository $typeMessageRepository, PhotoRepository $photoRepository, InformationRepository $informationRepository, MeetingRepository $meetingRepository, PaymentRepository $paymentRepository, NoteRepository $noteRepository, SupAndOpService $sendPusherService, PaginationService $paginator, MessageTeaserOrHoldRepository $messageTeaserOrHoldRepository, SentMessageTeaserOrHoldRepository $sentMessageTeaserOrHoldRepository, MessageTypeRepository $messageTypeRepository, ReceiveMessageService $receiveMessageService, JWTTokenManagerInterface $jwtTokenManager, PhotoRequestRepository $photoRequestRepository, GifRepository $gifRepository, UserRepository $userRepository, WaitMessageRepository $waitMessageRepository, UserPasswordHasherInterface $userPasswordHasherInterface, RoleRepository $roleRepository, EntityManagerInterface $entityManagerInterface, EntityValidatorService $entityValidatorService, ProfilRepository $profilRepository, MessageRepository $messageRepository, RequestService $requestService, ConversationRepository $conversationRepository, ProfilTypeRepository $profilTypeRepository, ProfileService $profileService, SerializerInterface $serializer, PusherService $pusherService, WaitMessageService $waitMessageService, EntityService $entityService, ReportRepository $reportRepository, LoggerInterface $logger, MessageOnHoldService $messageOnHoldService, SendMessageService $sendMessageService, LanguageRepository $languageRepository, PlatformRepository $platformRepository, LanguageService $languageService, TokenStorageInterface $tokenStorageInterface)
{
$this->notificationController = $notificationController;
$this->photoRepository = $photoRepository;
$this->paymentRepository = $paymentRepository;
$this->messageTypeRepository = $messageTypeRepository;
$this->messageTeaserOrHoldRepository = $messageTeaserOrHoldRepository;
$this->sentMessageTeaserOrHoldRepository = $sentMessageTeaserOrHoldRepository;
$this->jwtTokenManager = $jwtTokenManager;
$this->receiveMessageService = $receiveMessageService;
$this->userRepository = $userRepository;
$this->userPasswordHasherInterface = $userPasswordHasherInterface;
$this->roleRepository = $roleRepository;
$this->entityManagerInterface = $entityManagerInterface;
$this->entityValidatorService = $entityValidatorService;
$this->profilRepository = $profilRepository;
$this->requestService = $requestService;
$this->conversationRepository = $conversationRepository;
$this->profileService = $profileService;
$this->profilTypeRepository = $profilTypeRepository;
$this->messageRepository = $messageRepository;
$this->serializer = $serializer;
$this->waitMessageRepository = $waitMessageRepository;
$this->gifRepository = $gifRepository;
$this->photoRequestRepository = $photoRequestRepository;
$this->pusherService = $pusherService;
$this->waitMessageService = $waitMessageService;
$this->entityService = $entityService;
$this->reportRepository = $reportRepository;
$this->logger = $logger;
$this->messageOnHoldService = $messageOnHoldService;
$this->sendMessageService = $sendMessageService;
$this->languageRepository = $languageRepository;
$this->platformRepository = $platformRepository;
$this->languageService = $languageService;
$this->tokenStorageInterface = $tokenStorageInterface;
$this->paginator = $paginator;
$this->sendPusherService = $sendPusherService;
$this->noteRepository = $noteRepository;
$this->meetingRepository = $meetingRepository;
$this->informationRepository = $informationRepository;
$this->typeMessageRepository = $typeMessageRepository;
$this->rateRepository = $rateRepository;
}
/**
* API pour la connexion dans un text moding en fonction du rôle
*
*/
#[Route('/login', name: 'login', methods: ['POST'])]
public function login(Request $request)
{
[$mail, $password, $role ] = $this->requestService->getFromDataRequestBody('mail', 'password', 'role');
$user = $this->userRepository->findOneBy(['mail' => $mail]);
if (!$user) return $this->json(['message' => 'Email non trouvé'], Response::HTTP_BAD_REQUEST);
if ($role != $user->getRoles()[0]) return $this->json(['message' => 'Role non autorisé'], Response::HTTP_UNAUTHORIZED);
if (!$this->userPasswordHasherInterface->isPasswordValid($user, $password)) {
return $this->json(['message' => 'Mot de passe invalide'], Response::HTTP_FORBIDDEN);
}
$currentDate = new \DateTimeImmutable();
$userSuspendDate = $user->getSuspend();
$userDeleted = $user->isDeleted();
if ($userSuspendDate != null) {
if ($userSuspendDate > $currentDate) {
return $this->json(['date' => $userSuspendDate, 'message' => 'Votre compte a été suspendu pendant 7 jours vous ne pouvez pas accédez'], 403);
}
}
if ($userDeleted == true) {
return $this->json(['message' => 'Utilisateur renvoyer'], Response::HTTP_UNAUTHORIZED);
}
$user->setStatus('free');
$user->setConv(NULL);
$user->setAnswer(true);
$token = $this->jwtTokenManager->create($user);
$this->entityService->saveEntity($user);
$this->pusherService->createPusher();
$this->pusherService->triggerEvent('private-conversation', 'status', [
'id' => $user->getId(),
'status' => $user->getStatus()
]);
// changement de statistic new design
$languageName = $user->getLanguage()->getName();
$statistic2 = [
"name" => "agents",
"language" => $languageName,
"field" => "online",
"value" => 1
];
// statistic
$statistic = [
"name" => "operator",
"field" => "online",
"value" => 1
];
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($languageName);
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statistic2);
$this->pusherService->triggerEvent('private-statistic', strval($userReal->getId()), $statistic);
}
return $this->json(['token' => $token, "role" => $user->getRoles()[0], "userId" => $user->getId(), "userName" => $user->getName(), 'status' => $user->getStatus(), 'languageName' => $user->getLanguage()->getName(),'accessareas' => json_decode($user->getAccessareas())], Response::HTTP_OK);
}
#[Route('/pusher/user-auth', name: "pusher_user_auth", methods: ["GET"])]
public function userAuth(Request $request, SerializerInterface $serializer)
{
$socketId = $request->query->get('socket_id');
$channelName = $request->query->get('channel_name');
$callback = $request->query->get('callback');
$user = [
'id' => 'id0',
'channel' => $channelName,
'user_info' => [
'name' => 'test',
],
'watchlist' => ['another_id_1', 'another_id_2']
];
$pusher = $this->pusherService->createPusher();
if ($socketId) {
$user = json_encode($user);
$auth = $pusher->authorizeChannel($channelName, $socketId, $user);
$output = $callback . "(" . $auth . ");";
return new Response($output, 200);
} else {
return $this->json('no id', 400);
}
}
/**
* API pour s'inscrire au text moding
*/
#[Route('/register', name: 'register', methods: ['POST'])]
public function register()
{
$userRole = $this->getUser();
if (!$userRole){
return $this->json(["message" => "Vous n'êtes pas connecté"], 401);
}
[$email, $password, $roleName, $login, $name, $country, $languageName, $paymentName, $bankName, $iban, $bic, $paymentMail, $fullName, $fullAddress, $companyname, $folder, $accessareas, $validity] = $this->requestService->getFromDataRequestBody('mail', 'password', 'role', 'login', 'name', 'country', 'languageName', 'paymentName', 'bankname', 'iban', 'bic', 'paymail', 'fullName', 'fullAddress', 'company', 'folder', 'accessarea', 'validity');
$users = $this->userRepository->findOneBy(['login' => $login, 'mail' => $email]);
if ($users) return $this->json(['error' => 'Login ou mail déjà utiliser', Response::HTTP_CONFLICT]);
$allowedRoles = ['operator', 'supervisor', 'administrator', 'accountant', 'qualitycontroller'];
$this->languageService->handleEmptyRepository();
$language = $this->languageRepository->findOneBy(['name' => $languageName]);
if (!in_array($roleName, $allowedRoles)) {
return $this->json(['error' => 'Role non trouvé'], Response::HTTP_NOT_FOUND);
}
$role = $this->roleRepository->findOneBy(['name' => $roleName]);
// $folder = $this->platformRepository->findOneBy(['id' => $tmfolder]);
if (!$role) {
$role = new Role();
$role->setName($roleName);
$this->entityManagerInterface->persist($role);
}
if ($role->getName() == 'operator') {
$payment = $this->paymentRepository->findOneBy(['Name' => $paymentName]);
if (!$payment) {
$payment = new Payment();
$payment->setName($paymentName);
$this->entityManagerInterface->persist($payment);
}
}
$user = new User();
$hashedPassword = $this->userPasswordHasherInterface->hashPassword($user, $password);
$user->setMail($email);
$user->setLogin($login);
$user->setPassword($hashedPassword);
$user->setRole($role);
$user->setName($name);
$user->setCountry($country);
$user->setStatus('disconnect');
$user->setLanguage($language);
$user->setDateInscription(new \DateTimeImmutable());
if ($role->getName() != 'administrator')
{
$user->setFullName($fullName);
$user->setAddress($fullAddress);
};
if ($role->getName() == 'operator') {
$user->setPayment($payment);
$user->setBankname($bankName);
$user->setIban($iban);
$user->setBic($bic);
$user->setPaymail($paymentMail);
};
if ($role->getName() == 'administrator') {
$user->setCompanyname($companyname);
$user->setTmfolder($folder);
$user->setAccessareas($accessareas);
$user->setValidity(new \DateTimeImmutable($validity));
};
if($userRole->isIsTest()){
$dataBaseName = "tm_db_" . $userRole->getName() . "_" . $userRole->getId();
$user->setDataBaseName($dataBaseName);
}
$errors = $this->entityValidatorService->validateEntity($user);
if (count($errors) > 0) {
return $this->json(['errors' => $this->entityValidatorService->getErrorMessages($errors)], Response::HTTP_BAD_REQUEST);
}
$this->entityService->saveEntity($user);
$typeR = null;
if($role->getName() === self::OPERATOR) $typeR = 0;
else if($role->getName() === self::QC) $typeR = 1;
if($typeR !== null) $this->messageOnHoldService->createNewCntrlArch($user,$typeR);
$token = $this->jwtTokenManager->create($user);
return $this->json(['message' => 'Utilisateur enregistré avec succés', 'token' => $token,'id' => $user->getId()], Response::HTTP_OK);
}
/**
*
* API pour recevoir le message d'un site
*
*/
#[Route('/receive_message', name: 'receive_message', methods: ['POST'])]
public function ReceiveMessage(Request $request)
{
//Récupération du message, faux profil et vrai profil
$datas = json_decode($request->getContent(), true);
$this->logger->info(json_encode($datas));
$events = $datas['events'][0];
$name = $events['name'];
$channel = $events['channel'];
// Renvoyer immédiatement une réponse 200 OK à Pusher
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$response->send();
if ($name == 'channel_vacated') {
$id = str_replace('private-', '', $channel);
$id = intval($id);
if ($id != 0) {
$user = $this->userRepository->findOneBy(['id' => $id]);
if ($user) {
$user->setStatus('disconnect');
$this->entityService->saveEntity($user);
$conv = $user->getConv();
$this->pusherService->createPusher();
if ($conv) {
$role = $this->roleRepository->findOneBy(['name' => 'operator']);
$users = $this->userRepository->findOneBy(['role' => $role, 'status' => 'free','language' => $user->getLanguage()]);
if ($users) {
$conv->setPriority($users);
$this->entityManagerInterface->persist($conv);
$this->pusherService->triggerEvent('private-' . $users->getId(), 'onHold', []);
}else {
$waitMsg = $this->waitMessageRepository->findBy(['conv' => $conv, 'deleted' => true]);
$wait_id = [];
foreach ($waitMsg as $msg) {
$wait_id[] = $msg->getId();
$msg->setDeleted(false);
$this->entityManagerInterface->persist($msg);
}
$PusherHoldStatus = [
'id' => $wait_id,
'type' => false
];
$this->pusherService->triggerEvent('private-conversation', 'change-status', $PusherHoldStatus);
$conv->setPriority(NULL);
$this->entityManagerInterface->persist($conv);
}
}
$user->setConv(NULL);
$this->entityService->saveEntity($user);
$this->pusherService->triggerEvent('private-conversation', 'status', [
'id' => $user->getId(),
'status' => $user->getStatus()
]);
// changement de statistic new design
$languageName = $user->getLanguage()->getName();
$statistic2 = [
"name" => "agents",
"language" => $languageName,
"field" => "online",
"value" => -1
];
// statistic
$statistic = [
"name" => "operator",
"field" => "online",
"value" => -1
];
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($languageName);
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statistic2);
$this->pusherService->triggerEvent('private-statistic', strval($userReal->getId()), $statistic);
}
}
}
return $this->json(['success' => true], Response::HTTP_OK);
} else if ($name == 'channel_occupied') {
return $this->json(null,200);
} else {
$data = json_decode($events['data'], true);
$message = $data['content'];
$realProfilId = $data['real_profil'];
$fakeProfilId = $data['fake_profil'];
$type_mess = $data['type_mess'];
$lastId = $data['last_id'];
$this->logger->info($name);
$realProfil = $this->profilRepository->findOneBy(['id' => $realProfilId]);
$senderMessage = $realProfil;
$receiveMessage = $this->profilRepository->findOneBy(['id' => $fakeProfilId]);
$languageName = $receiveMessage->getLanguage()->getName();
$language = $this->languageRepository->findOneBy(['name' => $languageName]);
$rProfil = $senderMessage->getProfilType()->getName();
if ( $rProfil != 'real_profil') {
return $this->json(["message" => "Cette message ne peut pas envoyer dans le serveur"], Response::HTTP_UNAUTHORIZED);
}
$fprofil = $receiveMessage->getProfilType()->getName();
if ( $fprofil != 'fake_profil') {
return $this->json(["message" => "Cette message ne peut pas envoyer dans le serveur"], Response::HTTP_UNAUTHORIZED);
}
$Conversation = $this->conversationRepository->findOneBy([
'sender_profil' => $senderMessage,
'receive_profil' => $receiveMessage,
]);
$this->pusherService->createPusher();
$messageAt = new DateTimeImmutable();
$type = $this->profilTypeRepository->findOneBy(['name' => 'real_profil']);
// $type = $senderMessage->getProfilType()->getId();
if ($Conversation) {
$dataRealProfil = $this->profileService->getProfil($Conversation, 'vp');
$dataFakeProfil = $this->profileService->getProfil($Conversation, 'fp');
if ($Conversation->getKickoff()) {
return $this->json('kickoff', Response::HTTP_UNAUTHORIZED);
} else if ($Conversation->getSuspend()) {
$dateSuspend = $Conversation->getSuspend();
if ($dateSuspend > $messageAt) {
return $this->json('suspend', Response::HTTP_ALREADY_REPORTED);
} else {
$Conversation->setSuspend(null);
$this->entityManagerInterface->persist($Conversation);
}
}
$convId = $Conversation->getId();
$typeMess = $this->typeMessageRepository->findOneBy(['name' => 'message']);
if($type_mess == 'poke' || $type_mess == 'teaser' || $type_mess == 'stop' ){
$lastMessage = $this->messageRepository->findOneBy([ 'id' => $lastId ]);
$content = new WaitMessage($messageAt, $message, $Conversation, $Conversation->getLanguage(), NULL);
$content->setMessType($typeMess);
$content->setResponseWait($lastMessage);
$this->entityManagerInterface->persist($content);
$this->entityManagerInterface->flush();
// changement de statistic new design
$statisticNew = [
"name" => $type_mess == 'stop' ? $type_mess : $type_mess . "s",
"language" => $Conversation->getLanguage()->getName(),
"platform" => $Conversation->getPlatform()->getName(),
"field" => $type_mess == 'stop' ? "answer" : "answered",
"value" => 1
];
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($Conversation->getLanguage()->getName());
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticNew);
}
}else{
$content = new WaitMessage($messageAt, $message, $Conversation, $Conversation->getLanguage(), NULL);
$content->setMessType($typeMess);
$this->entityManagerInterface->persist($content);
$this->entityManagerInterface->flush();
}
$MessHold = [
'id' => $content->getId(),
'sender_profil' => $content->getConv()->getSenderProfil()->getId(),
'receiver_profil' => $content->getConv()->getReceiveProfil()->getId(),
'message_at' => $content->getCreatedAt()->format('Y-m-d H:i:s'),
'content' => $content->getMessage(),
'message_id' => $content->getId(),
'type_profil' => $type->getId(),
'gifs' => [],
'photos' => [],
'type_mess' => $content->getMessType()->getName(),
];
$this->pusherService->triggerEvent('private-message', "add", $MessHold);
$data2 = $this->messageOnHoldService->createContent(false, $messageAt, $message, $Conversation, $content->getId(), false, NULL, $type, NULL, NULL);
$wait_id[] = $content->getId();
$priority = $Conversation->getPriority();
if ($priority) {
if ($priority->getStatus() == 'disconnect') {
$Conversation->setPriority(NULL);
$this->entityService->saveEntity($Conversation);
$priority = null;
} else {
$priority = $Conversation->getPriority();
}
}
if ($priority) {
if ($priority->getStatus() == 'free') {
// $content = new Message($priority, $Conversation, $message,$type, $messageAt, NULL, NULL);
$contentData = $this->messageOnHoldService->createContent(false, $messageAt, $message, $Conversation, NULL, false, NULL, $type, NULL, NULL);
$data2['status'] = true;
$this->pusherService->triggerEvent('private-conversation', 'add-hold', $data2);
$Data = $this->messageOnHoldService->getConversation($Conversation, $wait_id);
$messageData[] = $contentData;
foreach ($Data['messageData'] as $mess) {
$messageData[] = $mess;
}
$content->setDeleted(true);
$priority->setStatus('occuped');
$priority->setConv($Conversation);
$this->entityService->saveEntity($priority);
$Conversation->setPriority($priority);
$this->entityService->saveEntity($Conversation);
$infos = $this->profileService->getInfoMeeting($Conversation);
$data = [
'wait_id' => $wait_id,
'convId' => $convId,
'message_data' => $messageData,
'real_profil' => $dataRealProfil,
'fake_profil' => $dataFakeProfil,
'meeting' => $infos['meet'],
'info' => $infos['info'],
'type_mess' => $content->getMessType()->getName()
];
$statistic = [
"name" => "conversation",
"field" => "onHold",
"value" => 1
];
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($priority->getLanguage()->getName());
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic', strval($userReal->getId()), $statistic);
}
$this->sendPusherService->sendPusher($priority, $data);
} else { //else free
$this->pusherService->triggerEvent('private-conversation', 'add-hold', $data2);
$this->pusherService->triggerEvent('private-' . strval($priority->getId()), 'countOnHoldEvent', [
'count' => 1,
]);
$statistic = [
"name" => "conversation",
"field" => "onHold",
"value" => 1
];
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($priority->getLanguage()->getName());
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic', strval($userReal->getId()), $statistic);
}
}
$this->entityManagerInterface->flush();
// changement de statistic new design
$statisticNew = [
"name" => "trafic",
"language" => $Conversation->getLanguage()->getName(),
"platform" => $Conversation->getPlatform()->getName(),
"field" => "alreadyAllocated",
"value" => 1
];
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($Conversation->getLanguage()->getName());
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticNew);
}
} else { // else priority
// changement de statistic new design
$statisticNew = [
"name" => "trafic",
"language" => $Conversation->getLanguage()->getName(),
"platform" => $Conversation->getPlatform()->getName(),
"field" => "notAllocated",
"value" => 1
];
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($Conversation->getLanguage()->getName());
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticNew);
}
$this->receiveMessageService->findUser($data2, $content, $wait_id, $dataFakeProfil, $dataRealProfil, $type, $messageAt, $Conversation, $message, $language, $senderMessage, $receiveMessage);
}
} else { // else conversation
$Conversation = new Conversation($senderMessage, $receiveMessage, $language, $senderMessage->getPlatform());
$this->entityService->saveEntity($Conversation);
$dataRealProfil = $this->profileService->getProfil($Conversation, 'vp');
$dataFakeProfil = $this->profileService->getProfil($Conversation, 'fp');
$typeMess = $this->typeMessageRepository->findOneBy(['name' => 'message']);
$newMessage = new WaitMessage($messageAt, $message, $Conversation, $Conversation->getLanguage(), NULL);
$newMessage->setMessType($typeMess);
$MessHold = [
'id' => $newMessage->getId(),
'sender_profil' => $newMessage->getConv()->getSenderProfil()->getId(),
'receiver_profil' => $newMessage->getConv()->getReceiveProfil()->getId(),
'message_at' => $newMessage->getCreatedAt()->format('Y-m-d H:i:s'),
'content' => $newMessage->getMessage(),
'message_id' => $newMessage->getId(),
'type_profil' => $type->getId(),
'gifs' => [],
'photos' => [],
'type_mess' => $newMessage->getMessType()->getName()
];
$dataRealProfil = $this->profileService->getProfil($Conversation, 'vp');
$dataFakeProfil = $this->profileService->getProfil($Conversation, 'fp');
$this->pusherService->triggerEvent('private-message', "add", $MessHold);
$this->entityService->saveEntity($newMessage);
$data2 = $this->messageOnHoldService->createContent(false, $messageAt, $message, $Conversation, $newMessage->getId(), false, NULL, $type, NULL, NULL);
$wait_id[] = $newMessage->getId();
$this->receiveMessageService->findUser($data2, $newMessage, $wait_id, $dataFakeProfil, $dataRealProfil, $type, $messageAt, $Conversation, $message, $language, $senderMessage, $receiveMessage);
// changement de statistic new design
$statisticNew = [
"name" => "trafic",
"language" => $Conversation->getLanguage()->getName(),
"platform" => $Conversation->getPlatform()->getName(),
"field" => "notAllocated",
"value" => 1
];
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($Conversation->getLanguage()->getName());
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticNew);
}
}
// changement de statistic new design
$statistic2 = [
"name" => "conversations",
"language" => $languageName,
"platform" => $realProfil->getPlatform()->getName(),
"field" => "onHold",
"value" => 1
];
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($languageName);
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statistic2);
}
return $this->json(['success' => true], Response::HTTP_OK);
}
return $this->json(['message' => 'Service indisponible'], Response::HTTP_SERVICE_UNAVAILABLE);
}
/**
*
* API envoi message du vrai profil au faux profil
*
*/
#[Route('/send_message_fp_to_vp', name: 'send_message_fp_to_vp', methods: ['POST'])]
public function sendMessageFpToVp(ProfilRepository $profilRepository)
{
$user = $this->getUser();
if (!$user) return $this->json(['message' => "Vous n'êtes pas connécté"], Response::HTTP_METHOD_NOT_ALLOWED);
$role = $user->getRoles()[0];
if ($role != self::OPERATOR) {
return $this->json(['message' => "Vous n'êtes pas autorisé à accéder à cet API"], Response::HTTP_NETWORK_AUTHENTICATION_REQUIRED);
}
$this->pusherService->createPusher();
// $message = $this->messageRepository->findOneBy(['id' => $messId]);
$type_real = $this->profilTypeRepository->findOneBy(['name' => 'real_profil']);
$type_fake = $this->profilTypeRepository->findOneBy(['name' => 'fake_profil']);
[$content] = $this->requestService->getFromDataRequestBody('message_content');
[$answers] = $this->requestService->getFromDataRequestBody('status');
[$waitStr] = $this->requestService->getFromDataRequestBody('wait_id');
[$convId] = $this->requestService->getFromDataRequestBody('convId');
[$photo_id] = $this->requestService->getFromRequestBody('photo_id');
[$gif_id] = $this->requestService->getFromRequestBody('gif_id');
[$nbrWait] = $this->requestService->getFromDataRequestBody('nbrWait');
[$type_mess] = $this->requestService->getFromDataRequestBody('type_mess');
if ($waitStr) {
$string = trim($waitStr, "[]");
$array = explode(",", $string);
$wait_id = array_map('intval', $array);
}
$contentMessage = $content;
$conv = $this->conversationRepository->findOneBy(['id' => $convId]);
if ($answers == 'true') {
$data = [];
$this->logger->info('answer true');
if (!$user->isAnswer()) {
$user->setAnswer(true);
$this->entityManagerInterface->persist($user);
}
$messageAt = new DateTimeImmutable();
$images = NULL;
if ($photo_id) {
$images = [];
foreach ($photo_id as $image_id) {
$image = $this->photoRepository->findOneBy(['id' => $image_id]);
if($image->getTypePhoto() == 'photo'){
$image->setDeleted(true);
}
$this->entityManagerInterface->persist($image);
$this->entityManagerInterface->flush();
$images[] = $image;
}
}
$gifs = NULL;
if ($gif_id) {
$gifs = [];
foreach ($gif_id as $gifs_id) {
$gif = $this->gifRepository->find($gifs_id);
$gifs[] = $gif;
}
}
if ($type_mess == 'poke' || $type_mess == 'stop' || $type_mess == 'teaser') {
$wait = $this->waitMessageRepository->findOneBy(['id' => $wait_id[0]]);
$idWait = $wait->getId();
$waitMessage = new Message($user, $conv, $wait->getMessage(), $type_real, $wait->getMessType(), $wait->getCreatedAt(), NULL, NULL);
$newMessage = new Message($user, $conv, $contentMessage, $type_fake, $wait->getMessType(), $messageAt, $gifs, $images);
$this->entityService->saveEntity($waitMessage);
$this->entityService->saveEntity($newMessage);
$waitMessage->setResponseMess($newMessage);
$this->entityService->saveEntity($waitMessage);
$this->entityManagerInterface->remove($wait);
$this->entityManagerInterface->flush();
$data[] = $this->messageOnHoldService->createContent(false, $newMessage->getMessageAt(), $newMessage->getContent(), $newMessage->getConversation(), $newMessage->getId(), $newMessage->isEtat(), $newMessage->getOperator()->getName(), $newMessage->getType(), $newMessage->serializeGifs(), $newMessage->serializePhotos());
$user->setStatus('free');
$user->setConv(NULL);
$this->entityManagerInterface->persist($user);
$this->entityService->saveEntity($newMessage);
$dataPush = [
'id' => $idWait,
'vprofil' => $waitMessage->getConversation()->getSenderProfil()->getUsername(),
'fprofil' => $waitMessage->getConversation()->getReceiveProfil()->getUsername(),
'date' => $waitMessage->getMessageAt()->format('Y-m-d H:i:s'),
'response' => $newMessage->getContent(),
'réresponse' => 'pas encore.'
];
$this->pusherService->triggerEvent('private-'.$type_mess , "add", $dataPush);
// changement de statistic new design
$statisticNew = [
"name" => $type_mess == 'stop' ? $type_mess : $type_mess . "s",
"language" => $conv->getLanguage()->getName(),
"platform" => $conv->getPlatform()->getName(),
"field" => "sent",
"value" => 1
];
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($user->getLanguage()->getName());
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticNew);
}
}
else {
foreach ($wait_id as $msg_id) {
$wait = $this->waitMessageRepository->findOneBy(['id' => $msg_id]);
$newMessage = new Message($user, $conv, $wait->getMessage(), $type_real, $wait->getMessType(), $wait->getCreatedAt(), NULL, NULL);
$newMessage->setEtat($wait->isEtatMsg());
$this->entityManagerInterface->persist($newMessage);
$this->entityManagerInterface->flush();
$data[] = $this->messageOnHoldService->createContent(false, $newMessage->getMessageAt(), $newMessage->getContent(), $newMessage->getConversation(), $newMessage->getId(), $newMessage->isEtat(), $newMessage->getOperator()->getName(), $newMessage->getType(), $newMessage->serializeGifs(), $newMessage->serializePhotos());
$profilInfo = $this->messageOnHoldService->getProfilInfo($newMessage);
$data[count($data) - 1]['receiver_profil'] = $profilInfo['receive'];
$data[count($data) - 1]['sender_profil'] = $profilInfo['sender'];
$data[count($data) - 1]['wait_id'] = $msg_id;
}
$newMessage = new Message($user, $conv, $contentMessage, $type_fake, $wait->getMessType(), $messageAt, $gifs, $images);
if($wait->getResponseWait()){
$last = $this->messageRepository->findOneBy([ 'id' => $wait->getResponseWait()->getId()]);
$new = $this->messageRepository->findOneBy([ 'id' => $data[0]['message_id']]);
$last->setResponseMess($new);
$this->entityManagerInterface->persist($last);
$this->entityManagerInterface->flush();
}
foreach ($wait_id as $msg_id) {
$wait = $this->waitMessageRepository->findOneBy(['id' => $msg_id]);
$wait->setResponseWait(null);
$this->entityManagerInterface->remove($wait);
$this->entityManagerInterface->flush();
}
$user->setStatus('free');
$user->setConv(NULL);
$this->entityManagerInterface->persist($user);
$this->entityService->saveEntity($newMessage);
$this->messageOnHoldService->sendMsgListQC($newMessage);
}
$contents = $this->messageOnHoldService->createContent(false, $newMessage->getMessageAt(), $newMessage->getContent(), $newMessage->getConversation(), $newMessage->getId(), $newMessage->isEtat(), $newMessage->getOperator()->getName(), $newMessage->getType(), $newMessage->serializeGifs(), $newMessage->serializePhotos());
$profilInfo = $this->messageOnHoldService->getProfilInfo($newMessage);
$contents['receiver_profil'] = $profilInfo['receive'];
$contents['sender_profil'] = $profilInfo['sender'];
$data[] = $contents;
$this->pusherService->createPusher();
$MessHold = [
'id' => $newMessage->getId(),
'sender_profil' => $newMessage->getConversation()->getSenderProfil()->getId(),
'receiver_profil' => $newMessage->getConversation()->getReceiveProfil()->getId(),
'message_at' => $newMessage->getMessageAt()->format('Y-m-d H:i:s'),
'content' => $newMessage->getContent(),
'message_id' => $newMessage->getId(),
'type_profil' => $newMessage->getType()->getId(),
'gifs' => $newMessage->serializeGifs(),
'photos' => $newMessage->serializePhotos(),
'type_mess' => $type_mess,
];
$this->pusherService->triggerEvent('private-conversation', 'add-treated', $data);
$this->pusherService->triggerEvent('private-conversation', 'status', [
'id' => $user->getId(),
'status' => $user->getStatus()
]);
$MessHold1 = [
'id' => $newMessage->getId(),
'sender_profil' => $newMessage->getConversation()->getSenderProfil()->getId(),
'receiver_profil' => $newMessage->getConversation()->getReceiveProfil()->getId(),
'message_at' => $newMessage->getMessageAt()->format('Y-m-d H:i:s'),
'content' => $newMessage->getContent(),
'message_id' => $newMessage->getId(),
'type_profil' => $newMessage->getType()->getId(),
'gifs' => $newMessage->serializeGifs(),
'photos' => $newMessage->serializePhotos(),
'type_mess' => $type_mess
];
$this->pusherService->triggerEvent('private-message', "add", $MessHold1);
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($user->getLanguage()->getName());
$countHold = count($data) - 1;
// changement de statistic new design
$statisticNew = [
"name" => "conversations",
"language" => $conv->getLanguage()->getName(),
"platform" => $conv->getPlatform()->getName(),
"field" => "treated",
"value" => count($data)
];
$statistic = [
"name" => "conversation",
"field" => "treated",
"value" => count($data)
];
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticNew);
$this->pusherService->triggerEvent('private-statistic', strval($userReal->getId()), $statistic);
}
// changement de statistic new design
$language = $conv->getLanguage();
$platform = $conv->getPlatform();
$now = new \DateTimeImmutable();
$period = $now->format("Y-m");
$rate = $this->rateRepository->findOneBy([ 'platform' => $platform, 'language' => $language, 'period' => $period]);
if($type_mess == 'poke'){
$price = $rate->getPokeMessage();
}elseif($type_mess == 'stop'){
$price = $rate->getStopMessage();
}elseif($type_mess == 'teaser'){
$price = $rate->getTeaserMessage();
}else{
$price = $rate->getMessage();
}
$statisticAccountant = [
"name" => "accountant",
"language" => $language->getName(),
"platform" => $platform->getName(),
"field" => $user->getPayment()->getName(),
"value" => $price
];
$statisticAccountantTotal = [
"name" => "accountant",
"language" => $language->getName(),
"platform" => $platform->getName(),
"field" => 'total',
"value" => $price
];
$statisticAlreAll = [
"name" => "trafic",
"language" => $language->getName(),
"platform" => $platform->getName(),
"field" => "alreadyAllocated",
"value" => -$countHold
];
$statisticQcTotal = [
"name" => "qc",
"language" => $language->getName(),
"platform" => $platform->getName(),
"field" => "qcTotal",
"value" => 1
];
$statisticQcNot = [
"name" => "qc",
"language" => $language->getName(),
"platform" => $platform->getName(),
"field" => "notPassedQc",
"value" => 1
];
$statisticNew1 = [
"name" => "conversations",
"language" => $language->getName(),
"platform" => $platform->getName(),
"field" => "onHold",
"value" => -$countHold
];
$statistic1 = [
"name" => "conversation",
"field" => "onHold",
"value" => -$countHold
];
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticAccountantTotal);
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticAccountant);
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticNew1);
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticQcTotal);
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticQcNot);
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticAlreAll);
$this->pusherService->triggerEvent('private-statistic', strval($userReal->getId()), $statistic1);
}
$users = $this->userRepository->findBy(['status' => 'occuped']);
foreach ($users as $user) {
$this->pusherService->triggerEvent('private-' . strval($user->getId()), 'countOnHoldEvent', [
'count' => -1,
]);
}
return $this->json(['message' => 'Message envoyé avec succés', $answers], Response::HTTP_OK);
} else {
$this->logger->info('answer false');
return $this->sendMessageService->getMessageService($nbrWait, $conv, $wait_id, $user, $type_mess);
}
}
/**
*
** API message en attente
*
*/
#[Route('/message_on_hold', name: 'message_on_hold', methods: ['GET'])]
public function findMessageOnHold()
{
$user = $this->getUser();
if (!$user) return $this->json(['message' => "Vous n'êtes pas connécté"], Response::HTTP_METHOD_NOT_ALLOWED);
$role = $user->getRoles()[0];
if ($role != self::OPERATOR) {
return $this->json(['message' => "Vous n'êtes pas autorisé à accéder à cet API"], Response::HTTP_NETWORK_AUTHENTICATION_REQUIRED);
}
$this->pusherService->createPusher();
return $this->messageOnHoldService->findMessageOnHold($user);
}
/**
*
* API pour la deconnexion d'un opérateur
*
*/
#[Route('/disconnection/{id}', name: 'deconnection', methods: ['POST'])]
public function disconnection()
{
// dd("test");
[$id] = $this->requestService->getFromAttributes('id');
$user = $this->userRepository->findOneBy(['id' => $id]);
$user->setStatus('disconnect');
$this->entityService->saveEntity($user);
// changement de statistic new design
$languageName = $user->getLanguage()->getName();
$statistic2 = [
"name" => "agents",
"language" => $languageName,
"field" => "online",
"value" => -1
];
// statistic
$statistic = [
"name" => "operator",
"field" => "online",
"value" => -1
];
$this->pusherService->createPusher();
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($languageName);
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statistic2);
$this->pusherService->triggerEvent('private-statistic', strval($userReal->getId()), $statistic);
}
return $this->json(['message' => 'Vous êtes déconnectez avec succés'], Response::HTTP_OK);
}
private function getMessageComps($senderId, $receiverId, $operatorId, $conversationId)
{
// Récupération du sender (faux profil)
$sender = $this->profilRepository->find($senderId);
if (!$sender) return ['error' => 'Faux profil non trouvé'];
// Récupération du receiver (vrai profil)
$receiver = $this->profilRepository->find($receiverId);
if (!$receiver) return ['error' => 'Vrai profil non trouvé'];
// Récupération de l'opérateur
$operator = $this->userRepository->find($operatorId);
if (!$operator) return ['error' => 'Opérateur non trouvé'];
// Récupération de la conversation
$conversation = $this->conversationRepository->find($conversationId);
if (!$conversation) return ['error' => 'Conversation non trouvée'];
return ['data' => [$sender, $receiver, $operator, $conversation]];
}
/**
* API pour envoi message
*/
#[Route('/send_photo', name: 'send_photo', methods: ['POST'])]
public function sendPhoto()
{
// Autorisation
$user = $this->getUser();
if (!$user) return $this->json(["message" => "Vous n'êtes pas connecté"], 401);
// Récupération des données dans le request body
[$fp_id, $vp_id, $conv_id, $images_ids, $site_id] = $this->requestService->getFromRequestBody('fp_id', 'vp_id', 'conversation_id', 'images_ids', 'site_id');
// Récupération des éléments à partir de leurs id respectifs
$messageComps = $this->getMessageComps($fp_id, $vp_id, $user->getId(), $conv_id);
if (isset($messageComps['error'])) return $this->json(['message' => $messageComps['error']], 404);
[$sender, $receiver, $operator, $conversation] = $messageComps['data'];
// Récupération des images
$images = [];
if ($images_ids) foreach ($images_ids as $image_id) {
$image = $this->photoRequestRepository->find($image_id);
if (!$image) return $this->json(['message' => 'Image ' . $image_id . ' non trouvé'], 404);
if (!$image->getPhotoName()) return $this->json(['message' => 'Image ' . $image_id . ' non trouvé'], 404);
$image->setDeleted(true);
$this->entityManagerInterface->persist($image);
$this->entityManagerInterface->flush();
$images[] = $image;
}
// Ajout et stockage du message
$type = $this->profilTypeRepository->findOneBy(["name" => 'fake_profil']);
$typeMessType = $this->typeMessageRepository->findOneBy(['name' => 'message']);
$messageAt = new DateTimeImmutable();
$message = new Message($operator, $conversation, null, $type, $typeMessType, $messageAt, null, $images);
$this->entityManagerInterface->persist($message);
$this->entityManagerInterface->flush();
// Récupération du site
$platform = 'test'; //FIXME $this->platformRepository->find($site_id);
if (!$platform) return $this->json(['message' => 'Site non trouvée'], 404);
// TODO Envoi du message dans le site
// Libérer l'opérateur
$operator->setStatus("free");
$photos = [];
for ($i = 0; $i < count($images); $i++) {
$photos[$i] = [
'id' => $images[$i]->getId(),
'photoName' => $images[$i]->getPhotoName()
];
}
$data = [
"sender_profil" => $message->getConversation()->getSenderProfil()->getRealName(),
"receiver_profil" => $message->getConversation()->getReceiveProfil()->getRealName(),
"message_at" => $message->getMessageAt()->format('Y-m-d H:i:s'),
"content" => $message->getContent(),
"message_id" => $message->getId(),
"type_profil" => $message->getType()->getId(),
'photos' => $photos,
'gifs' => []
];
return $this->json(['message' => 'Photo envoyée', "data" => $data], 201);
}
/**
* API pour envoyer un gif: faux profil -> vrai profil
*
*/
#[Route('/send_gif', name: 'send_gif', methods: ['POST'])]
public function sendGif()
{
// Récupération des données dans le request body
[$fp_id, $vp_id, $conv_id, $gifs_ids, $site_id] = $this->requestService->getFromRequestBody('fp_id', 'vp_id', 'conversation_id', 'gifs_ids', 'site_id');
$user = $this->getUser();
if (!$user) return $this->json(["message" => "Vous n'êtes pas connecté"], 401);
// Récupération des éléments à partir de leurs id respectifs
$messageComps = $this->getMessageComps($fp_id, $vp_id, $user->getId(), $conv_id);
if (isset($messageComps['error'])) return $this->json(['message' => $messageComps['error']], 404);
[$sender, $receiver, $operator, $conversation] = $messageComps['data'];
// Récupération des gifs
$gifs = [];
if ($gifs_ids) foreach ($gifs_ids as $gif_id) {
$gif = $this->gifRepository->find($gif_id);
if (!$gif) return $this->json(['message' => 'Gif ' . $gif_id . ' non trouvé'], 404);
$gifs[] = $gif;
}
// Ajout et stockage du message
$type = $this->profilTypeRepository->findOneBy(["name" => 'fake_profil']);
$typeMessType = $this->typeMessageRepository->findOneBy(['name' => 'message']);
$messageAt = new DateTimeImmutable();
$message = new Message($operator, $conversation, null, $type, $typeMessType, $messageAt, $gifs, null);
$this->entityManagerInterface->persist($message);
$this->entityManagerInterface->flush();
// Récupération du site
$platform = 'test'; //FIXME $this->platformRepository->find($site_id);
if (!$platform) return $this->json(['message' => 'Site non trouvée'], 404);
// TODO Envoi du message dans le site
// Libérer l'opérateur
$operator->setStatus("free");
$gifToSend = [];
for ($i = 0; $i < count($gifs); $i++) {
$gifToSend[$i] = [
'id' => $gifs[$i]->getId(),
'photoName' => $gifs[$i]->getName()
];
}
$data = [
"sender_profil" => $message->getConversation()->getSenderProfil()->getRealName(),
"receiver_profil" => $message->getConversation()->getReceiveProfil()->getUsername(),
"message_at" => $message->getMessageAt()->format('Y-m-d H:i:s'),
"content" => $message->getContent(),
"message_id" => $message->getId(),
"type_profil" => $message->getType()->getId(),
'photos' => [],
'gifs' => $gifToSend
];
return $this->json(['message' => 'Message gif envoyé', "data" => $data], 201);
}
#[Route('/readconversation/{convId}', name: 'read_conversation', methods: ['GET'])]
public function readConversation($convId)
{
$conversation = $this->conversationRepository->findOneBy(['id' => $convId]);
if (!$conversation) {
return $this->json(['message' => 'Conversation non trouvée'], Response::HTTP_NOT_FOUND);
}
$messages = $conversation->getMessages();
$messageData = [];
foreach ($messages as $message) {
$senderProfil = $message->getConversation()->getSenderProfil()->getRealName();
$typeProfil = $message->getConversation()->getSenderProfil()->getProfilType()->getId();
$receiveProfil = $message->getConversation()->getReceiveProfil()->getRealName();
$messageAt = $message->getMessageAt();
$content = $message->getContent();
$messageId = $message->getId();
$messageData[] = [
'sender_profil' => $senderProfil,
'receiver_profil' => $receiveProfil,
'message_at' => $messageAt,
'content' => $content,
'message_id' => $messageId,
'type_profil' => $typeProfil,
];
}
return $this->json($messageData, Response::HTTP_OK);
}
#[Route('/conversation/treated', name: 'get_treated_conversation', methods: ['GET'])]
public function getTreatedConversation(Request $request)
{
//Autorisation
$user = $this->getUser();
if (!$user) {
return $this->json("Vous n'êtes pas connecté ", 401);
}
$decodedJwtToken = $this->jwtTokenManager->decode($this->tokenStorageInterface->getToken());
if ($decodedJwtToken['roles'][0] !== self::ADMIN && $decodedJwtToken['roles'][0] !== self::SUPERVISOR && $decodedJwtToken['roles'][0] !== self::QC) return $this->json(['message' => 'Accès refusé'], 403);
$year = $request->query->get('year', date('Y'));
$month = $request->query->get('month', date('m'));
$date = $request->query->get('date', '');
$startingDate = $request->query->get('startingDate', '');
$closingDate = $request->query->get('closingDate', '');
$platforms = $request->query->get('platforms', '');
$agents = $request->query->get('agents', '');
$fakeProfil = $request->query->get('fakeProfil', '');
$conversation = $request->query->get('conversation', '');
$message = $request->query->get('message', '');
$language = $request->query->get('language', '');
$typeMS = $request->query->get('type', '');
$typeMS = intval($typeMS);
$messages = $this->messageRepository->filterConversation(
$year,
$month,
$conversation,
$message,
$fakeProfil,
$startingDate,
$date,
$closingDate,
$platforms,
$agents,
$language,
$user,
$typeMS
);
$paginations = $this->paginator->getPagination($request, $messages, 20);
$messageData = [];
foreach ($paginations->getItems() as $message) {
$messageAt = $message->getMessageAt();
$conv = $message->getConversation();
$profilInfoData = $this->messageOnHoldService->getProfilInfo($message);
$senderProfil = $profilInfoData['sender'];
$receiveProfil = $profilInfoData['receive'];
$messageId = $message->getId();
$content = $message->getContent();
$operator = $message->getOperator()->getName();
$operator_log = $message->getOperator()->getMail();
$language = $this->languageRepository->findOneById(['id' => $conv->getLanguage()->getId()])->getName();
$platform = $conv->getSenderProfil()->getPlatform()->getName();
$qc_ctr = [];
$validation = false;
$getQcCtr = $message->getQcControl();
$type_mess = $message->getMessType() ? $message->getMessType()->getName() : null;
if ($getQcCtr) {
$qc_ctr = $getQcCtr;
$validation = true;
}
$messageData[] = [
'message_at' => $messageAt,
'conv_id' => $conv->getId(),
'message_id' => $messageId,
'sender_profil' => $senderProfil,
'receiver_profil' => $receiveProfil,
'gifs' => $message->serializeGifs(),
'photos' => $message->serializePhotos(),
'content' => $content,
'operator' => $operator,
'language' => $language,
'platform' => $platform,
'ag_log' => $operator_log,
'qc_control' => $qc_ctr,
'qc_result' => $message->getQcResult(),
'type_mess' => $type_mess,
'validation' => $validation,
'type' => $profilInfoData['type']
];
}
return $this->json([
'data' => $messageData,
'pagination' => [
'page' => $paginations->getCurrentPageNumber(),
'total_pages' => ceil($paginations->getTotalItemCount() / $paginations->getItemNumberPerPage()),
'total_items' => $paginations->getTotalItemCount(),
]
], Response::HTTP_OK);
}
#[Route('/user/{roleName}', name: 'user_by_role', methods: ['GET'])]
public function getUserByRole(SerializerInterface $serializer, $roleName, Request $request)
{
$user = $this->getUser();
if (!$user) {
return $this->json("Vous n'êtes pas connecté ", 401);
}
$year = $request->query->get('year', "");
$month = $request->query->get('month', "");
$date = $request->query->get('date', '');
$startingDate = $request->query->get('startingDate', '');
$closingDate = $request->query->get('closingDate', '');
$agents = $request->query->get('agents', '');
$language = $request->query->get('language', '');
$platforms = $request->query->get('platforms', '');
$roleToken = $user->getRoles()[0];
$supervisor = $this->roleRepository->findOneBy(['name' => 'supervisor']);
$operator = $this->roleRepository->findOneBy(['name' => 'operator']);
$locale = $user->getLanguage();
if ($roleName == self::OPERATOR && $roleToken == self::SUPERVISOR) {
$users = $this->userRepository->findUsersByRoleAndStatus($operator, $year, $locale, $month, $date, $startingDate, $closingDate, $agents);
$paginations = $this->paginator->getPagination($request, $users, 5);
} elseif ($roleName == self::OPERATOR && $roleToken == self::ADMIN) {
$users = $this->userRepository->findUsers($operator, $year, $month, $date, $startingDate, $closingDate, $agents, $language, $platforms);
$paginations = $this->paginator->getPagination($request, $users, 5);
} elseif ($roleName == self::SUPERVISOR && $roleToken == self::ADMIN) {
$users = $this->userRepository->findUsers($supervisor, $year, $month, $date, $startingDate, $closingDate, $agents, $language, $platforms);
$paginations = $this->paginator->getPagination($request, $users, 5);
} elseif ($roleName == self::QC && $roleToken == self::ADMIN) {
$QC = $this->roleRepository->findOneBy(['name' => self::QC]);
$users = $this->userRepository->findUsers($QC, $year, $month, $date, $startingDate, $closingDate, $agents, $language, $platforms);
$paginations = $this->paginator->getPagination($request, $users, 5);
} elseif ($roleName == self::ACCOUNTANT && $roleToken == self::ADMIN) {
$comptable = $this->roleRepository->findOneBy(['name' => self::ACCOUNTANT]);
$users = $this->userRepository->findUsers($comptable, $year, $month, $date, $startingDate, $closingDate, $agents, $language, $platforms);
$paginations = $this->paginator->getPagination($request, $users, 5);
} else {
return $this->json(['message' => "Inaccessible"], Response::HTTP_NOT_ACCEPTABLE);
}
$response = $serializer->serialize($paginations, 'json', ['groups' => ['user', 'language']]);
$responseArray = json_decode($response, true);
return $this->json([
'data' => $responseArray,
'pagination' => [
'page' => $paginations->getCurrentPageNumber(),
'total_pages' => ceil($paginations->getTotalItemCount() / $paginations->getItemNumberPerPage()),
'total_items' => $paginations->getTotalItemCount(),
]
], Response::HTTP_OK);
}
#[Route('/payment/{paymentName}', name: 'user_by_payment', methods: ['GET'])]
public function getUserByPayment(SerializerInterface $serializer, $paymentName)
{
// Autorisation
$user = $this->getUser();
if (!$user) {
return $this->json("Vous n'êtes pas connecté ", 401);
}
$decodedJwtToken = $this->jwtTokenManager->decode($this->tokenStorageInterface->getToken());
if ($decodedJwtToken['roles'][0] !== self::ADMIN && $decodedJwtToken['roles'][0] !== self::ACCOUNTANT) return $this->json(['message' => 'Accès refusé'], 403);
$payment = $this->paymentRepository->findOneBy(['Name' => $paymentName]);
$users = $this->userRepository->findBy(['payment' => $payment, 'deleted' => false]);
$response = $serializer->serialize($users, 'json', ['groups' => ['user', 'language']]);
return $this->json(json_decode($response, true), 200);
}
#[Route('/report', name: 'report', methods: ['POST'])]
public function createReport()
{
$user = $this->getUser();
if (!$user) {
return $this->json("Vous n'êtes pas connecté ", 401);
}
if ($user->getRoles()[0] !== self::OPERATOR) return $this->json(['message' => 'Accès refusé'], 403);
[$id_message, $content, $id_agent] = $this->requestService->getFromRequestBody('id_message', 'content', 'id_agent');
$message = $this->messageRepository->findOneBy(['id' => $id_message]);
$message->setEtat(true);
$this->entityManagerInterface->persist($message);
$this->pusherService->createPusher();
$agent = $this->userRepository->findOneBy(['id' => $id_agent]);
$report = new Report();
$report->setDateReport(new \DateTimeImmutable());
$report->setMessageId($message);
$report->setContent($content);
$report->setAgent($agent);
$report->setStatus(false);
$errors = $this->entityValidatorService->validateEntity($report);
if (count($errors) > 0) {
return $this->json(['errors' => $this->entityValidatorService->getErrorMessages($errors)], Response::HTTP_BAD_REQUEST);
}
$this->entityManagerInterface->persist($report);
$this->entityManagerInterface->flush();
$role = self::SUPERVISOR;
$role_id = $this->roleRepository->findBy(['name' => $role]);
$super = $this->userRepository->findBy(['role' => $role_id, 'status' => 'free']);
$data = [
'role' => 'Agent',
'type' => 'Report1',
'sender' => $role,
'content' => 'New report',
'date' => $report->getDateReport()->format('Y-m-d H:i:s'),
'checked' => false
];
foreach ($super as $superviseur) {
$this->pusherService->triggerEvent('private-' . $superviseur->getId(), 'Add_Notif', $data);
}
// changement de statistic new design
$conv = $report->getMessageId()->getConversation();
$statisticNew = [
"name" => "report",
"language" => $conv->getLanguage()->getName(),
"platform" => $conv->getPlatform()->getName(),
"field" => "new",
"value" => 1
];
$statisticTotal = [
"name" => "report",
"language" => $conv->getLanguage()->getName(),
"platform" => $conv->getPlatform()->getName(),
"field" => "all",
"value" => 1
];
// statistic
$statistic = [
"name" => "Report",
"field" => "total",
"value" => 1
];
$data = $this->notificationController->setNotification('report',null,'',$role,false,$user,$user->getName());
$usersToRealTime = $this->userRepository->findSupervisorsAndAdminsByLanguage($user->getLanguage()->getName());
foreach ($usersToRealTime as $userReal) {
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticNew);
$this->pusherService->triggerEvent('private-statistic', strval($userReal->getId()), $statistic);
$this->pusherService->triggerEvent('private-statistic2', strval($userReal->getId()), $statisticTotal);
}
return $this->json(Response::HTTP_OK);
}
#[Route('/all_report', name: 'all_report', methods: ['GET'])]
public function getAllReport()
{
$user = $this->getUser();
if (!$user) {
return $this->json("Vous n'êtes pas connecté ", 401);
}
if ($user->getRoles()[0] !== self::ADMIN && $user->getRoles()[0] !== self::SUPERVISOR) return $this->json(['message' => 'Accès refusé'], 403);
$reports = $this->reportRepository->findAll();
$reportData = [];
foreach ($reports as $report) {
$reportdate = $report->getDateReport();
$platform = $report->getMessageId()->getConversation()->getSenderProfil()->getPlatform()->getName();
$idreport = $report->getId();
$message = $report->getMessageId()->getContent();
$idmessage = $report->getMessageId()->getId();
$senderProfil = $this->messageOnHoldService->getInformationProfil($report->getMessageId()->getConversation()->getSenderProfil());
$receiveProfil = $report->getMessageId()->getConversation()->getReceiveProfil()->getRealName();
$operator = $report->getMessageId()->getOperator()->getId();
$operator = $this->userRepository->findOneBy(['id' => $operator]);
$reportData[] = [
'reportdate' => $reportdate,
'platform' => $platform,
'id_report' => $idreport,
'message' => $message,
'id_message' => $idmessage,
'sender_profil' => $senderProfil,
'receiver_profil' => $receiveProfil,
'operatorName' => $operator->getName(),
'operatorId' => $operator->getId(),
'agentSign' => $report->getAgent()->getName(),
'content' => $report->getContent(),
'status' => $report->isStatus()
];
}
return $this->json($reportData, Response::HTTP_OK);
}
#[Route('/conversation_on_hold', name: 'get_on_hold_conversation', methods: ['GET'])] //FIXME
public function getConversationOnHold(Request $request)
{
// Autorisation
$user = $this->getUser();
if (!$user) {
return $this->json("Vous n'êtes pas connecté ", 401);
}
$decodedJwtToken = $this->jwtTokenManager->decode($this->tokenStorageInterface->getToken());
if ($decodedJwtToken['roles'][0] !== self::ADMIN && $decodedJwtToken['roles'][0] !== self::SUPERVISOR) return $this->json(['message' => 'Accès refusé'], 403);
$year = $request->query->get('year', date('Y'));
$month = $request->query->get('month', date('m'));
$date = $request->query->get('date', '');
$startingDate = $request->query->get('startingDate', '');
$closingDate = $request->query->get('closingDate', '');
$platforms = $request->query->get('platforms', '');
$fakeProfil = $request->query->get('fakeProfil', '');
$conversation = $request->query->get('conversation', '');
$message = $request->query->get('message', '');
$language = $request->query->get('language', '');
$messages = $this->waitMessageRepository->filterOnhold(
$year,
$month,
$conversation,
$message,
$fakeProfil,
$startingDate,
$date,
$closingDate,
$platforms,
$language,
$user
);
$paginations = $this->paginator->getPagination($request, $messages, 20);
$waitmessageData = [];
foreach ($paginations as $waitmessage) {
$createdAt = $waitmessage->getCreatedAt();
$messageId = $waitmessage->getId();
$convId = $waitmessage->getConv()->getId();
$realProfil = $this->messageOnHoldService->getInformationProfil($waitmessage->getConv()->getSenderProfil());
$fakeProfil = $this->messageOnHoldService->getInformationProfil($waitmessage->getConv()->getReceiveProfil());
$content = $waitmessage->getMessage();
$platform = $waitmessage->getConv()->getSenderProfil()->getPlatform()->getName();
$priority_name = null;
$priority_id = null;
$priority_login = null;
$userPr = $waitmessage->getConv()->getPriority();
if ($userPr) {
$priority_name = $userPr->getName();
$priority_id = $userPr->getId();
$priority_login = $userPr->getMail();
}
$type_mess = '';
if ($waitmessage->getMessType()) $type_mess = $waitmessage->getMessType()->getName();
$waitmessageData[] = [
'id' => $waitmessage->getId(),
'message_at' => $createdAt,
'message_id' => $messageId,
'conv_id' => $convId,
'agent' => $priority_name,
'agent_id' => $priority_id,
'agent_log' => $priority_login,
'sender_profil' => $realProfil,
'receiver_profil' => $fakeProfil,
'content' => $content,
'date' => $waitmessage->getCreatedAt(),
'platform' => $platform,
'language' => $waitmessage->getLanguage()->getName(),
'status' => $waitmessage->isDeleted(),
'opAssign' => '',
'type_mess' => $type_mess
];
}
$operatorList = [];
$opRole = $this->roleRepository->findOneBy(['name' => self::OPERATOR]);
$userL = $this->userRepository->findBy(['role' => $opRole]);
foreach ($userL as $op) {
$operatorList[] = [
'agent' => $op->getName(),
'status' => $op->getStatus(),
'agent_id' => $op->getId(),
'language' => $op->getLanguage()->getName()
];
}
return $this->json([
'data' => $waitmessageData,
'operator' => $operatorList,
'pagination' => [
'page' => $paginations->getCurrentPageNumber(),
'total_pages' => ceil($paginations->getTotalItemCount() / $paginations->getItemNumberPerPage()),
'total_items' => $paginations->getTotalItemCount(),
]
], Response::HTTP_OK);
}
#[Route('/platforms_performance', name: 'get_platforms_performance', methods: ['GET'])]
public function getPlatformsPerformance()
{
// Autorisation
$user = $this->getUser();
if (!$user) {
return $this->json("Vous n'êtes pas connecté ", 401);
}
$decodedJwtToken = $this->jwtTokenManager->decode($this->tokenStorageInterface->getToken());
if ($decodedJwtToken['roles'][0] !== self::ADMIN && $decodedJwtToken['roles'][0] !== self::SUPERVISOR) return $this->json(['message' => 'Accès refusé'], 403);
$profilTypeFake = $this->profilTypeRepository->findOneBy(['name' => 'fake_profil']);
$profilTypeReal = $this->profilTypeRepository->findOneBy(['name' => 'real_profil']);
$platforms = $this->platformRepository->findAll();
$reports = $this->reportRepository->findAll();
$data = [];
foreach ($platforms as $platform) {
$fakeProfils = $this->profilRepository->findBy(['profilType' => $profilTypeFake, 'platform' => $platform]);
$realProfils = $this->profilRepository->findBy(['profilType' => $profilTypeReal, 'platform' => $platform]);
$numberOfFakeProfil = count($fakeProfils);
$plt = $platform->getName();
$numberTotalOfMessageSent = 0;
$numberTotalOfMessageReceived = 0;
$numberTotalOfReport1 = 0;
$numberTotalOfReport2 = 0;
$numberTotalOfReport = 0;
foreach ($fakeProfils as $fakeProfil) {
$messageFakeProfils = $this->conversationRepository->findBy(['sender_profil' => $fakeProfil]);
$report1 = $this->reportRepository->findBy(['message' => $messageFakeProfils]);
$numberOfReport1 = count($report1);
$numberTotalOfReport1 += $numberOfReport1;
$numberOfMessageSent = count($messageFakeProfils);
$numberTotalOfMessageSent += $numberOfMessageSent;
}
foreach ($realProfils as $realProfil) {
$messageRealProfils = $this->conversationRepository->findBy(['sender_profil' => $realProfil]);
$report2 = $this->reportRepository->findBy(['message' => $messageRealProfils]);
$numberOfReport2 = count($report2);
$numberTotalOfReport2 += $numberOfReport2;
$numberOfMessageReceived = count($messageRealProfils);
$numberTotalOfMessageReceived += $numberOfMessageReceived;
}
$numberTotalOfReport = $numberTotalOfReport1 + $numberTotalOfReport2;
$data[] = [
'platform' => $plt,
'numberOfFakeProfil' => $numberOfFakeProfil,
'numberOfMessageSent' => $numberTotalOfMessageSent,
'numberOfMessageReceived' => $numberTotalOfMessageReceived,
'numberOfReport' => $numberTotalOfReport,
];
}
return $this->json($data, Response::HTTP_OK);
}
#[Route('/allplatform', name: 'platform', methods: ['GET'])]
public function getAllPlatform(PlatformRepository $platformRepository, SerializerInterface $serializer)
{
// Autorisation
// $user = $this->getUser();
// if (!$user) {
// return $this->json("Vous n'êtes pas connecté ", 401);
// }
// $decodedJwtToken = $this->jwtTokenManager->decode($this->tokenStorageInterface->getToken());
// if ($decodedJwtToken['roles'][0] !== self::ADMIN ) return $this->json(['message' => 'Accès refusé'], 403);
$platforms = $platformRepository->findAll();
// foreach($platforms as $platform){
// $datas[] = [
// "value" => $platform->getId(),
// "innerHTML" => $platform->getName(),
// ];
// }
// return $this->json($datas);
$response = $serializer->serialize($platforms, 'json', ['groups' => ['platform']]);
return $this->json(json_decode($response, true), 200);
}
/**
* API pour avoir tous les faux profil et vrai profil
*
*/
#[Route('/profil', name: 'get_profil', methods: ['GET'])]
public function getProfil()
{
// Recherche type de profil
$realProfil = $this->profilTypeRepository->findOneBy(['name' => 'real_profil']);
$fakeProfil = $this->profilTypeRepository->findOneBy(['name' => 'fake_profil']);
// Rescherche des faux et vrai profil
$ProfilsReal = $this->profilRepository->findBy(['profilType' => $realProfil]);
$ProfilFake = $this->profilRepository->findBy(['profilType' => $fakeProfil]);
//Serialisation des Real profil
$RealList = [];
foreach ($ProfilsReal as $l) {
$RealList[] = [
'id' => $l->getId(),
'name' => $l->getUsername(),
'language' => $l->getLanguage()->getName(),
'age' => $l->getAge(),
'sex' => $l->getSex(),
'status' => $l->getMaritalStatus(),
'search' => $l->getResearch(),
'country' => $l->getCountry(),
'city' => $l->getCity(),
'oriatation' => $l->getSexualOrientation(),
'desc' => $l->getDescription(),
'suspendu' => $l->getSuspend(),
'bani' => $l->getKickOff(),
];
}
//Serialisation des Fake profil
$FakeList = [];
foreach ($ProfilFake as $l) {
$FakeList[] = [
'id' => $l->getId(),
'name' => $l->getUsername(),
'language' => $l->getLanguage()->getName(),
'age' => $l->getAge(),
'sex' => $l->getSex(),
'status' => $l->getMaritalStatus(),
'search' => $l->getResearch(),
'country' => $l->getCountry(),
'city' => $l->getCity(),
'oriatation' => $l->getSexualOrientation(),
'desc' => $l->getDescription(),
'suspendu' => $l->getSuspend(),
'bani' => $l->getKickOff(),
];
}
// Serialisation du reponse
$data = [
"realProfil" => $RealList,
"fakeProfil" => $FakeList,
];
return $this->json($data, Response::HTTP_OK);
}
#[Route('/agents_performance', name: 'get_agents_performance', methods: ['GET'])]
public function getAgentsPerformance(SerializerInterface $serializer)
{
// Autorisation
$user = $this->getUser();
if (!$user) {
return $this->json("Vous n'êtes pas connecté ", 401);
}
$decodedJwtToken = $this->jwtTokenManager->decode($this->tokenStorageInterface->getToken());
if ($decodedJwtToken['roles'][0] !== self::ADMIN && $decodedJwtToken['roles'][0] !== self::SUPERVISOR) return $this->json(['message' => 'Accès refusé'], 403);
$role = $this->roleRepository->findOneBy(['name' => 'operator']);
$users = $this->userRepository->findBy(['role' => $role]);
$data = [];
foreach ($users as $user) {
$name = $user->getName();
$mail = $user->getMail();
$language = $user->getLanguage()->getName();
$messages = $this->messageRepository->findBy(['operator' => $users]);
$sentMessage = 0;
$receivedMessage = 0;
foreach ($messages as $message) {
$type = $message->getConversation()->getSenderProfil()->getProfilType();
if ($type == "fake_profil") {
$sentMessage++;
} else {
$receivedMessage++;
}
}
$data[] = [
'name' => $name,
'mail' => $mail,
'language' => $language,
'sentMessage' => $sentMessage,
'receivedMessage' => $receivedMessage,
];
}
return $this->json($data, Response::HTTP_OK);
}
#[Route('/supervisor/{id}', name: 'update_password', methods: ['PUT'])]
public function editPasswordSupervisor(Request $request)
{
$user = $this->getUser();
if (!$user) return $this->json(['message' => "Vous n'êtes pas connécté"], Response::HTTP_NOT_FOUND);
if (!($user->getRoles()[0] == self::ADMIN)) {
return $this->json(['message' => "Vous n'êtes pas autorisé à accéder à cet API"], Response::HTTP_UNAUTHORIZED);
}
[$id] = $this->requestService->getFromAttributes('id');
[$newPassword] = $this->requestService->getFromDataRequestBody('newPassword');
if (!$newPassword) return $this->json(['message' => 'Le mot de passe ne peut pas être vide'], Response::HTTP_NOT_ACCEPTABLE);
$role = $this->roleRepository->findOneBy(['name' => self::SUPERVISOR]);
$supervisor = $this->userRepository->findOneBy(['id' => $id, 'role' => $role]);
$hashedPassword = $this->userPasswordHasherInterface->hashPassword($supervisor, $newPassword);
$supervisor->setPassword($hashedPassword);
$this->entityService->saveEntity($supervisor);
return $this->json(['message' => 'Mot de passe modifié avec succés'], Response::HTTP_OK);
}
/**
* API pour suppression d'un superviseur
*
*/
#[Route('/supervisor_delete/{id}', name: 'delete_password', methods: ['DELETE'])]
public function deletePasswordSupervisor()
{
$user = $this->getUser();
if (!$user) return $this->json(['message' => "Vous n'êtes pas connécté"], Response::HTTP_NOT_FOUND);
if (!($user->getRoles()[0] == self::ADMIN)) {
return $this->json(['message' => "Vous n'êtes pas autorisé à accéder à cet API"], Response::HTTP_UNAUTHORIZED);
}
[$id] = $this->requestService->getFromAttributes('id');
$role = $this->roleRepository->findOneBy(['name' => self::SUPERVISOR]);
$supervisor = $this->userRepository->findOneBy(['id' => $id, 'role' => $role]);
$supervisor->setDeleted(true);
$this->entityService->saveEntity($supervisor);
return $this->json(['message' => 'Superviseur supprimé avec succés'], Response::HTTP_OK);
}
/**
* API Edit Opérateur
*
*/
#[Route('/operator/{id}', name: 'update_operator', methods: ['PUT'])]
public function editPasswordOperator()
{
$user = $this->getUser();
if (!$user) return $this->json(['message' => "Vous n'êtes pas connécté"], Response::HTTP_NOT_FOUND);
if (!($user->getRoles()[0] == self::ADMIN || $user->getRoles()[0] == self::SUPERVISOR)) {
return $this->json(['message' => "Vous n'êtes pas autorisé à accéder à cet API"], Response::HTTP_UNAUTHORIZED);
}
[$id] = $this->requestService->getFromAttributes('id');
[$newPassword] = $this->requestService->getFromDataRequestBody('newPassword');
if (!$newPassword) return $this->json(['message' => 'Le mot de passe ne peut pas être vide'], Response::HTTP_NOT_ACCEPTABLE);
$role = $this->roleRepository->findOneBy(['name' => 'operator']);
$operator = $this->userRepository->findOneBy(['id' => $id, 'role' => $role]);
$hashedPassword = $this->userPasswordHasherInterface->hashPassword($operator, $newPassword);
$operator->setPassword($hashedPassword);
$this->entityService->saveEntity($operator);
return $this->json(['message' => 'Mot de passe modifié avec succés'], Response::HTTP_OK);
}
/**
* API pour suspendre un opérateur
*/
#[Route('/operator/suspend', name: 'suspend_operator', methods: ['POST'])]
public function suspendOperator()
{
$user = $this->getUser();
if (!$user) return $this->json(['message' => "Vous n'êtes pas connécté"], Response::HTTP_NOT_FOUND);
if (!($user->getRoles()[0] == self::ADMIN || $user->getRoles()[0] == self::SUPERVISOR)) {
return $this->json(['message' => "Vous n'êtes pas autorisé à accéder à cet API"], Response::HTTP_UNAUTHORIZED);
}
[$id] = $this->requestService->getFromDataRequestBody('id');
$role = $this->roleRepository->findOneBy(['name' => 'operator']);
$operator = $this->userRepository->findOneBy(['id' => $id, 'role' => $role]);
$currentDate = new \DateTimeImmutable();
$newDate = $currentDate->add(new \DateInterval('P7D'));
// Convertir la chaîne de caractères en un objet DateTimeImmutable
$newSuspendDate = \DateTimeImmutable::createFromFormat('Y-m-d', $newDate->format('Y-m-d'));
$operator->setSuspend($newSuspendDate);
$this->entityService->saveEntity($operator);
return $this->json(['message' => 'Operateur suspendu avec succés'], Response::HTTP_OK);
}
/**
* API pour suppression d'un superviseur
*
*/
#[Route('/kickOff_operator/{id}', name: 'kick_off_operator', methods: ['DELETE'])]
public function kickOffOperator()
{
$user = $this->getUser();
if (!$user) return $this->json(['message' => "Vous n'êtes pas connécté"], Response::HTTP_NOT_FOUND);
if (!($user->getRoles()[0] == self::ADMIN || $user->getRoles()[0] == self::SUPERVISOR)) {
return $this->json(['message' => "Vous n'êtes pas autorisé à accéder à cet API"], Response::HTTP_UNAUTHORIZED);
}
[$id] = $this->requestService->getFromAttributes('id');
$role = $this->roleRepository->findOneBy(['name' => "operator"]);
$operator = $this->userRepository->findOneBy(['id' => $id, 'role' => $role]);
$operator->setDeleted(true);
$this->entityService->saveEntity($operator);
return $this->json(['message' => 'Opérateur renvoyer avec succés'], Response::HTTP_OK);
}
#[Route('/agent_statistics', name: 'get_agent_statistics', methods: ['GET'])]
public function getAgentStatistics(SerializerInterface $serializer)
{
// Autorisation
$user = $this->getUser();
if (!$user) {
return $this->json("Vous n'êtes pas connecté ", 401);
}
$decodedJwtToken = $this->jwtTokenManager->decode($this->tokenStorageInterface->getToken());
if ($decodedJwtToken['roles'][0] !== self::ADMIN) return $this->json(['message' => 'Accès refusé'], 403);
$role = $this->roleRepository->findOneBy(['name' => 'operator']);
$users = $this->userRepository->findBy(['role' => $role]);
$data = [];
foreach ($users as $user) {
$language = $user->getLanguage()->getName();
$name = $user->getName();
$date = $user->getDateInscription();
$messages = $this->messageRepository->findBy(['operator' => $users]);
$sentMessage = 0;
foreach ($messages as $message) {
$type = $message->getConversation()->getSenderProfil()->getProfilType();
if ($type == "fake_profil") {
$sentMessage++;
}
}
$data[] = [
'language' => $language,
'name' => $name,
'sentMessage' => $sentMessage,
'date' => $date,
];
}
return $this->json($data, Response::HTTP_OK);
}
/**
* API pour suppression d'un admin
*
*/
#[Route('/admin_delete/{id}', name: 'delete_admin', methods: ['DELETE'])]
public function deleteAdmin()
{
$user = $this->getUser();
if (!$user) return $this->json(['message' => "Vous n'êtes pas connécté"], Response::HTTP_NOT_FOUND);
if (!($user->getRoles()[0] == self::ADMIN)) {
return $this->json(['message' => "Vous n'êtes pas autorisé à accéder à cet API"], Response::HTTP_UNAUTHORIZED);
}
[$id] = $this->requestService->getFromAttributes('id');
$role = $this->roleRepository->findOneBy(['name' => self::ADMIN]);
$admin = $this->userRepository->findOneBy(['id' => $id, 'role' => $role]);
$admin->setDeleted(true);
$this->entityService->saveEntity($admin);
return $this->json(['message' => 'Admin supprimé avec succés'], Response::HTTP_OK);
}
}