<?php
namespace App\Application\Internit\ContentBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;
use Sonata\AdminBundle\Controller\CoreController as BaseCoreContBroller;
class CoreController extends BaseCoreContBroller
{
public function permissionByRole(array $rolesPermission, $user)
{
/** Caso seja Super Administrador */
if( in_array('ROLE_SUPER_ADMIN', $user->getRoles()) )
return true;
foreach ($rolesPermission as $role)
if( in_array($role, $user->getRoles()) )
//dump($user);
return true;
return false;
}
public function dashboardAction()
{
$user = $this->get('security.token_storage')->getToken()->getUser();
if(!$this->permissionByRole(array('ROLE_SUPER_ADMIN'), $user))
if($this->permissionByRole(array('ROLE_CENTRAL_VENDAS'), $user))
return $this->redirectToRoute('admin_internit_proposal_proposal_realtyList');
// construtora pode ver todos os imóveis e espelhos de vendas cadastrados no sistema,
// independente da imobiliária a qual o imóvel percente.
// userId para construtora será null. Assim ela poderá ver tudo
$userId = in_array('ROLE_CONSTRUTORA', $user->getRoles()) ? null : $user->getId();
$realtys = $this->getDoctrine()->getRepository("ApplicationInternitRealEstateBundle:Realty")->dashBoardRealty($userId);
$mirrors = $this->getDoctrine()->getRepository("ApplicationInternitRealEstateBundle:Realty")->dashBoardMirror($userId);
$where = array();
$proposalOrder = array('createdAt' => 'DESC');
if (in_array('ROLE_CORRETOR', $this->get('security.token_storage')->getToken()->getUser()->getRoles()))
$where = array('user'=>$this->get('security.token_storage')->getToken()->getUser()->getid());
// usuário com perfil imobiliária vê todas as propostas abertas para empreendimentos
// da imobiliária
if (in_array('ROLE_IMOBILIARIA', $user->getRoles())) {
$proposals = $this->getDoctrine()
->getRepository('ApplicationInternitProposalBundle:Proposal')
->findByUserRealEstates($user->getId());
}
else {
// usuário com perfil corretor e perfil construtora
$proposals = $this->getDoctrine()
->getRepository('ApplicationInternitProposalBundle:Proposal')
->findBy($where, $proposalOrder);
}
// mostrar opções de imóveis das imobiliárias que o corretor faz parte
if (in_array('ROLE_CONSTRUTORA', $user->getRoles())) {
// construtora: vê todos os rankings do sistema
$rankings = $this->getDoctrine()
->getRepository("ApplicationInternitRealEstateBundle:Realty")
->dashBoardRanking();
}
elseif (in_array('ROLE_IMOBILIARIA', $user->getRoles())) {
// imobiliária: vê os rankings dos imóveis da imobiliária
$rankings = $this->getDoctrine()
->getRepository("ApplicationInternitRealEstateBundle:Realty")
->dashBoardRankingRealEstate($userId);
}
else {
// corretor: vê os rankings dos quais participa
$rankings = $this->getDoctrine()
->getRepository("ApplicationInternitRealEstateBundle:Realty")
->dashBoardRankingUser($userId);
}
// Adicionando uma opção vazia ao array de opções
$rankings = array_merge(
[ [ 'id' => '', 'realty' => 'Selecione um Empreendimento' ] ],
$rankings
);
//SALESGOAL
if (in_array('ROLE_CONSTRUTORA', $user->getRoles())) {
$data = $this->getDoctrine()->getRepository('ApplicationInternitSalesGoalBundle:SalesGoal')->findAll();
}
else {
$data = $this->getDoctrine()
->getRepository('ApplicationInternitSalesGoalBundle:SalesGoal')
->findByUserRealEstate($userId);
}
$infoSaleGoal = $this->getDoctrine()->getRepository('ApplicationInternitSalesGoalBundle:SalesGoal')->showSalesGoal();
$goals = array();
$value = 0;
$salesGoal = array();
foreach($data as $d)
{
foreach($infoSaleGoal as $info)
{
if($info['id'] == $d->getId())
{
if($info['type']=='valor')
{
$value = floatval($info['total_proposal']) + $value;
$goals[$d->getId()]['total'] = $value;
$goals[$d->getId()]['points'][$info['month_year']] = floatval($info['total_proposal']);
}
elseif($info['type']=='unidades')
{
$value = floatval($info['amount_proposal']) + $value;
$goals[$d->getId()]['total'] = $value;
$goals[$d->getId()]['points'][$info['month_year']] = floatval($info['amount_proposal']);
}
}
}
$value = 0;
}
$salesGoal['goals'] = $goals;
$salesGoal['datas'] = $data;
//SALESGOAL
/******************** QUIZ **********************/
$userId = $this->getUser()->getId();
// obtém as respostas que o usuário fez aos quizes
$userAnswers = $this->getDoctrine()->getRepository('ApplicationInternitQuizBundle:Quiz')
->viewUserAnswers($userId);
// quizes que o usuário ainda não respondeu
if (in_array('ROLE_CONSTRUTORA', $user->getRoles())) {
$quizesToAnswer = $this->getDoctrine()
->getRepository('ApplicationInternitQuizBundle:Quiz')
->viewUnansweredQuiz($userId);
}
else {
$quizesToAnswer = $this->getDoctrine()
->getRepository('ApplicationInternitQuizBundle:Quiz')
->viewRealtorUnansweredQuiz($userId);
}
$numQuizesToAnswer = count($quizesToAnswer);
$spentPoints = $this->getDoctrine()
->getRepository('ApplicationInternitQuizBundle:Quiz')->fetchSpentPoints($userId);
// para a última resposta do usuário
$lastUserAnswer = empty($userAnswers) ? null : $userAnswers[0];
$lastUserAnswerHitsPercentage = 0;
// para estatísticas de pontos e porcentagem de acertos totais
$totalScore = 0;
$totalHits = 0;
$totalHitsPercentage = 0;
$totalNumAnswers = 0;
$lastHits = 0;
$lastNumAnswers = 0;
foreach($userAnswers as $ua) {
$totalScore += $ua->getScore();
$totalHits += $ua->getNumHits();
$totalNumAnswers += count($ua->getAnswers());
if ($ua->getCreatedAt() > $lastUserAnswer->getCreatedAt()) {
$lastUserAnswer = $ua;
}
}
$availablePoints = $totalScore - $spentPoints;
if ($totalNumAnswers > 0) {
$totalHitsPercentage = ($totalHits / $totalNumAnswers) * 100;
}
if ($lastUserAnswer) {
$lastUserAnswerHitsPercentage = $lastUserAnswer->getHitsPercentage();
$lastHits = $lastUserAnswer->getNumHits();
$lastNumAnswers = count($lastUserAnswer->getAnswers());
}
$randomRewards = $this->getDoctrine()
->getRepository('ApplicationInternitQuizBundle:Quiz')->viewRandomReward($userId, 2);
$user = $this->getUser();
/********************* Comunicados **********************/
$comunicadosAll = $this->getDoctrine()->getRepository('ApplicationInternitCommunicationBundle:Communication')->findBy([], ['date'=>'DESC']);
if ( in_array('ROLE_CORRETOR', $user->getRoles()) || in_array('ROLE_IMOBILIARIA', $user->getRoles()) ){
$comunicados = [];
foreach ($comunicadosAll as $comunicado){
foreach ( $comunicado->getRealEstates() as $re ){
foreach ( $user->getRealEstates() as $userRE ){
if( $re === $userRE ){
$comunicados[] = $comunicado;
break;
}
}
}
}
$comunicadosAll = $comunicados;
}
//dump($comunicadosAll);
/********************* FIM QUIZ **********************/
/**/
return $this->render(
'@ApplicationInternit/ContentBundle/Resources/views/home.html.twig',
[
'realtys' => $realtys,
'mirrors' => $mirrors,
'proposals' => $proposals,
'rankings' => $rankings,
'salesGoal' => $salesGoal,
'availablePoints' => $availablePoints,
'totalHitsPercentage' => $totalHitsPercentage,
'numQuizesToAnswer' => $numQuizesToAnswer,
'lastAnswerHits' => $lastUserAnswerHitsPercentage,
'randomRewards' => $randomRewards,
'totalHits' => $totalHits,
'totalNumAnswers' => $totalNumAnswers,
'totalHitsPercentage' => $totalHitsPercentage,
'lastHits' => $lastHits,
'lastNumAnswers' => $lastNumAnswers,
'lastUserAnswerHitsPercentage' => $lastUserAnswerHitsPercentage,
'comunicados' => $comunicadosAll,
]
);
}
}