<?php
/**
* Created by PhpStorm.
* User: DEVELUP-USER3
* Date: 05/03/2019
* Time: 10:57
*/
namespace App\MDS\ApiBundle\Controller;
use App\Entity\MobileAppEventContact;
use App\Entity\MobileAppUsersBehavior;
use App\Entity\EmailRegisteredEventAssistants;
use DateInterval;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints as Assert;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\View\View;
use Symfony\Component\DependencyInjection\ContainerInterface;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Swift_Mailer;
use Swift_Message;
use Swift_Attachment;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class ApiAttendantsController extends AbstractFOSRestController
{
/**
* @Route("/api/email/registered/event/assistants", methods={"GET"})
*/
public function apiGuestAction(Request $request, EntityManagerInterface $em)
{
$serverHour = new \DateTime();
$serverHour->add(new \DateInterval('PT1H'));
$serverHourLess = clone $serverHour;
$serverHourLess->sub(new \DateInterval('PT5M'));
$serverHourLess = $serverHourLess->format('H:i');
$serverHourMore = clone $serverHour;
$serverHourMore->add(new \DateInterval('PT5M'));
$serverHourMore = $serverHourMore->format('H:i');
$configurations = $em->getRepository('App:EmailRegisteredEventAssistants')->findAll();
foreach ($configurations as $configuration) {
$hour = $configuration->getHour()->format('H:i');
$rows = [];
$headers = $configuration->getColumns();
$headers = explode(';', $headers);
$event = $em->getRepository('App:MobileAppEvent')->findOneBy(['id' => $configuration->getEid()]);
$guests = $em->getRepository('App:AppMobileGuest')->findBy(['eid' => $event->getId()]);
if ($hour >= $serverHourLess && $hour <= $serverHourMore) {
foreach ($guests as $guest) {
$rowData = [];
foreach ($headers as $header) {
$getterMethod = 'get' . ucfirst(strtolower(str_replace(' ', '', $header)));
if (method_exists($guest, $getterMethod)) {
$rowData[$header] = $guest->{$getterMethod}();
} else {
$rowData[$header] = '';
}
}
$rows[] = $rowData;
}
$tempFile = tempnam(sys_get_temp_dir(), 'excel') . '.xlsx';
$this->generateCsvRegisteredAttendantsSold($headers, $rows, $tempFile);
$message = (new Swift_Message('Datos de registros - ' . $event->getName()))
->setFrom('eventos@develup.solutions')
->setTo($configuration->getEmailTo())
->setBody('Datos de registrados en fichero adjunto', 'text/plain', 'utf-8')
->attach(Swift_Attachment::fromPath($tempFile)->setFilename($event->getName() . '.xlsx'));
$this->mailer->send($message);
unlink($tempFile);
}
}
return new Response();
}
protected function generateCsvRegisteredAttendantsSold($headers, $rows, $tempFile)
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$columnIndex = 'A';
foreach ($headers as $header) {
$sheet->setCellValue($columnIndex . '1', $header);
$columnIndex++;
}
$rowIndex = 2;
foreach ($rows as $row) {
$columnIndex = 'A';
foreach ($row as $cellValue) {
$sheet->setCellValue($columnIndex . $rowIndex, $cellValue);
$sheet->getStyle($columnIndex . $rowIndex)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
$columnIndex++;
}
$rowIndex++;
}
$writer = new Xlsx($spreadsheet);
$writer->save($tempFile);
}
/**
* @Rest\Get("/api/attendants/get")
*/
public function selectApiAttendantAction(Request $request)
{
$eid = $request->headers->get('eid');
$em = $this->getDoctrine()->getManager();
$token = $request->headers->get('token');
$uid = $em->getRepository(MobileAppToken::class)->findOneBy(
array('token' => $token)
);
if(empty($uid)){
$response = new JsonResponse("Session expired! Login again", 401);
return $response;
}
$uid = $uid->getUid();
$eventusers = $em->getRepository(AppUsersByEvent::class)->findBy(
array(
'eventId' => $eid,
'status' => 1,
),
array('qr' => 'ASC')
);
$attendants = array();
// $attendants = [];
if (!empty($eventusers)) {
foreach ($eventusers as $usuario){
if($usuario->getUserId() !== $uid){
$user = $em->getRepository(MobileAppUsers::class)->findOneBy(
array('shareContact' => 1, 'id' => $usuario->getUserId() )
);
$attendantsUser = $em->getrepository(AppMobileGuest::class)->findOneBy(
array( 'token' => $usuario->getQrToken() )
);
if(!empty($user) and !empty($attendantsUser)){
$attendants[] = array(
"id" => $user->getId(),
"attendantid" => $attendantsUser->getId(),
"name" => $user->getFullname(),
"image" => empty($user->getImage()) ? null : 'https://' . $_SERVER['HTTP_HOST']. '/' . $user->getImage()
);
}
}
}
}
$count = count($attendants);
$response_body = json_encode(array(
'attendants' => $attendants,
'meta' => array('count' => $count),
));
$response = new JsonResponse($response_body);
$em->clear();
return $response;
}
/**
* @Rest\Get("/api/attendants/getOne")
*/
public function selectApiOneAttendantsAction(Request $request) {
$attendantid = $request->headers->get('attendantid');
$id = $request->headers->get('id');
$em = $this->getDoctrine()->getManager();
$attendantsConsulta = $em->getrepository(AppMobileGuest::class)->findOneBy(
array('id' => $attendantid)
);
$user = $em->getRepository(MobileAppUsers::class)->findOneBy(
array('id' => $id )
);
$data = array();
if (!empty($attendantsConsulta)){
$prefix='https://'.$_SERVER['HTTP_HOST'].'/';
$var=(is_null($user->getImage()))?NULL:$prefix.$user->getImage();
$data = array(
"id" => $id,
"attendantid" => $attendantsConsulta->getId(),
"eid" => $attendantsConsulta->getEid(),
"image" =>$var,
"name" => $attendantsConsulta->getFirstName().' '.$attendantsConsulta->getLastName(),
"jobTitle" => is_null($attendantsConsulta->getJobTitle())?"":$attendantsConsulta->getJobTitle(),
"company" => is_null($attendantsConsulta->getCompany())?"":$attendantsConsulta->getCompany(),
"email" => $attendantsConsulta->getEmail(),
"telephone" => is_null($attendantsConsulta->getTelephone())?"":$attendantsConsulta->getTelephone(),
);
}
$response_body = json_encode(array(
'data' => $data,
));
$response = new JsonResponse($response_body);
$em->clear();
return $response;
}
/**
* @Rest\Get("/api/attendants/getNat")
*/
public function selectApiAttendantNativoAction(Request $request)
{
$eid = $request->headers->get('eid');
$token = $request->headers->get('token');
/* Mobile Operating System */
if ($request->headers->has('operatingsystem') == true){
if (empty($request->headers->get('operatingsystem'))){
$os = null;
}else{
$os = $request->headers->get('operatingsystem');
}
}else{
$os = null;
}
/* Mobile Model */
if ($request->headers->has('mobilemodel') == true){
if (empty($request->headers->get('mobilemodel'))){
$mm = null;
}else{
$mm = $request->headers->get('mobilemodel');
}
}else{
$mm = null;
}
/* Mobile Version */
if ($request->headers->has('mobileversion') == true){
if (empty($request->headers->get('mobileversion'))){
$mv = null;
}else{
$mv = $request->headers->get('mobileversion');
}
}else{
$mv = null;
}
/* Mobile lang */
if ($request->headers->has('lang') == true){
if (empty($request->headers->get('lang'))){
$lg = null;
}else{
$lg = $request->headers->get('lang');
}
}else{
$lg = null;
}
$em = $this->getDoctrine()->getManager();
$uid = $em->getRepository(MobileAppToken::class)->findOneBy(
array('token' => $token)
);
if(empty($uid)){
$response = new JsonResponse("Session expired! Login again", 401);
return $response;
}
$uid = $uid->getUid();
$eventusers = $em->getRepository(AppUsersByEvent::class)->findBy(
array(
'eventId' => $eid,
'status' => 1,
),
array('qr' => 'ASC')
);
$attendants = array();
// $attendants = [];
if (!empty($eventusers)) {
foreach ($eventusers as $usuario){
if($usuario->getUserId() !== $uid){
$user = $em->getRepository(MobileAppUsers::class)->findOneBy(
array('shareContact' => 1, 'id' => $usuario->getUserId() )
);
$attendantsUser = $em->getrepository(AppMobileGuest::class)->findOneBy(
array( 'token' => $usuario->getQrToken() )
);
if(!empty($user) and !empty($attendantsUser)){
$attendants[] = array(
"id" => $user->getId(),
"attendantid" => $attendantsUser->getId(),
// "fullname" => $user->getFullname(),
"fullname" => $attendantsUser->getLastName().' '.$attendantsUser->getFirstName(),
"name" => $attendantsUser->getFirstName(),
"lastname" => $attendantsUser->getLastName(),
"image" => empty($user->getImage()) ? null : 'https://' . $_SERVER['HTTP_HOST']. '/' . $user->getImage()
);
}
}
/* LIBERAR MEMORIA A MANO */
$em->detach($usuario);
unset($usuario);
}
}
$action = 'List Attendants';
$this->saveUserBehavior($uid, $eid, $os, $mm, $mv, $lg, $action,'Attendants');
$count = count( $attendants );
$response_base =array(
'data' => $attendants,
'meta' => array( 'count' => $count ),
);
$response_body = json_encode($response_base, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
$response = new Response($response_body, 200);
$em->clear();
return $response;
}
/**
* @Rest\Get("/api/attendants/getOneNat")
*/
public function selectApiOneAttendantsNativoAction(Request $request) {
$attendantid = $request->headers->get('attendantid');
$id = $request->headers->get('id');
// $token = $request->headers->get('token');
$em = $this->getDoctrine()->getManager();
// $uid = $em->getRepository(MobileAppToken::class)->findOneBy(
// array('token' => $token)
// );
//
// if(empty($uid)){
// $response = new JsonResponse("Session expired! Login again", 401);
// return $response;
// }
$attendantsConsulta = $em->getrepository(AppMobileGuest::class)->findOneBy(
array('id' => $attendantid)
);
$user = $em->getRepository(MobileAppUsers::class)->findOneBy(
array('id' => $id )
);
$data = array();
if (!empty($attendantsConsulta)){
$prefix='https://'.$_SERVER['HTTP_HOST'].'/';
$var=(is_null($user->getImage()))?NULL:$prefix.$user->getImage();
$data = array(
"id" => $id,
"attendantid" => $attendantsConsulta->getId(),
"eid" => $attendantsConsulta->getEid(),
"image" =>$var,
"fullname" => $attendantsConsulta->getFirstName().' '.$attendantsConsulta->getLastName(),
"name" => $attendantsConsulta->getFirstName(),
"lastname" => $attendantsConsulta->getLastName(),
"jobTitle" => is_null($attendantsConsulta->getJobTitle())?"":$attendantsConsulta->getJobTitle(),
"company" => is_null($attendantsConsulta->getCompany())?"":$attendantsConsulta->getCompany(),
"email" => $attendantsConsulta->getEmail(),
"telephone" => is_null($attendantsConsulta->getTelephone())?"":$attendantsConsulta->getTelephone(),
);
}
$response_base =array(
'data' => $data,
);
$response_body = json_encode($response_base, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
$response = new Response($response_body, 200);
$em->clear();
return $response;
}
/**
* @Rest\Get("/api/attendants/getTwoNat")
*/
public function selectApiTwoAttendantsNativoAction(Request $request) {
$attendantid = $request->headers->get('attendantid');
$id = $request->headers->get('id');
$token = $request->headers->get('token');
/* Mobile Operating System */
if ($request->headers->has('operatingsystem') == true){
if (empty($request->headers->get('operatingsystem'))){
$os = null;
}else{
$os = $request->headers->get('operatingsystem');
}
}else{
$os = null;
}
/* Mobile Model */
if ($request->headers->has('mobilemodel') == true){
if (empty($request->headers->get('mobilemodel'))){
$mm = null;
}else{
$mm = $request->headers->get('mobilemodel');
}
}else{
$mm = null;
}
/* Mobile Version */
if ($request->headers->has('mobileversion') == true){
if (empty($request->headers->get('mobileversion'))){
$mv = null;
}else{
$mv = $request->headers->get('mobileversion');
}
}else{
$mv = null;
}
/* Mobile lang */
if ($request->headers->has('lang') == true){
if (empty($request->headers->get('lang'))){
$lg = null;
}else{
$lg = $request->headers->get('lang');
}
}else{
$lg = null;
}
$em = $this->getDoctrine()->getManager();
$uid = $em->getRepository(MobileAppToken::class)->findOneBy(
array('token' => $token)
);
if(empty($uid)){
$response = new JsonResponse("Session expired! Login again", 401);
return $response;
}
$attendantsConsulta = $em->getrepository(AppMobileGuest::class)->findOneBy(
array('id' => $attendantid)
);
$user = $em->getRepository(MobileAppUsers::class)->findOneBy(
array('id' => $id )
);
$data = array();
if (!empty($attendantsConsulta)){
// comprobamos que ya no tenga los permisos previamente
$MobileAppScanCardPermission = $em->getRepository(MobileAppScanCardPermission::class)->findOneBy(
array(
'eid' => $attendantsConsulta->getEid(),
'asksUserId' => $uid->getUid(),
'grantUserGuestId' => $attendantid,
'grantUserId' => $user->getId(),
)
);
if (empty($MobileAppScanCardPermission)){
$jobTitle = "";
$company = "";
$email = "";
$telephone = "";
}else{
$jobTitle = is_null($attendantsConsulta->getJobTitle())?"":$attendantsConsulta->getJobTitle();
$company = is_null($attendantsConsulta->getCompany())?"":$attendantsConsulta->getCompany();
$email = $attendantsConsulta->getEmail();
$telephone = is_null($attendantsConsulta->getTelephone())?"":$attendantsConsulta->getTelephone();
}
$prefix='https://'.$_SERVER['HTTP_HOST'].'/';
$var=(is_null($user->getImage()))?NULL:$prefix.$user->getImage();
$data = array(
"id" => $id,
"attendantid" => $attendantsConsulta->getId(),
"eid" => $attendantsConsulta->getEid(),
"image" =>$var,
"fullname" => $attendantsConsulta->getFirstName().' '.$attendantsConsulta->getLastName(),
"name" => $attendantsConsulta->getFirstName(),
"lastname" => $attendantsConsulta->getLastName(),
"jobTitle" => $jobTitle,
"company" => $company,
"email" => $email,
"telephone" => $telephone,
);
}
$action = 'Details Attendants, '.$attendantid;
$this->saveUserBehavior($uid->getUid(), $attendantsConsulta->getEid(), $os, $mm, $mv, $lg, $action,'Attendants');
$response_base =array(
'data' => $data,
);
$response_body = json_encode($response_base, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
$response = new Response($response_body, 200);
$em->clear();
return $response;
}
private function saveUserBehavior($userId, $event, $os, $mm, $mv, $lg, $action, $module){
$em = $this->getDoctrine()->getManager();
$MobileAppUsersBehavior = new MobileAppUsersBehavior();
$MobileAppUsersBehavior->setUserId($userId);
$MobileAppUsersBehavior->setEventId($event);
$MobileAppUsersBehavior->setOperatingSystem($os);
$MobileAppUsersBehavior->setMobileModel($mm);
$MobileAppUsersBehavior->setMobileVersion($mv);
$MobileAppUsersBehavior->setAction($action);
$MobileAppUsersBehavior->setModule($module);
$MobileAppUsersBehavior->setLang($lg);
$em->persist($MobileAppUsersBehavior);
$em->flush();
$em->clear();
}
}