Skip to content

Commit

Permalink
Enquetes funcionando!
Browse files Browse the repository at this point in the history
  • Loading branch information
guaycuru committed Jun 8, 2017
1 parent 5ea4bf3 commit 5e21846
Show file tree
Hide file tree
Showing 8 changed files with 328 additions and 84 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ Funciona:
- Disciplina
- Editar Perfil (pouco testada)
- Eliminar Disciplinas
- Enquetes
- Estatísticas (parcial)
- Frase do Dia
- Login
Expand All @@ -56,7 +57,6 @@ Ainda não funciona:
- Admin
- API
- Chat
- Enquetes


P: E qual o prazo pra isso ser concluído?
Expand Down
39 changes: 39 additions & 0 deletions ajax/enquete.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace GDE;

define('JSON', true);

require_once('../common/common.inc.php');

if((isset($_POST['votar'])) && (isset($_POST['enquete']))) {
$Enquete = Enquete::Load($_POST['enquete']);
if($Enquete->getID() == null)
Base::Error_JSON('Enquete não encontrada.');
if(($Enquete->Ja_Votou($_Usuario)) || ($Enquete->getAtiva() === false))
Base::Error_JSON('Voc&ecirc; j&aacute; votou nesta Enquete');
elseif((($Enquete->getMax_Votos() > 1) && ((!isset($_POST['votos'])) || (!is_array($_POST['votos'])))) || (($Enquete->getMax_Votos() == 1) && ((!isset($_POST['voto'])) || ($_POST['voto'] == null))))
Base::Error_JSON('Selecione pelo menos uma op&ccedil;&atilde;o...');
elseif((isset($_POST['votos'])) && (count($_POST['votos']) > $Enquete->getMax_Votos()))
Base::Error_JSON('Selecione no m&aacute;ximo '.$Enquete->getMax_Votos().(($Enquete->getMax_Votos() > 1)? ' op&ccedil;&otilde;es' : ' op&ccedil;&atilde;o').'...');
else {
if($Enquete->getMax_Votos() == 1) {
$Opcao = EnqueteOpcao::Load($_POST['voto']);
if($Opcao->getID() == null)
Base::Error_JSON('Opção não encontrada.');
if(($Opcao->getEnquete() === null) || ($Opcao->getEnquete()->getID()) != $Enquete->getID())
Base::Error_JSON('Opção inválida.');
$_Usuario->addEnquetes_Opcoes($Opcao);
} else {
foreach($_POST['votos'] as $id_opcao) {
$Opcao = EnqueteOpcao::Load($id_opcao);
if($Opcao->getID() == null)
Base::Error_JSON('Opção não encontrada.');
if(($Opcao->getEnquete() === null) || ($Opcao->getEnquete()->getID()) != $Enquete->getID())
Base::Error_JSON('Opção inválida.');
$_Usuario->addEnquetes_Opcoes($Opcao);
}
}
$_Usuario->Save_JSON(true);
}
}
96 changes: 96 additions & 0 deletions ajax/enquetes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

namespace GDE;

define('NO_CACHE', true);
define('NO_HTML', true);
define('NO_REDIRECT', true);

require_once('../common/common.inc.php');

if(empty($_GET['id']))
exit();

$Enquete = Enquete::Load($_GET['id']);
$resultado = ((isset($_GET['res'])) || ($Enquete->Ja_Votou($_Usuario)) || ($Enquete->getAtiva() === false));
?>
<script type="text/javascript">
$.tablesorter.addParser({
id: 'votos',
is: function(s) { return false; },
format: function(s) {
var tmp = s.split(" ");
return tmp[0];
},
type: 'numeric'
});
var resultados = function() {
$("div.enquete_content").Carregando();
$("div.enquete_content").load('<?= CONFIG_URL; ?>ajax/enquetes.php?id=<?= $Enquete->getID(); ?>&res');
return false;
};
$(document).ready(function() {
$("#ver_resultados").click(resultados);
$("#atualizar").click(resultados);
});
</script>
<div class="enquete_content" style="width: 640px; height: 480px;">
<?php if(!$resultado) { ?>
<form method="post" class="auto-form" action="<?= CONFIG_URL; ?>ajax/enquete.php" data-destino="<?= CONFIG_URL; ?>" data-sucesso="Voto computado com sucesso! Obrigado!">
<input type="hidden" name="enquete" value="<?= $Enquete->getID(); ?>" />
<?php } ?>
<table border="1" id="table_enquete" class="tabela_bonyta" width="95%">
<thead>
<tr>
<td align="center" colspan="<?= ($resultado) ? 3 : 1; ?>"><strong><?= $Enquete->getPergunta(false); ?></strong></td>
</tr>
<?php if($resultado) { ?>
<tr>
<th align="center" width="75%"><strong>Op&ccedil;&atilde;o</strong></td>
<th align="center" width="15%"><strong>Votos</strong></td>
<td align="center"><strong>-</strong></td>
</tr>
</thead>
<tbody>
<?php
$total_votos = $Enquete->Numero_Votos();
$total_usuarios = $Enquete->Numero_Usuarios();
foreach($Enquete->getOpcoes() as $Opcao) {
$votos = $Opcao->Numero_Votos();
$porcentagem = $Opcao->Porcentagem(2);
?>
<tr>
<td><?= $Opcao->getOpcao(false); ?></td>
<td><?= $votos; ?> (<?= $porcentagem; ?>%)</td>
<td><img src="<?= CONFIG_URL; ?>web/images/barra.gif" alt="" width="<?= ceil($porcentagem * 2); ?>" height="12" /></td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr>
<td colspan="3" align="center">Total de Votos: <?= $total_votos; ?> (<?= $total_usuarios; ?> Usu&aacute;rios)</td>
</tr>
</tfoot>
<?php } else { ?>
</thead>
<tbody>
<?php foreach($Enquete->getOpcoes() as $Opcao) { ?>
<tr>
<td><input type="<?= (($Enquete->getMax_Votos() > 1) ? "checkbox" : "radio"); ?>" class="opcao" name="<?= (($Enquete->getMax_Votos() > 1) ? "votos[]" : "voto"); ?>" value="<?= $Opcao->getID(); ?>" id="opcao_<?= $Opcao->getID(); ?>" /><label for="opcao_<?= $Opcao->getID(); ?>"><?= $Opcao->getOpcao(false); ?></label></td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr>
<td align="center"><input type="submit" name="votar" value=" " class="botao_salvar" /><br />
<a href="#" id="ver_resultados">Ver Resultados</a></td>
</tr>
</tfoot>
<?php } ?>
</table>
<?php if(!$resultado) { ?>
</form>
<?php } else { ?>
<div align="center"><a href="#" id="atualizar">Atualizar</a></div>
<?php } ?>
</div>
75 changes: 74 additions & 1 deletion classes/GDE/Enquete.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@
/**
* Enquete
*
* @ORM\Table(name="gde_enquetes")
* @ORM\Table(
* name="gde_enquetes",
* indexes={
* @ORM\Index(name="ativa", columns={"ativa"})
* }
* )
* @ORM\Entity
*/
class Enquete extends Base {
Expand All @@ -20,13 +25,27 @@ class Enquete extends Base {
*/
protected $id_enquete;

/**
* @var EnqueteOpcao
*
* @ORM\OneToMany(targetEntity="EnqueteOpcao", mappedBy="enquete")
*/
protected $opcoes;

/**
* @var string
*
* @ORM\Column(type="string", length=255, nullable=false)
*/
protected $nome;

/**
* @var string
*
* @ORM\Column(type="string", nullable=false)
*/
protected $chamada;

/**
* @var string
*
Expand Down Expand Up @@ -55,5 +74,59 @@ class Enquete extends Base {
*/
protected $max_votos = 1;

/**
* @return Enquete|null
*/
public static function Ativa() {
$Enquetes = self::FindBy(array('ativa' => true), null, 1);
return (count($Enquetes) > 0) ? $Enquetes[0] : null;
}

/**
* @param Usuario $Usuario
* @return integer
*/
public function Usuario_Quantos_Votos(Usuario $Usuario) {
$dql = "SELECT COUNT(O.id_opcao) FROM ".get_class()." AS E ".
"JOIN E.opcoes AS O ".
"WHERE E.id_enquete = :id_enquete ".
"AND :usuario MEMBER OF O.usuarios";
return self::_EM()->createQuery($dql)
->setParameter('id_enquete', $this->getID())
->setParameter('usuario', $Usuario)
->getSingleScalarResult();
}

/**
* @param Usuario $Usuario
* @return bool
*/
public function Ja_Votou(Usuario $Usuario) {
return ($this->Usuario_Quantos_Votos($Usuario) > 0);
}

/**
* @return integer
*/
public function Numero_Votos() {
$dql = "SELECT COUNT(U.id_usuario) FROM ".get_class()." AS E ".
"JOIN E.opcoes AS O JOIN O.usuarios AS U ".
"WHERE E.id_enquete = :id_enquete";
return self::_EM()->createQuery($dql)
->setParameter('id_enquete', $this->getID())
->getSingleScalarResult();
}

/**
* @return integer
*/
public function Numero_Usuarios() {
$dql = "SELECT COUNT(DISTINCT U.id_usuario) FROM ".get_class()." AS E ".
"JOIN E.opcoes AS O JOIN O.usuarios AS U ".
"WHERE E.id_enquete = :id_enquete";
return self::_EM()->createQuery($dql)
->setParameter('id_enquete', $this->getID())
->getSingleScalarResult();
}

}
35 changes: 30 additions & 5 deletions classes/GDE/EnqueteOpcao.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace GDE;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
Expand All @@ -24,18 +25,20 @@ class EnqueteOpcao extends Base {
* @var Enquete
*
* @ORM\ManyToOne(targetEntity="Enquete")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_enquete", referencedColumnName="id_enquete")
* })
* @ORM\JoinColumn(name="id_enquete", referencedColumnName="id_enquete")
*/
protected $enquete;

/**
* @var \Doctrine\Common\Collections\Collection
* @var ArrayCollection|Usuario[]
*
* @ORM\ManyToMany(targetEntity="Usuario", mappedBy="enquetes_opcoes")
* @ORM\JoinTable(name="gde_r_usuarios_enquetes_opcoes",
* inverseJoinColumns={@ORM\JoinColumn(name="id_usuario", referencedColumnName="id_usuario")},
* joinColumns={@ORM\JoinColumn(name="id_opcao", referencedColumnName="id_opcao")}
* )
*/
protected $usuario;
protected $usuarios;

/**
* @var string
Expand All @@ -51,5 +54,27 @@ class EnqueteOpcao extends Base {
*/
protected $ativa = false;

/**
* @return integer
*/
public function Numero_Votos() {
$dql = "SELECT COUNT(DISTINCT U.id_usuario) FROM ".get_class()." AS O ".
"JOIN O.usuarios AS U ".
"WHERE O.id_opcao = :id_opcao";
return self::_EM()->createQuery($dql)
->setParameter('id_opcao', $this->getID())
->getSingleScalarResult();
}

/**
* @param int $decimais
* @return string
*/
public function Porcentagem($decimais = 2) {
$total_usuarios = $this->getEnquete()->Numero_Usuarios();
return ($total_usuarios > 0)
? number_format(($this->Numero_Votos() / $total_usuarios)*100, $decimais)
: '0.'.str_repeat('0', $decimais);
}

}
2 changes: 1 addition & 1 deletion classes/GDE/Usuario.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ class Usuario extends Base {
/**
* @var ArrayCollection|EnqueteOpcao[]
*
* @ORM\ManyToMany(targetEntity="EnqueteOpcao")
* @ORM\ManyToMany(targetEntity="EnqueteOpcao", inversedBy="usuarios")
* @ORM\JoinTable(name="gde_r_usuarios_enquetes_opcoes",
* joinColumns={@ORM\JoinColumn(name="id_usuario", referencedColumnName="id_usuario")},
* inverseJoinColumns={@ORM\JoinColumn(name="id_opcao", referencedColumnName="id_opcao")}
Expand Down
13 changes: 11 additions & 2 deletions views/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
$Recomendacoes = $_Usuario->Amigos_Recomendacoes(2, 15);
$Autorizacoes = $_Usuario->getAmigos_Pendentes();

$_enquete = '';
$Enquete = Enquete::Ativa();
if($Enquete !== null) {
$_enquete = '<div class="tip" id="perfil_tip" style="text-align: center;"><strong>'.$Enquete->getChamada(true).'</strong> Clique <a href="'.CONFIG_URL.'ajax/enquetes.php?id='.$Enquete->getID().'" id="enquete">aqui</a> e d&ecirc; sua opini&atilde;o!</div>';
}

// ToDo ?
if(!isset($_SESSION['atualizacoes_last_id']))
$_SESSION['atualizacoes_last_id'] = 0; //Acontecimento::Ultimo_Id_Por_Data($_SESSION['ultimo_acesso']);
Expand Down Expand Up @@ -241,7 +247,10 @@
$('#buscar_amigos1').Procura_Amigo('lista_amigos1');
$("a#enquete").fancybox({
'hideOnContentClick': false,
'autoDimensions': true
'autoDimensions': true,
'onComplete': function() {
$("#fancybox-content form.auto-form").each(auto_form_handler);
}
});
$("#lista_amigos2 div.sliding_top").live("click", function() {
Adicionar_Amigo_Sugestao(($(this).attr("id").split('_'))[1]);
Expand Down Expand Up @@ -288,7 +297,7 @@
</div>
</div>
</div>
<!-- <div class="tip" id="perfil_tip" style="text-align: center;"><strong>Ajude a escolher o futuro do GDE.</strong> Clique <a href="<?= CONFIG_URL; ?>ajax/ax_enquete.php?id=5" id="enquete">aqui</a> e d&ecirc; sua opini&atilde;o!</div> -->
<?= $_enquete; ?>
<div id="perfil_abas">
<div id="tabs">
<ul>
Expand Down
Loading

0 comments on commit 5e21846

Please sign in to comment.