Browse Source

Ajustando o fale conosco para as novas requisições do escolamodelows

master
Matheus456 6 years ago
parent
commit
502ea3fa47
  1. 271
      amd/src/config.js
  2. 6
      block_fale_conosco.php
  3. 16
      db/access.php
  4. 113
      index.php
  5. 64
      proxy.php
  6. 32
      searchform.php

271
amd/src/config.js

@ -1,147 +1,136 @@
define(['jquery', 'js/jquery.dataTables.min.js', 'js/jquery-ui.min.js'] , function($) { define(['jquery', 'js/jquery.dataTables.min.js', 'js/jquery-ui.min.js'] , function($) {
var exports = {}; var exports = {};
var answered = 1;
var init = exports.init = function() { var school = 'SSL';
$( "#id_situacao" ).change(function() { var init = exports.init = function() {
alert( "Handler for .change() called." ); // Altera entre mensagens respondidas e não respondidas
}); $( "#id_situacao" ).change(function() {
answered = $(this).val();
var tabelaContatos = $('#tabela_contatos').DataTable({ $("#id_situacao").val(answered);
//dom: "Bfrtip", tabelaContatos.ajax.url('proxy.php?schoolInitials=' + school +' + &answered=' + answered)
ajax: { tabelaContatos.ajax.reload();
url: "proxy.php", });
// dataType: "json",
// contentType: "aplication/json", // Obtém dados de todas as conversas
dataSrc:"" var tabelaContatos = $('#tabela_contatos').DataTable({
}, ajax: {
columns: [ url: "proxy.php?schoolInitials=" + school + "&answered=" + 0,
{ data: "id_conversa" }, dataSrc:""
{ data: "titulo" }, },
{ data: "cpf" } columns: [
], { data: "id_conversa" },
//select: true { data: "titulo" },
}); { data: "cpf" }
],
$( "#tabs" ).tabs({ active: 0 }); // Passando o datatable para português
"oLanguage": {
$('#tabela_contatos tbody').on( 'click', 'tr', function () { "sEmptyTable": "Nenhum registro encontrado",
if ( $(this).hasClass('selected') ) { "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
$(this).removeClass('selected'); "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
} "sInfoPostFix": "",
else { "sInfoThousands": ".",
tabelaContatos.$('tr.selected').removeClass('selected'); "sLengthMenu": "_MENU_ resultados por página",
$(this).addClass('selected'); "sLoadingRecords": "Carregando...",
} "sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
getMessagesFromContact(); "sSearch": "Pesquisar",
} ); "oPaginate": {
} "sNext": "Próximo",
"sPrevious": "Anterior",
/* "sFirst": "Primeiro",
Obtém todas as trocas de mensagens relacionadas a um determinado contato no Fale Conosco "sLast": "Último"
*/ },
var getMessagesFromContact = exports.getMessagesFromContact = function(contactID) { "oAria": {
$.ajax({ "sSortAscending": ": Ordenar colunas de forma ascendente",
url: "proxy.php?contactID=" + contactID, "sSortDescending": ": Ordenar colunas de forma descendente"
async: true, }
},
});
$( "#tabs" ).tabs({ active: 0 });
$('#tabela_contatos tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
tabelaContatos.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
data = tabelaContatos.row(this).data();
getMessagesFromContact(data);
} );
}
// Obtém todas as trocas de mensagens relacionadas a um determinado contato no Fale Conosco
var getMessagesFromContact = exports.getMessagesFromContact = function(data_conversation) {
$.ajax({
url: "proxy.php?conversationID=" + data_conversation.id_conversa,
type: "POST",
dataType: 'json',
success: function (data) {
var mensagens = "";
for (var i = 0, len = data.length; i < len; i++) {
var desc = data[i].body;
arrayReturn.push([ data[i].id, data[i].name, data[i].email]);
if (data[i].aluno != false) {
mensagens += '<div class="panel panel-success"> ';
}
else {
mensagens += '<div class="panel panel-primary"> ';
}
mensagens +=
' <div class="panel-heading">'+
' <h3 class="panel-title">' + data[i].cpf + '</h3>'+
' </div>'+
' <div class="panel-body">'+
data[i].texto_mensagem +
' </div><div class="text-right">'+
Date(data[i].data_mensagem) +
'</div></div>';
};
mensagens +=
'<div class="form-group">'+
'<label for="comment">Mensagem:</label>'+
'<textarea class="form-control" rows="5" id="comment"></textarea>'+
'</div>' +
'<button type="button" id="sendMessage" class="btn">Enviar</button>';
$('#mensagens').html(mensagens);
$('#sendMessage').click(function (){
description = $('#comment').val();
$('#comment').attr('value', "")
$.ajax({
url: "proxy.php?addMessage=" + data_conversation.id_conversa + "&description=" + description,
contentType: "application/json; charset=utf-8",
type: "post",
dataType: 'json', dataType: 'json',
success: function (data) { success: function (data) {
var mensagens = ""; alert("Mensagem enviada!");
for (var i = 0, len = data.length; i < len; i++) { $( "#tabs" ).tabs({ active: 0 });
var desc = data[i].body; },
arrayReturn.push([ data[i].id, data[i].name, data[i].email]); error: function (x, y, z) {
mensagens += alert(x.responseText +" " +x.status);
'<div class="panel panel-default"> '+
' <div class="panel-heading">'+
' <h3 class="panel-title">' + data[i].description + '</h3>'+
' </div>'+
' <div class="panel-body">'+
data[i].description +
' </div>'+
'</div>';
};
mensagens +=
'<div class="form-group">'+
'<label for="comment">Sua resposta:</label>'+
'<textarea class="form-control" rows="5" id="comment"></textarea>'+
'</div>' +
'<button type="button" id="sendMessage" class="btn">Basic</button>';
$('#mensagens').html(mensagens);
$('#sendMessage').click(function (){
$.ajax({
url: "proxy.php?addMessage=1",
data: "Teste", //ur data to be sent to server
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (data) {
alert("Mensagem enviada!");
$( "#tabs" ).tabs({ active: 0 });
},
error: function (x, y, z) {
alert(x.responseText +" " +x.status);
}
});
});
$( "#tabs" ).tabs({ active: 1 });
}
});
};
/*
Obtém dados de todos os contatos do Fale Conosco
*/
var getTableContacts = exports.getTableContacts = function() {
$( "#tabs" ).tabs();
$('ul.tabs li').click(function(){
var tab_id = $(this).attr('data-tab');
$('ul.tabs li').removeClass('current');
$('.tab-content').removeClass('current');
$(this).addClass('current');
$("#"+tab_id).addClass('current');
})
/*
var arrayReturn = [];
$.ajax({
url: "proxy.php",
async: true,
dataType: 'json',
success: function (data) {
for (var i = 0, len = data.length; i < len; i++) {
var desc = data[i].body;
arrayReturn.push([ data[i].id, data[i].name, data[i].email]);
}
tabela = $('#tabela_contatos').DataTable(
//{"aaData": arrayReturn}
{ajax: "proxy.php"}
);
//$( "#tabs" ).tabs({ active: 0 });
$('#tabela_contatos tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
tabela.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
getMessagesFromContact();
} );
} }
});
}); });
*/ $( "#tabs" ).tabs({ active: 1 });
}; }
});
return exports; };
});
// Obtém dados de todos os contatos do Fale Conosco
var getTableContacts = exports.getTableContacts = function() {
$( "#tabs" ).tabs();
$('ul.tabs li').click(function(){
var tab_id = $(this).attr('data-tab');
$('ul.tabs li .tab-content').removeClass('current');
$(this).addClass('current');
$("#"+tab_id).addClass('current');
})
};
return exports;
});

6
block_fale_conosco.php

@ -9,11 +9,11 @@ class block_fale_conosco extends block_base {
if ($this->content !== null) { if ($this->content !== null) {
return $this->content; return $this->content;
} }
$this->content = new stdClass; $this->content = new stdClass;
$this->content->text = 'The content of our SimpleHTML block!'; $this->content->text = 'The content of our SimpleHTML block!';
$this->content->footer = 'Footer here...'; $this->content->footer = 'Footer here...';
return $this->content; return $this->content;
} }
} }

16
db/access.php

@ -1,27 +1,29 @@
<?php <?php
$capabilities = array( $capabilities = array(
'block/fale_conosco:myaddinstance' => array( 'block/fale_conosco:myaddinstance' => array(
'captype' => 'write', 'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM, 'contextlevel' => CONTEXT_SYSTEM,
'archetypes' => array( 'archetypes' => array(
'user' => CAP_ALLOW // 'user' => CAP_ALLOW
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'manager' => CAP_ALLOW,
), ),
'clonepermissionsfrom' => 'moodle/my:manageblocks' 'clonepermissionsfrom' => 'moodle/my:manageblocks'
), ),
'block/fale_conosco:addinstance' => array( 'block/fale_conosco:addinstance' => array(
'riskbitmask' => RISK_SPAM | RISK_XSS, 'riskbitmask' => RISK_SPAM | RISK_XSS,
'captype' => 'write', 'captype' => 'write',
'contextlevel' => CONTEXT_BLOCK, 'contextlevel' => CONTEXT_BLOCK,
'archetypes' => array( 'archetypes' => array(
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'manager' => CAP_ALLOW 'manager' => CAP_ALLOW
), ),
'clonepermissionsfrom' => 'moodle/site:manageblocks' 'clonepermissionsfrom' => 'moodle/site:manageblocks'
), ),
); );

113
index.php

@ -10,7 +10,7 @@ if (isguestuser()) {
} }
// Prepare page // Prepare page
$context = context_system::instance(); $context = context_system::instance();
$PAGE->set_pagelayout('standard'); $PAGE->set_pagelayout('standard');
$PAGE->set_url('/blocks/fale_conosco/index.php'); $PAGE->set_url('/blocks/fale_conosco/index.php');
$PAGE->requires->css(new moodle_url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css')); $PAGE->requires->css(new moodle_url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'));
@ -18,6 +18,7 @@ $PAGE->requires->css(new moodle_url('https://code.jquery.com/ui/1.12.1/themes/ba
$PAGE->requires->css(new moodle_url('https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css')); $PAGE->requires->css(new moodle_url('https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css'));
$PAGE->set_context($context); $PAGE->set_context($context);
// Get data // Get data
@ -25,36 +26,16 @@ $strtitle = get_string('fale_conosco', 'block_fale_conosco');
$user = $USER; $user = $USER;
//$icon = $OUTPUT->pix_icon('print', get_string('print', 'block_fale_conosco'), 'block_fale_conosco'); //$icon = $OUTPUT->pix_icon('print', get_string('print', 'block_fale_conosco'), 'block_fale_conosco');
global $DB, $CFG; global $DB, $CFG, $USER;
/*
$uri = 'https://escolamodelows.interlegis.leg.br/api/v1/fale_conosco';
$response = \Httpful\Request::get($uri)
//->sendsJson()
//->body('{"school_initial": "SSL"}')
->expectsJson()
->send();
$data=$response->body;
html_writer::span("<p>Quantidade" . count($data) . '</p>');
// Print the header
$PAGE->navbar->add($strtitle);
$PAGE->set_title($strtitle);
$PAGE->set_heading($strtitle);
*/
//$PAGE->requires->css('/blocks/fale_conosco/printstyle.css');
echo $OUTPUT->header(); echo $OUTPUT->header();
// Print concluded courses // Print concluded courses
echo $OUTPUT->box_start('generalbox boxaligncenter'); echo $OUTPUT->box_start('generalbox boxaligncenter');
echo $OUTPUT->heading(get_string('fale_conosco', 'block_fale_conosco')); echo $OUTPUT->heading(get_string('fale_conosco', 'block_fale_conosco'));
//Instantiate simplehtml_form //Instantiate simplehtml_form
$mform = new searchform(); $mform = new searchform();
//Form processing and displaying is done here //Form processing and displaying is done here
@ -65,92 +46,15 @@ if ($mform->is_cancelled()) {
} else { } else {
// this branch is executed if the form is submitted but the data doesn't validate and the form should be redisplayed // this branch is executed if the form is submitted but the data doesn't validate and the form should be redisplayed
// or on the first display of the form. // or on the first display of the form.
//Set default data (if any)
//$mform->set_data($toform);
//displays the form
$mform->display(); $mform->display();
} }
?> ?>
<!--
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css"/>
-->
<style>
/*
body{
margin-top: 100px;
font-family: 'Trebuchet MS', serif;
line-height: 1.6
}
.container{
width: 800px;
margin: 0 auto;
}
ul.tabs{
margin: 0px;
padding: 0px;
list-style: none;
}
ul.tabs li{
background: none;
color: #222;
display: inline-block;
padding: 10px 15px;
cursor: pointer;
}
ul.tabs li.current{
background: #ededed;
color: #222;
}
.tab-content{
display: none;
background: #ededed;
padding: 15px;
}
.tab-content.current{
display: inherit;
}
*/
</style>
<script> <script>
var arrayReturn = [];
var arrayReturn = [];
/*$.ajax({
url: "http://jsonplaceholder.typicode.com/posts",
async: true,
dataType: 'json',
success: function (data) {
for (var i = 0, len = data.length; i < len; i++) {
var desc = data[i].body;
arrayReturn.push([ data[i].userId, '<a href="http://google.com" target="_blank">'+data[i].title+'</a>', desc.substring(0, 12)]);
}
alert('loaded ' + data.length);
inittable(arrayReturn);
}
});
function inittable(data) {
//console.log(data);
$('#photos').DataTable( {
"aaData": data
} );
}*/
</script> </script>
<?php <?php
$PAGE->requires->js_call_amd('block_fale_conosco/config', 'init'); $PAGE->requires->js_call_amd('block_fale_conosco/config', 'init');
//$PAGE->requires->js_call_amd('block_fale_conosco/config', 'getTableContacts'); $PAGE->requires->js_call_amd('block_fale_conosco/config', 'getTableContacts');
?> ?>
<div id="tabs"> <div id="tabs">
@ -163,14 +67,15 @@ if ($mform->is_cancelled()) {
<thead> <thead>
<tr> <tr>
<th>ID</th> <th>ID</th>
<th>Usuário</th> <th>Assunto</th>
<th>E-mail</th> <th>CPF</th>
</tr> </tr>
</thead> </thead>
</table> </table>
</div> </div>
<div id="tabs-2"> <div id="tabs-2">
<div id="mensagens"></div> <div id="mensagens"></div>
</table>
</div> </div>
</div> </div>

64
proxy.php

@ -1,44 +1,52 @@
<?php <?php
include('httpful.phar'); include('httpful.phar');
require_once("../../config.php");
header("Content-Type: application/json"); header("Content-Type: application/json");
if(isset($_GET["contactID"])) { if(isset($_GET["conversationID"])) {
$uri = 'https://escolamodelows.interlegis.leg.br/api/v1/fale_conosco/mensagens_conversa'; $id = intval($_GET['conversationID']);
$uri = 'https://escolamodelows.interlegis.leg.br/api/v1/fale_conosco/mensagens';
$response = \Httpful\Request::post($uri) $response = \Httpful\Request::post($uri)
->sendsJson() ->sendsJson()
->body('{"conversation_id": "1"}') ->body('{"conversation_id": "' . $id . '"}')
//->expectsJson()
->send(); ->send();
} elseif(isset($_REQUEST["addMessage"])) { } elseif(isset($_REQUEST["addMessage"])) {
$id = intval($_GET['addMessage']);
$cpf = $USER->username;
$description = $_GET['description'];
// ***Pega o contexto do curso e verifica o papel do usuário
// $cContext = context_course::instance(3);
// $isStudent = current(get_user_roles($cContext, $USER->id))->shortname =='student'? 'true' : 'false';
// ***Verifica se o usuário assume o papel de estudante em algum curso
// $isStudent = user_has_role_assignment($USER->id, 5);
$uri = 'https://escolamodelows.interlegis.leg.br/api/v1/fale_conosco/adicionar'; $uri = 'https://escolamodelows.interlegis.leg.br/api/v1/fale_conosco/adicionar';
$response = \Httpful\Request::post($uri) $response = \Httpful\Request::post($uri)
->sendsJson() ->sendsJson()
->body('{ ->body('{
"name": "Matheus", "name": "' . $USER->username . '",
"email": "garcia.figueiredo@gmail.com", "email": "' . $USER->email . '",
"cpf": "05272886674", "cpf": "' . $cpf . '",
"description": "Palmeiras nunca vai ganhar um mundial", "description": "' . $description . '",
"date": "2018-08-01", "is_student": false,
"course_id": "1", "conversation_id": "' . $id . '"
"course_category_id": "1" , }')
"school_initials": "SSL",
"id_conversation": "1"
}')
->send(); ->send();
} } elseif(isset($_REQUEST["schoolInitials"])) {
else { $not_answered = intval($_GET['answered'])== 0 ? 'false':'true';
$uri = 'https://escolamodelows.interlegis.leg.br/api/v1/fale_conosco/conversa'; $not_answered = trim($not_answered, '"');
$response = \Httpful\Request::post($uri) $uri = 'https://escolamodelows.interlegis.leg.br/api/v1/fale_conosco/conversa';
->sendsJson() $response = \Httpful\Request::post($uri)
->body( ->sendsJson()
'{ ->body(
"school_initials": "SSL", '{
"page" : "1", "school_initials": "SSL",
"limit": "10" "page" : "1",
}' "limit": "2000",
) "not_answered": '. $not_answered .'
//->expectsJson() }')
->send(); ->send();
} }

32
searchform.php

@ -1,22 +1,22 @@
<?php <?php
require_once("$CFG->libdir/formslib.php"); require_once("$CFG->libdir/formslib.php");
class searchform extends moodleform { class searchform extends moodleform {
function definition() {
function definition() { global $CFG;
global $CFG;
$mform = $this->_form; // Don't forget the underscore!
$mform = $this->_form; // Don't forget the underscore!
$attributes=array('size'=>'20');
$attributes=array('size'=>'20'); $selSituacao = $mform->addElement('select', 'situacao', get_string('situacao', 'block_fale_conosco'),
$selSituacao = $mform->addElement('select', 'situacao', get_string('situacao', 'block_fale_conosco'), array('Não respondidas', 'Respondidas'), $attributes);
array('Não respondidas', 'Respondidas', 'Pendentes'), $attributes);
$selSituacao->setMultiple(false); $selSituacao->setMultiple(false);
$attributes=array('size'=>'20'); $attributes=array('size'=>'20');
$txtUsuario = $mform->addElement('text', 'usuario', get_string('usuario', 'block_fale_conosco'), $attributes); // $txtUsuario = $mform->addElement('text', 'usuario', get_string('usuario', 'block_fale_conosco'), $attributes);
// $mform->addElement('button', 'Atualizar', get_string("atualizar", "block_fale_conosco"));
$mform->addElement('button', 'Atualizar', get_string("atualizar", "block_fale_conosco")); }
} }
}

Loading…
Cancel
Save