From 2c57defbbeea8879e78260a8ca828b16b46ee933 Mon Sep 17 00:00:00 2001 From: Everton Muniz Date: Mon, 4 Jun 2018 22:32:37 -0300 Subject: [PATCH 1/8] Corrige problema no encoding obtendo slug da string --- composer.json | 3 ++- .../modules/Avaliacao/Views/DiarioApiController.php | 12 ++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index e6ba15e214..b4826380d8 100644 --- a/composer.json +++ b/composer.json @@ -9,6 +9,7 @@ "require": { "portabilis/jasperphp": "v1.2.0", "robmorgan/phinx": "v0.8.1", - "gilbitron/php-simplecache": "^1.4" + "gilbitron/php-simplecache": "^1.4", + "cocur/slugify": "^3.1" } } diff --git a/ieducar/modules/Avaliacao/Views/DiarioApiController.php b/ieducar/modules/Avaliacao/Views/DiarioApiController.php index 6c961e5f8f..74f30c0e96 100644 --- a/ieducar/modules/Avaliacao/Views/DiarioApiController.php +++ b/ieducar/modules/Avaliacao/Views/DiarioApiController.php @@ -1,5 +1,7 @@ getRequest()->turma_id; $situacoes = $this->getSituacaoComponentes(); + + $slugify = new Slugify(); + foreach ($_componentesCurriculares as $_componente) { $componente = array(); $componenteId = $_componente->get('id'); @@ -1204,8 +1212,8 @@ protected function loadComponentesCurricularesForMatricula($matriculaId, $turmaI //criando chave para ordenamento temporário //área de conhecimento + componente curricular - $componente['ordem_nome_area_conhecimento'] = strtr($nomeArea, "áàãâéêíóôõúüçÁÀÃÂÉÊÍÓÔÕÚÜÇ", "aaaaeeiooouucAAAAEEIOOOUUC"); - $componente['ordem_componente_curricular'] = strtr(($_componente->get('nome')), "áàãâéêíóôõúüçÁÀÃÂÉÊÍÓÔÕÚÜÇ", "aaaaeeiooouucAAAAEEIOOOUUC"); + $componente['ordem_nome_area_conhecimento'] = $slugify->slugify($nomeArea); + $componente['ordem_componente_curricular'] = $slugify->slugify($_componente->get('nome')); $componentesCurriculares[] = $componente; } From 9d812c369cb148884950cef85c8b5097c4989b46 Mon Sep 17 00:00:00 2001 From: bonot Date: Tue, 5 Jun 2018 09:35:27 -0300 Subject: [PATCH 2/8] Trata booleano que vem do banco --- ieducar/modules/Api/Views/EducacensoAnaliseController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ieducar/modules/Api/Views/EducacensoAnaliseController.php b/ieducar/modules/Api/Views/EducacensoAnaliseController.php index 6d33d6320b..914857f0b4 100644 --- a/ieducar/modules/Api/Views/EducacensoAnaliseController.php +++ b/ieducar/modules/Api/Views/EducacensoAnaliseController.php @@ -1221,7 +1221,7 @@ protected function analisaEducacensoRegistro60() { "linkPath" => "/intranet/public_municipio_cad.php?idmun={$codMunicipio}", "fail" => true); } - if ($aluno["possui_deficiencia"] && empty($aluno["recursos_prova_inep"])) { + if (dbBool($aluno["possui_deficiencia"]) && empty($aluno["recursos_prova_inep"])) { $mensagem[] = array("text" => "Aviso! Dados para formular o registro 60 da escola {$nomeEscola} não encontrados. Verificamos que o(a) aluno(a) {$nomeAluno} possui uma(s) deficiência(s), porém nenhum recurso para a prova INEP foi selecionado.", "path" => "(Escola > Cadastros > Alunos > Cadastrar > Editar > Aba: Dados educacenso > Campo: Recursos prova INEP)", "linkPath" => "/module/Cadastro/aluno?id={$codAluno}", From 74da51fe889d591a161f1d70a97fb21bdeabd9e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89ber=20Freitas=20Dias?= Date: Tue, 5 Jun 2018 11:08:29 -0300 Subject: [PATCH 3/8] Atualiza lock do composer; Refs #encoding-fix --- composer.lock | 197 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 160 insertions(+), 37 deletions(-) diff --git a/composer.lock b/composer.lock index 3054a978cc..27fbbc10fe 100644 --- a/composer.lock +++ b/composer.lock @@ -1,11 +1,76 @@ { "_readme": [ "This file locks the dependencies of your project to a known state", - "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "54fd5e2dc075b55d008b31c2cdc6776e", + "content-hash": "ceda83eeb3051ebd372f452e2fa30a93", "packages": [ + { + "name": "cocur/slugify", + "version": "v3.1", + "source": { + "type": "git", + "url": "https://github.com/cocur/slugify.git", + "reference": "b2ccf7b735f4f3df3979aef2e1ebf8e19ca772f7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/cocur/slugify/zipball/b2ccf7b735f4f3df3979aef2e1ebf8e19ca772f7", + "reference": "b2ccf7b735f4f3df3979aef2e1ebf8e19ca772f7", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=5.5.9" + }, + "require-dev": { + "laravel/framework": "~5.1", + "latte/latte": "~2.2", + "league/container": "^2.2.0", + "mikey179/vfsstream": "~1.6", + "mockery/mockery": "~0.9", + "nette/di": "~2.2", + "phpunit/phpunit": "~4.8|~5.2", + "pimple/pimple": "~1.1", + "plumphp/plum": "~0.1", + "silex/silex": "~1.3", + "symfony/config": "~2.4|~3.0", + "symfony/dependency-injection": "~2.4|~3.0", + "symfony/http-kernel": "~2.4|~3.0", + "twig/twig": "~1.26|~2.0", + "zendframework/zend-modulemanager": "~2.2", + "zendframework/zend-servicemanager": "~2.2", + "zendframework/zend-view": "~2.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "Cocur\\Slugify\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ivo Bathke", + "email": "ivo.bathke@gmail.com" + }, + { + "name": "Florian Eckerstorfer", + "email": "florian@eckerstorfer.co", + "homepage": "https://florian.ec" + } + ], + "description": "Converts a string into a slug.", + "keywords": [ + "slug", + "slugify" + ], + "time": "2018-01-22T09:00:48+00:00" + }, { "name": "gilbitron/php-simplecache", "version": "1.4.2", @@ -204,21 +269,22 @@ }, { "name": "symfony/config", - "version": "v3.4.8", + "version": "v3.4.11", "source": { "type": "git", "url": "https://github.com/symfony/config.git", - "reference": "7c2a9d44f4433863e9bca682e7f03609234657f9" + "reference": "73e055cf2e6467715f187724a0347ea32079967c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/config/zipball/7c2a9d44f4433863e9bca682e7f03609234657f9", - "reference": "7c2a9d44f4433863e9bca682e7f03609234657f9", + "url": "https://api.github.com/repos/symfony/config/zipball/73e055cf2e6467715f187724a0347ea32079967c", + "reference": "73e055cf2e6467715f187724a0347ea32079967c", "shasum": "" }, "require": { "php": "^5.5.9|>=7.0.8", - "symfony/filesystem": "~2.8|~3.0|~4.0" + "symfony/filesystem": "~2.8|~3.0|~4.0", + "symfony/polyfill-ctype": "~1.8" }, "conflict": { "symfony/dependency-injection": "<3.3", @@ -263,20 +329,20 @@ ], "description": "Symfony Config Component", "homepage": "https://symfony.com", - "time": "2018-03-19T22:32:39+00:00" + "time": "2018-05-14T16:49:53+00:00" }, { "name": "symfony/console", - "version": "v3.4.8", + "version": "v3.4.11", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "d4bb70fa24d540c309d88a9d6e43fb2d339b1fbf" + "reference": "36f83f642443c46f3cf751d4d2ee5d047d757a27" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/d4bb70fa24d540c309d88a9d6e43fb2d339b1fbf", - "reference": "d4bb70fa24d540c309d88a9d6e43fb2d339b1fbf", + "url": "https://api.github.com/repos/symfony/console/zipball/36f83f642443c46f3cf751d4d2ee5d047d757a27", + "reference": "36f83f642443c46f3cf751d4d2ee5d047d757a27", "shasum": "" }, "require": { @@ -297,7 +363,7 @@ "symfony/process": "~3.3|~4.0" }, "suggest": { - "psr/log": "For using the console logger", + "psr/log-implementation": "For using the console logger", "symfony/event-dispatcher": "", "symfony/lock": "", "symfony/process": "" @@ -332,20 +398,20 @@ ], "description": "Symfony Console Component", "homepage": "https://symfony.com", - "time": "2018-04-03T05:22:50+00:00" + "time": "2018-05-16T08:49:21+00:00" }, { "name": "symfony/debug", - "version": "v3.4.8", + "version": "v3.4.11", "source": { "type": "git", "url": "https://github.com/symfony/debug.git", - "reference": "9cf7c2271cfb89ef9727db1b740ca77be57bf9d7" + "reference": "b28fd73fefbac341f673f5efd707d539d6a19f68" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/debug/zipball/9cf7c2271cfb89ef9727db1b740ca77be57bf9d7", - "reference": "9cf7c2271cfb89ef9727db1b740ca77be57bf9d7", + "url": "https://api.github.com/repos/symfony/debug/zipball/b28fd73fefbac341f673f5efd707d539d6a19f68", + "reference": "b28fd73fefbac341f673f5efd707d539d6a19f68", "shasum": "" }, "require": { @@ -388,24 +454,25 @@ ], "description": "Symfony Debug Component", "homepage": "https://symfony.com", - "time": "2018-04-03T05:22:50+00:00" + "time": "2018-05-16T14:03:39+00:00" }, { "name": "symfony/filesystem", - "version": "v3.4.8", + "version": "v3.4.11", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", - "reference": "253a4490b528597aa14d2bf5aeded6f5e5e4a541" + "reference": "8e03ca3fa52a0f56b87506f38cf7bd3f9442b3a0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/filesystem/zipball/253a4490b528597aa14d2bf5aeded6f5e5e4a541", - "reference": "253a4490b528597aa14d2bf5aeded6f5e5e4a541", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/8e03ca3fa52a0f56b87506f38cf7bd3f9442b3a0", + "reference": "8e03ca3fa52a0f56b87506f38cf7bd3f9442b3a0", "shasum": "" }, "require": { - "php": "^5.5.9|>=7.0.8" + "php": "^5.5.9|>=7.0.8", + "symfony/polyfill-ctype": "~1.8" }, "type": "library", "extra": { @@ -437,20 +504,75 @@ ], "description": "Symfony Filesystem Component", "homepage": "https://symfony.com", - "time": "2018-02-22T10:48:49+00:00" + "time": "2018-05-16T08:49:21+00:00" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.8.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "7cc359f1b7b80fc25ed7796be7d96adc9b354bae" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/7cc359f1b7b80fc25ed7796be7d96adc9b354bae", + "reference": "7cc359f1b7b80fc25ed7796be7d96adc9b354bae", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + }, + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "time": "2018-04-30T19:57:29+00:00" }, { "name": "symfony/polyfill-mbstring", - "version": "v1.7.0", + "version": "v1.8.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "78be803ce01e55d3491c1397cf1c64beb9c1b63b" + "reference": "3296adf6a6454a050679cde90f95350ad604b171" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/78be803ce01e55d3491c1397cf1c64beb9c1b63b", - "reference": "78be803ce01e55d3491c1397cf1c64beb9c1b63b", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/3296adf6a6454a050679cde90f95350ad604b171", + "reference": "3296adf6a6454a050679cde90f95350ad604b171", "shasum": "" }, "require": { @@ -462,7 +584,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.7-dev" + "dev-master": "1.8-dev" } }, "autoload": { @@ -496,24 +618,25 @@ "portable", "shim" ], - "time": "2018-01-30T19:27:44+00:00" + "time": "2018-04-26T10:06:28+00:00" }, { "name": "symfony/yaml", - "version": "v3.4.8", + "version": "v3.4.11", "source": { "type": "git", "url": "https://github.com/symfony/yaml.git", - "reference": "a42f9da85c7c38d59f5e53f076fe81a091f894d0" + "reference": "c5010cc1692ce1fa328b1fb666961eb3d4a85bb0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/yaml/zipball/a42f9da85c7c38d59f5e53f076fe81a091f894d0", - "reference": "a42f9da85c7c38d59f5e53f076fe81a091f894d0", + "url": "https://api.github.com/repos/symfony/yaml/zipball/c5010cc1692ce1fa328b1fb666961eb3d4a85bb0", + "reference": "c5010cc1692ce1fa328b1fb666961eb3d4a85bb0", "shasum": "" }, "require": { - "php": "^5.5.9|>=7.0.8" + "php": "^5.5.9|>=7.0.8", + "symfony/polyfill-ctype": "~1.8" }, "conflict": { "symfony/console": "<3.4" @@ -554,7 +677,7 @@ ], "description": "Symfony Yaml Component", "homepage": "https://symfony.com", - "time": "2018-04-03T05:14:20+00:00" + "time": "2018-05-03T23:18:14+00:00" } ], "packages-dev": [], From f73b49be309cb0f633831deb83dfac80728fca40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89ber=20Freitas=20Dias?= Date: Tue, 5 Jun 2018 11:08:46 -0300 Subject: [PATCH 4/8] Criando classe para lidar com JSON; Refs #encoding-fix --- ieducar/lib/Utils/SafeJson.php | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 ieducar/lib/Utils/SafeJson.php diff --git a/ieducar/lib/Utils/SafeJson.php b/ieducar/lib/Utils/SafeJson.php new file mode 100644 index 0000000000..e820afb20b --- /dev/null +++ b/ieducar/lib/Utils/SafeJson.php @@ -0,0 +1,23 @@ + Date: Tue, 5 Jun 2018 11:09:22 -0300 Subject: [PATCH 5/8] =?UTF-8?q?Modificando=20c=C3=B3digo=20para=20usar=20S?= =?UTF-8?q?afeJson;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #encoding-fix --- .../modules/clsModulesAuditoriaGeral.inc.php | 3 +- .../clsPmieducarConfiguracoesGerais.inc.php | 3 +- .../Controller/ApiCoreController.php | 5 +- .../Input/Resource/MultipleSearchCustom.php | 5 +- .../Input/Resource/MultipleSearchSerie.php | 3 +- .../Views/ProcessamentoApiController.php | 2307 +++++++++-------- 6 files changed, 1166 insertions(+), 1160 deletions(-) diff --git a/ieducar/intranet/include/modules/clsModulesAuditoriaGeral.inc.php b/ieducar/intranet/include/modules/clsModulesAuditoriaGeral.inc.php index 9f8bcbcb18..de388ee609 100644 --- a/ieducar/intranet/include/modules/clsModulesAuditoriaGeral.inc.php +++ b/ieducar/intranet/include/modules/clsModulesAuditoriaGeral.inc.php @@ -29,6 +29,7 @@ */ require_once 'include/pmieducar/geral.inc.php'; +require_once 'lib/Utils/SafeJson.php'; /** * clsModulesAuditoriaGeral class. @@ -108,7 +109,7 @@ function removeKeysDesnecessarias($dados) { function converteArrayDadosParaJson($dados) { $dados = $this->removeKeyNaoNumerica($dados); $dados = $this->removeKeysDesnecessarias($dados); - $dados = json_encode($dados); + $dados = SafeJson::encode($dados); $dados = str_replace("'", "''", $dados); return $dados; } diff --git a/ieducar/intranet/include/pmieducar/clsPmieducarConfiguracoesGerais.inc.php b/ieducar/intranet/include/pmieducar/clsPmieducarConfiguracoesGerais.inc.php index b7610f6378..23f2c4d318 100644 --- a/ieducar/intranet/include/pmieducar/clsPmieducarConfiguracoesGerais.inc.php +++ b/ieducar/intranet/include/pmieducar/clsPmieducarConfiguracoesGerais.inc.php @@ -29,6 +29,7 @@ */ require_once 'include/pmieducar/geral.inc.php'; +require_once 'lib/Utils/SafeJson.php'; /** * clsPmieducarConfiguracoesGerais class. @@ -234,7 +235,7 @@ function edita() } if (is_array($this->custom_labels)) { - $customLabels = json_encode($this->custom_labels); + $customLabels = SafeJson::encode($this->custom_labels); $set[] = "custom_labels = '{$customLabels}'"; } diff --git a/ieducar/lib/Portabilis/Controller/ApiCoreController.php b/ieducar/lib/Portabilis/Controller/ApiCoreController.php index 3c32fe9a32..abb073ad73 100644 --- a/ieducar/lib/Portabilis/Controller/ApiCoreController.php +++ b/ieducar/lib/Portabilis/Controller/ApiCoreController.php @@ -44,6 +44,7 @@ require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; require_once 'lib/Portabilis/Utils/User.php'; +require_once 'lib/Utils/SafeJson.php'; class ApiCoreController extends Core_Controller_Page_EditController { @@ -255,14 +256,14 @@ protected function prepareResponse(){ $this->appendResponse('msgs', $this->messenger->getMsgs()); $this->appendResponse('any_error_msg', $this->messenger->hasMsgWithType('error')); - $response = json_encode($this->response); + $response = SafeJson::encode($this->response); } catch (Exception $e){ error_log("Erro inesperado no metodo prepareResponse da classe ApiCoreController: {$e->getMessage()}"); $response = array('msgs' => array('msg' => 'Erro inesperado no servidor. Por favor, tente novamente.', 'type' => 'error')); - $response = json_encode($response); + $response = SafeJson::encode($response); } echo $response; diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCustom.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCustom.php index 66e3dd6aff..38200da866 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCustom.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCustom.php @@ -32,6 +32,7 @@ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; +require_once 'lib/Utils/SafeJson.php'; /** * Portabilis_View_Helper_Input_MultipleSearchCustom class. @@ -64,7 +65,7 @@ protected function placeholderJs($options) { $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; $optionsVarName.placeholder = safeUtf8Decode('Selecione');"; - $json = json_encode($options['options']['options']['values']); + $json = SafeJson::encode($options['options']['options']['values']); $js .= 'arrayOptions.push({element : $j("#'. $options['objectName'] .'"),values : '. $json .'})'; @@ -77,4 +78,4 @@ protected function loadAssets() { $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/MultipleSearchCustom.js'; Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); } -} \ No newline at end of file +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchSerie.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchSerie.php index ecf3eb9108..bce072302e 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchSerie.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchSerie.php @@ -3,6 +3,7 @@ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; +require_once 'lib/Utils/SafeJson.php'; class Portabilis_View_Helper_Input_Resource_MultipleSearchSerie extends Portabilis_View_Helper_Input_MultipleSearch { @@ -28,7 +29,7 @@ protected function placeholderJs($options) { $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; $optionsVarName.placeholder = safeUtf8Decode('Selecione');"; - $json = json_encode($options['options']['values']); + $json = SafeJson::encode($options['options']['values']); $js .= 'arrayOptions.push({element : $j("#'. $options['objectName'] . "_serie-". $options['options']['coluna'] .'"),values : '. $json .'})'; diff --git a/ieducar/modules/HistoricoEscolar/Views/ProcessamentoApiController.php b/ieducar/modules/HistoricoEscolar/Views/ProcessamentoApiController.php index e12a39ff70..c1a29fdb73 100644 --- a/ieducar/modules/HistoricoEscolar/Views/ProcessamentoApiController.php +++ b/ieducar/modules/HistoricoEscolar/Views/ProcessamentoApiController.php @@ -1,1153 +1,1154 @@ -appendMsg($msg); - } - - if ($raiseExceptionOnEmpty) { - throw new Exception($msg); - } - - return false; - } - return true; - } - - protected function validatesValueIsNumeric(&$value, $name, $raiseExceptionOnError = false, $msg = '', $addMsgOnError = true) - { - if (!is_numeric($value)) { - if ($addMsgOnError) { - $msg = empty($msg) ? "O valor recebido para variavel '$name' deve ser numerico" : $msg; - $this->appendMsg($msg); - } - - if ($raiseExceptionOnError) { - throw new Exception($msg); - } - - return false; - } - return true; - } - - protected function validatesValueIsArray(&$value, $name, $raiseExceptionOnError = false, $msg = '', $addMsgOnError = true) - { - - if (!is_array($value)) { - if ($addMsgOnError) { - $msg = empty($msg) ? "Deve ser recebido uma lista de '$name'" : $msg; - $this->appendMsg($msg); - } - - if ($raiseExceptionOnError) { - throw new Exception($msg); - } - - return false; - } - return true; - } - - protected function validatesValueInSetOf(&$value, $setExpectedValues, $name, $raiseExceptionOnError = false, $msg = '') - { - if (!in_array($value, $setExpectedValues)) { - $msg = empty($msg) ? "Valor recebido na variavel '$name' é invalido" : $msg; - $this->appendMsg($msg); - - if ($raiseExceptionOnError) { - throw new Exception($msg); - } - - return false; - } - return true; - } - - - protected function requiresLogin($raiseExceptionOnEmpty) - { - return $this->validatesPresenceOf($this->getSession()->id_pessoa, '', $raiseExceptionOnEmpty, 'Usuário deve estar logado'); - } - - protected function validatesPresenceOfInstituicaoId($raiseExceptionOnEmpty) - { - return $this->validatesPresenceOf($this->getRequest()->instituicao_id, 'instituicao_id', $raiseExceptionOnEmpty); - } - - protected function validatesPresenceOfEscolaId($raiseExceptionOnEmpty) - { - return $this->validatesPresenceOf($this->getRequest()->escola_id, 'escola_id', $raiseExceptionOnEmpty); - } - - protected function validatesPresenceOfCursoId($raiseExceptionOnEmpty) - { - return $this->validatesPresenceOf($this->getRequest()->curso_id, 'curso_id', $raiseExceptionOnEmpty); - } - - protected function validatesPresenceOfSerieId($raiseExceptionOnEmpty, $addMsgOnEmpty = true) - { - return $this->validatesPresenceOf($this->getRequest()->serie_id, 'serie_id', $raiseExceptionOnEmpty, '', $addMsgOnEmpty); - } - - protected function validatesPresenceOfAno($raiseExceptionOnEmpty) - { - return $this->validatesPresenceOf($this->getRequest()->ano, 'ano', $raiseExceptionOnEmpty); - } - - protected function validatesPresenceOfMatriculaId($raiseExceptionOnEmpty) - { - return $this->validatesPresenceOf($this->getRequest()->matricula_id, 'matricula_id', $raiseExceptionOnEmpty); - } - - protected function validatesValueIsInBd($fieldName, &$value, $schemaName, $tableName, $raiseExceptionOnError = true) - { - $sql = "select 1 from $schemaName.$tableName where $fieldName = $1"; - $isValid = Portabilis_Utils_DataBase::selectField($sql, $value) == '1'; - - if (!$isValid) { - $msg = "O valor informado {$value} para $tableName, não esta presente no banco de dados."; - $this->appendMsg($msg); - - if ($raiseExceptionOnError) { - throw new Exception($msg); - } - - return false; - } - - return true; - } - - protected function validatesPresenceAndValueInDbOfGradeCursoId($raiseExceptionOnError) - { - return $this->validatesPresenceOf($this->getRequest()->grade_curso_id, 'grade_curso_id', $raiseExceptionOnError) && - $this->validatesValueIsInBd('id', $this->getRequest()->grade_curso_id, 'pmieducar', 'historico_grade_curso', $raiseExceptionOnError); - } - - protected function validatesPresenceOfDiasLetivos($raiseExceptionOnEmpty) - { - return $this->validatesPresenceOf($this->getRequest()->dias_letivos, 'dias_letivos', $raiseExceptionOnEmpty); - } - - protected function validatesValueOfAttValueIsNumeric($raiseExceptionOnError) - { - return $this->validatesValueIsNumeric($this->getRequest()->att_value, 'att_value', $raiseExceptionOnError); - } - - protected function validatesPresenceOfAttValue($raiseExceptionOnEmpty) - { - return $this->validatesPresenceOf($this->getRequest()->att_value, 'att_value', $raiseExceptionOnEmpty); - } - - - protected function validatesPresenceAndValueInSetOfAtt($raiseExceptionOnError) - { - $result = $this->validatesPresenceOf($this->getRequest()->att, 'att', $raiseExceptionOnError); - - if ($result) { - $expectedAtts = array('matriculas', 'processamento', 'historico'); - $result = $this->validatesValueInSetOf($this->getRequest()->att, $expectedAtts, 'att', $raiseExceptionOnError); - } - return $result; - } - - - protected function validatesPresenceAndValueInSetOfOper($raiseExceptionOnError) - { - $result = $this->validatesPresenceOf($this->getRequest()->oper, 'oper', $raiseExceptionOnError); - - if ($result) { - $expectedOpers = array('post', 'get', 'delete'); - $result = $this->validatesValueInSetOf($this->getRequest()->oper, $expectedOpers, 'oper', $raiseExceptionOnError); - } - return $result; - } - - - protected function validatesPresenceAndValueInSetOfExtraCurricular($raiseExceptionOnError) - { - $result = $this->validatesPresenceOf($this->getRequest()->extra_curricular, 'extra_curricular', $raiseExceptionOnError); - - if ($result) { - $expectedOpers = array(0, 1); - $result = $this->validatesValueInSetOf($this->getRequest()->extra_curricular, $expectedOpers, 'extra_curricular', $raiseExceptionOnError); - } - return $result; - } - - protected function validatesPresenceAndValueOfPercentualFrequencia($raiseExceptionOnError) - { - $name = 'percentual_frequencia'; - $isValid = $this->validatesPresenceOf($this->getRequest()->percentual_frequencia, $name, $raiseExceptionOnError); - - if ($isValid && $this->getRequest()->percentual_frequencia != 'buscar-boletim') { - $isValid = $this->validatesValueIsNumeric($this->getRequest()->percentual_frequencia, $name, $raiseExceptionOnError); - } - - return $isValid; - } - - protected function validatesPresenceOfNotas($raiseExceptionOnError) - { - return $this->validatesPresenceOf($this->getRequest()->notas, 'notas', $raiseExceptionOnError); - } - - protected function validatesPresenceAndValueOfFaltas($raiseExceptionOnError) - { - $name = 'faltas'; - $isValid = $this->validatesPresenceOf($this->getRequest()->faltas, $name, $raiseExceptionOnError); - - if ($isValid && $this->getRequest()->faltas != 'buscar-boletim') { - $isValid = $this->validatesValueIsNumeric($this->getRequest()->faltas, $name, $raiseExceptionOnError); - } - - return $isValid; - } - - - protected function validatesPresenceAndValueOfDisciplinas($raiseExceptionOnError) - { - $name = 'disciplinas'; - $isValid = $this->validatesPresenceOf($this->getRequest()->disciplinas, $name, $raiseExceptionOnError); - - if ($isValid && $this->getRequest()->disciplinas != 'buscar-boletim') { - $isValid = $this->validatesValueIsArray($this->getRequest()->disciplinas, 'disciplinas', $raiseExceptionOnError); - if ($isValid) { - foreach ($this->getRequest()->disciplinas as $disciplina) { - $isValid = $this->validatesPresenceOf($disciplina['nome'], 'nome (para todas disciplinas)', $raiseExceptionOnError); - - if ($isValid && isset($disciplina['falta']) && trim($disciplina['falta']) != '') { - $isValid = $this->validatesValueIsNumeric($disciplina['falta'], 'falta (para todas disciplinas)', $raiseExceptionOnError); - } - } - } - } - return $isValid; - } - - protected function validatesPresenceAndValueInSetOfSituacao($raiseExceptionOnError) - { - $name = 'situacao'; - $isValid = $this->validatesPresenceOf($this->getRequest()->situacao, $name, $raiseExceptionOnError); - - if ($isValid) { - $expectedOpers = array('buscar-matricula', 'aprovado', 'reprovado', 'em-andamento', 'transferido'); - $isValid = $this->validatesValueInSetOf($this->getRequest()->situacao, $expectedOpers, $name, $raiseExceptionOnError); - } - - return $isValid; - } - - - /* esta funcao só pode ser chamada após setar $this->getService() */ - protected function validatesPresenceOfComponenteCurricularId($raiseExceptionOnEmpty, $addMsgOnEmpty = true) - { - return $this->validatesPresenceOf($this->getRequest()->componente_curricular_id, 'componente_curricular_id', $raiseExceptionOnEmpty, $msg = '', $addMsgOnEmpty); - } - - - protected function canAcceptRequest() - { - try { - $this->requiresLogin(true); - $this->validatesPresenceAndValueInSetOfAtt(true); - $this->validatesPresenceAndValueInSetOfOper(true); - } catch (Exception $e) { - return false; - } - return true; - } - - - protected function canGetMatriculas() - { - return $this->validatesPresenceOfAno(false) && - $this->validatesPresenceOfInstituicaoId(false) && - $this->validatesPresenceOfEscolaId(false); - } - - - protected function canPostProcessamento() - { - $canPost = $this->validatesPresenceOfInstituicaoId(false) && - $this->validatesPresenceOfMatriculaId(false) && - $this->validatesPresenceOfDiasLetivos(false) && - $this->validatesPresenceAndValueInSetOfSituacao(false) && - $this->validatesPresenceAndValueInSetOfExtraCurricular(false) && - $this->validatesPresenceAndValueInDbOfGradeCursoId(false) && - $this->validatesPresenceAndValueOfPercentualFrequencia(false) && - $this->validatesPresenceAndValueOfDisciplinas(false); - - if ($canPost && $this->getRequest()->disciplinas == 'buscar-boletim') { - $canPost = $this->validatesPresenceOfNotas(false) && $this->validatesPresenceAndValueOfFaltas(false); - } - - if ($canPost) { - $sql = "select 1 from pmieducar.matricula where cod_matricula = $1 and ativo = 1"; - - if (!Portabilis_Utils_Database::selectField($sql, $this->getRequest()->matricula_id)) { - $this->appendMsg("A matricula {$this->getRequest()->matricula_id} não existe ou esta desativa", 'error'); - $canPost = false; - } - } - - if ($canPost) { - $sql = "select 1 from pmieducar.matricula_turma where ref_cod_matricula = $1 and ativo = 1 limit 1"; - - if (!Portabilis_Utils_Database::selectField($sql, $this->getRequest()->matricula_id)) { - $this->appendMsg("A matricula {$this->getRequest()->matricula_id} não está enturmada.", 'error'); - $canPost = false; - } - } - return $canPost && $this->setService(); - } - - - protected function canDeleteHistorico() - { - return $this->validatesPresenceOfInstituicaoId(false) && - $this->validatesPresenceOfMatriculaId(false); - } - - - protected function deleteHistorico() - { - if ($this->canDeleteHistorico()) { - - $matriculaId = $this->getRequest()->matricula_id; - $alunoId = $this->getAlunoIdByMatriculaId($matriculaId); - $dadosMatricula = $this->getdadosMatricula($matriculaId); - $ano = $dadosMatricula['ano']; - - if ($this->existsHistorico($alunoId, $ano, $matriculaId)) { - $sequencial = $this->getSequencial($alunoId, $ano, $matriculaId); - $this->deleteHistoricoDisplinas($alunoId, $sequencial); - - $historicoEscolar = new clsPmieducarHistoricoEscolar( - $ref_cod_aluno = $alunoId, - $sequencial, - $ref_usuario_exc = $this->getSession()->id_pessoa, - $ref_usuario_cad = null, - //TODO nm_curso - $nm_serie = null, - $ano = $ano, - $carga_horaria = null, - $dias_letivos = null, - $escola = null, - $escola_cidade = null, - $escola_uf = null, - $observacao = null, - $aprovado = null, - $data_cadastro = null, - $data_exclusao = date('Y-m-d'), - $ativo = 0 - ); - $historicoEscolar->edita(); - - $this->appendMsg('Histórico escolar removido com sucesso', 'success'); - } else { - $this->appendMsg("Histórico matricula $matriculaId inexistente ou já removido", 'notice'); - } - - $situacaoHistorico = $this->getSituacaoHistorico($alunoId, $ano, $matriculaId, $reload = true); - - $this->appendResponse('situacao_historico', $situacaoHistorico); - $this->appendResponse('link_to_historico', ''); - } - } - - protected function deleteHistoricoDisplinas($alunoId, $historicoSequencial) - { - $historicoDisciplinas = new clsPmieducarHistoricoDisciplinas(); - $historicoDisciplinas->excluirTodos($alunoId, $historicoSequencial); - } - - - protected function getdadosEscola($escolaId) - { - $sql = "select - (select pes.nome from pmieducar.escola esc, cadastro.pessoa pes - where esc.ref_cod_instituicao = $1 and esc.cod_escola = $2 - and pes.idpes = esc.ref_idpes) as nome, - - (select coalesce((select coalesce((select municipio.nome from public.municipio, - cadastro.endereco_pessoa, cadastro.juridica, public.bairro, pmieducar.escola - where endereco_pessoa.idbai = bairro.idbai and bairro.idmun = municipio.idmun and - juridica.idpes = endereco_pessoa.idpes and juridica.idpes = escola.ref_idpes and - escola.cod_escola = $2),(select endereco_externo.cidade from cadastro.endereco_externo, - pmieducar.escola where endereco_externo.idpes = escola.ref_idpes and escola.cod_escola = $2))), - (select municipio from pmieducar.escola_complemento where ref_cod_escola = $2))) as cidade, - - (select coalesce((select coalesce((select municipio.sigla_uf from public.municipio, - cadastro.endereco_pessoa, cadastro.juridica, public.bairro, pmieducar.escola - where endereco_pessoa.idbai = bairro.idbai and bairro.idmun = municipio.idmun and - juridica.idpes = endereco_pessoa.idpes and juridica.idpes = escola.ref_idpes and - escola.cod_escola = $2),(select endereco_externo.sigla_uf from cadastro.endereco_externo, - pmieducar.escola where endereco_externo.idpes = escola.ref_idpes and escola.cod_escola = $2))), - (select inst.ref_sigla_uf from pmieducar.instituicao inst where inst.cod_instituicao = $1))) as uf"; - - $params = array('params' => array($this->getrequest()->instituicao_id, $escolaId), 'return_only' => 'first-line'); - return Portabilis_Utils_Database::fetchPreparedQuery($sql, $params); - } - - - protected function getNextHistoricoSequencial($alunoId) - { - //A consulta leva em consideração historicos inativos pois o sequencial é chave composta com ref_cod_aluno id - $sql = "select coalesce(max(sequencial), 0) + 1 from pmieducar.historico_escolar where ref_cod_aluno = $1"; - - return Portabilis_Utils_Database::selectField($sql, $alunoId); - } - - - protected function getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId) - { - $sql = "select coalesce(max(sequencial), 0) + 1 from pmieducar.historico_disciplinas where - ref_sequencial = $1 and ref_ref_cod_aluno = $2"; - - return Portabilis_Utils_Database::selectField($sql, array($historicoSequencial, $alunoId)); - } - - - protected function getSituacaoMatricula($matriculaId = null) - { - if (!is_null($matriculaId)) { - - if (!is_null($this->getService(false, false))) { - $situacao = $this->getService()->getOption('aprovado'); - } else { - $sql = "select aprovado from pmieducar.matricula where cod_matricula = $1"; - $situacao = Portabilis_Utils_Database::selectField($sql, $matriculaId); - } - - } else if ($this->getRequest()->situacao == 'buscar-matricula') { - $situacao = $this->getService()->getOption('aprovado'); - } else { - $situacoes = array( - 'aprovado' => App_Model_MatriculaSituacao::APROVADO, - 'reprovado' => App_Model_MatriculaSituacao::REPROVADO, - 'em-andamento' => App_Model_MatriculaSituacao::EM_ANDAMENTO, - 'transferido' => App_Model_MatriculaSituacao::TRANSFERIDO - ); - $situacao = $situacoes[$this->getRequest()->situacao]; - } - return $situacao; - } - - protected function getPercentualFrequencia() - { - if ($this->getRequest()->percentual_frequencia == 'buscar-boletim') { - $percentual = round($this->getService()->getSituacaoFaltas()->porcentagemPresenca, 2); - } else { - $percentual = $this->getRequest()->percentual_frequencia; - } - return str_replace(',', '.', $percentual); - } - - protected function getFaltaGlobalizada($defaultValue = null) - { - $faltaGeral = $this->getService()->getRegra()->get('tipoPresenca') == RegraAvaliacao_Model_TipoPresenca::GERAL; - - if (! $faltaGeral) { - return $defaultValue; - } - - return $this->getFalta(); - } - - protected function postProcessamento() - { - if ($this->canPostProcessamento()) { - $matriculaId = $this->getRequest()->matricula_id; - - try { - $alunoId = $this->getAlunoIdByMatriculaId($matriculaId); - $dadosMatricula = $this->getdadosMatricula($matriculaId); - $dadosEscola = $this->getdadosEscola($dadosMatricula['escola_id']); - $ano = $dadosMatricula['ano']; - $isNewHistorico = !$this->existsHistorico($alunoId, $ano, $matriculaId); - - if ($isNewHistorico) { - $sequencial = $this->getNextHistoricoSequencial($alunoId); - - $historicoEscolar = new clsPmieducarHistoricoEscolar( - $alunoId, - $sequencial, - $ref_usuario_exc = null, - $ref_usuario_cad = $this->getSession()->id_pessoa, - $dadosMatricula['nome_serie'], - $ano, - $this->getService()->getOption('serieCargaHoraria'), - $this->getRequest()->dias_letivos, - strtoupper($dadosEscola['nome']), - strtoupper($dadosEscola['cidade']), - $dadosEscola['uf'], - $this->getRequest()->observacao, - $this->getSituacaoMatricula(), - $data_cadastro = date('Y-m-d'), - $data_exclusao = null, - $ativo = 1, - $this->getFaltaGlobalizada($defaultValue = 'null'), - $dadosMatricula['instituicao_id'], - $origem = '', //TODO - $this->getRequest()->extra_curricular, - $matriculaId, - $this->getPercentualFrequencia(), - $this->getRequest()->registro, - $this->getRequest()->livro, - $this->getRequest()->folha, - $dadosMatricula['nome_curso'], - $this->getRequest()->grade_curso_id, - null, - $dadosMatricula['escola_id'], - $this->getRequest()->dependencia, - $this->getRequest()->posicao - ); - - $historicoEscolar->cadastra(); - $this->recreateHistoricoDisciplinas($sequencial, $alunoId, $dadosMatricula['turma_id']); - - $this->appendMsg('Histórico processado com sucesso', 'success'); - } else { - - $sequencial = $this->getSequencial($alunoId, $ano, $matriculaId); - - $historicoEscolar = new clsPmieducarHistoricoEscolar( - $alunoId, - $sequencial, - $this->getSession()->id_pessoa, - $ref_usuario_cad = null, - $dadosMatricula['nome_serie'], - $ano, - $this->getService()->getOption('serieCargaHoraria'), - $this->getRequest()->dias_letivos, - strtoupper($dadosEscola['nome']), - strtoupper($dadosEscola['cidade']), - $dadosEscola['uf'], - $this->getRequest()->observacao, - $this->getSituacaoMatricula(), - $data_cadastro = null, - $data_exclusao = null, - $ativo = 1, - $this->getFaltaGlobalizada($defaultValue = 'null'), - $dadosMatricula['instituicao_id'], - $origem = '', //TODO - $this->getRequest()->extra_curricular, - $matriculaId, - $this->getPercentualFrequencia(), - $this->getRequest()->registro, - $this->getRequest()->livro, - $this->getRequest()->folha, - $dadosMatricula['nome_curso'], - $this->getRequest()->grade_curso_id, - null, - $dadosMatricula['escola_id'], - $this->getRequest()->dependencia, - $this->getRequest()->posicao - ); - - $historicoEscolar->edita(); - $this->recreateHistoricoDisciplinas($sequencial, $alunoId, $dadosMatricula['turma_id']); - $this->appendMsg('Histórico reprocessado com sucesso', 'success'); - } - - } catch (Exception $e) { - $this->appendMsg('Erro ao processar histórico, detalhes:' . $e->getMessage(), 'error', true); - } - - $situacaoHistorico = $this->getSituacaoHistorico($alunoId, $ano, $matriculaId, $reload = true); - $linkToHistorico = $this->getLinkToHistorico($alunoId, $ano, $matriculaId); - - $this->appendResponse('situacao_historico', $situacaoHistorico); - $this->appendResponse('link_to_historico', $linkToHistorico); - } - } - - - protected function _createHistoricoDisciplinas($fields) - { - $historicoDisciplina = new clsPmieducarHistoricoDisciplinas( - $fields['sequencial'], - $fields['alunoId'], - $fields['historicoSequencial'], - $fields['nome'], - $fields['nota'], - $fields['falta'], - $fields['ordenamento'], - $fields['carga_horaria_disciplina'], - $fields['dependencia'] - ); - $historicoDisciplina->cadastra(); - } - - protected function shouldProcessAreaConhecimento($areaConhecimento) - { - if (!empty($this->getRequest()->area_conhecimento)) { - return in_array($areaConhecimento, $this->getRequest()->area_conhecimento); - } - return true; - } - - protected function recreateHistoricoDisciplinas($historicoSequencial, $alunoId, $turmaId = null) - { - - $this->deleteHistoricoDisplinas($alunoId, $historicoSequencial); - - if ($this->getRequest()->disciplinas == 'buscar-boletim') { - - $cnsNota = RegraAvaliacao_Model_Nota_TipoValor; - $tpNota = $this->getService()->getRegra()->get('tipoNota'); - $situacaoFaltasCc = $this->getService()->getSituacaoFaltas()->componentesCurriculares; - $mediasCc = $this->getService()->getMediasComponentes(); - $turmaId = $this->getRequest()->turma_id ?: $turmaId; - $mediaAreaConhecimento = $this->getRequest()->media_area_conhecimento; - $processarMediaGeral = $this->getRequest()->processar_media_geral; - - $aprovadoDependencia = $this->getSituacaoMatricula($aluno['ref_cod_matricula']) == 12; - - foreach ($this->getService()->getComponentes() as $componenteCurricular) { - if (!$this->shouldProcessAreaConhecimento($componenteCurricular->get('area_conhecimento'))) { - continue; - } - $ccId = $componenteCurricular->get('id'); - $reprovado = $mediasCc[$ccId][0]->situacao == 2; - $disciplinaDependencia = ($aprovadoDependencia && $reprovado); - $nome = $componenteCurricular->nome; - $ordenamento = $componenteCurricular->ordenamento; - $carga_horaria_disciplina = $componenteCurricular->carga_horaria_disciplina; - $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId); - $nota = ''; - $notaConceitualNumerica = ''; - - if (clsPmieducarTurma::verificaDisciplinaDispensada($turmaId, $ccId)) { - $nota = $this->DISCIPLINA_DISPENSADA; - } elseif ($this->getRequest()->notas == 'buscar-boletim') { - if ($tpNota == $cnsNota::CONCEITUAL) { - if ($GLOBALS['coreExt']['Config']->app->processar_historicos_conceituais == "1") { - $nota = (string)$mediasCc[$ccId][0]->mediaArredondada; - $notaConceitualNumerica = (string)$mediasCc[$ccId][0]->media; - } - } elseif ($tpNota == $cnsNota::NUMERICA) { - $nota = (string)$mediasCc[$ccId][0]->mediaArredondada; - } elseif ($tpNota == $cnsNota::NUMERICACONCEITUAL) { - $nota = (string)$mediasCc[$ccId][0]->mediaArredondada; - $notaConceitualNumerica = (string)$mediasCc[$ccId][0]->media; - } - } else { - $nota = $this->getRequest()->notas; - } - - if (is_numeric($nota)) { - $nota = sprintf("%.1f", $nota); - } - - if ($processarMediaGeral) { - $nota = '-'; - } - - if ($mediaAreaConhecimento) { - $nota = str_replace(',', '.', $nota); - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['nome'] = $componenteCurricular->area_conhecimento->nome; - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['nota'] += $nota; - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['nota_conceitual_numerica'] += $notaConceitualNumerica; - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['falta'] += $this->getFalta($situacaoFaltasCc[$ccId]); - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['ordenamento'] = $componenteCurricular->area_conhecimento->ordenamento; - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['carga_horaria_disciplina'] = $componenteCurricular->area_conhecimento->carga_horaria_disciplina; - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['dependencia'] = $disciplinaDependencia; - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['count']++; - } else { - $this->_createHistoricoDisciplinas( - array( - "sequencial" => $sequencial, - "alunoId" => $alunoId, - "historicoSequencial" => $historicoSequencial, - "nome" => $nome, - "nota" => $nota, - "falta" => $this->getFalta($situacaoFaltasCc[$ccId]), - "ordenamento" => $ordenamento, - "carga_horaria_disciplina" => $carga_horaria_disciplina, - "dependencia" => $disciplinaDependencia - ) - ); - } - } - - if ($mediaAreaConhecimento) { - foreach ($arrayAreaConhecimento as $key => $value) { - - $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId); - - if ($this->getRequest()->notas == 'buscar-boletim') { - $nota = number_format(($value['nota_conceitual_numerica'] / $value['count']), 2, ',', ''); - } - - if ($processarMediaGeral) { - $nota = '-'; - } - - $this->_createHistoricoDisciplinas( - array( - "sequencial" => $sequencial, - "alunoId" => $alunoId, - "historicoSequencial" => $historicoSequencial, - "nome" => $value['nome'], - "nota" => $nota, - "falta" => round($value['falta'] / $value['count']), - "ordenamento" => $value['ordenamento'], - "carga_horaria_disciplina" => $value['carga_horaria_disciplina'], - "dependencia" => $value['dependencia'] - ) - ); - } - } - if ($processarMediaGeral) { - $componentesCurriculares['media_geral'] = $this->insereComponenteMediaGeral($historicoSequencial, $alunoId); - } - } else { - foreach ($this->getRequest()->disciplinas as $disciplina) { - $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId); - - $this->_createHistoricoDisciplinas( - array( - "sequencial" => $sequencial, - "alunoId" => $alunoId, - "historicoSequencial" => $historicoSequencial, - "nome" => $disciplina['nome'], - "nota" => $disciplina['nota'], - "falta" => $falta = $disciplina['falta'], - "ordenamento" => $value['ordenamento'], - "carga_horaria_disciplina" => $value['carga_horaria_disciplina'], - "dependencia" => $value['dependencia'] - ) - ); - } - } - } - - protected function insereComponenteMediaGeral($historicoSequencial, $alunoId) - { - $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId); - $historicoEscolar = new clsPmieducarHistoricoEscolar($alunoId, $historicoSequencial); - - $historicoEscolar->insereComponenteMediaGeral($sequencial); - } - - protected function getFalta($situacaoFaltaComponenteCurricular = null) - { - if ($this->getRequest()->faltas == 'buscar-boletim') { - - $cnsPresenca = RegraAvaliacao_Model_TipoPresenca; - $tpPresenca = $this->getService()->getRegra()->get('tipoPresenca'); - - //retorna '' caso não exista situacaoFalta para o componente curricular, - //como nos casos em que a regra de avaliação muda - if ($tpPresenca == $cnsPresenca::POR_COMPONENTE && !is_null($situacaoFaltaComponenteCurricular)) { - $falta = $situacaoFaltaComponenteCurricular->total; - } elseif ($tpPresenca == $cnsPresenca::POR_COMPONENTE) { - $falta = ''; - } elseif ($tpPresenca == $cnsPresenca::GERAL) { - $falta = $this->getService()->getSituacaoFaltas()->totalFaltas; - } - } else { - $falta = $this->getRequest()->faltas; - } - - return $falta; - } - - protected function getDadosMatricula($matriculaId) - { - $ano = $this->getAnoMatricula($matriculaId); - $sql = "select ref_ref_cod_serie as serie_id, ref_cod_curso as curso_id from pmieducar.matricula - where cod_matricula = $1"; - - $params = array('params' => $matriculaId, 'return_only' => 'first-line'); - $idsSerieCurso = Portabilis_Utils_Database::fetchPreparedQuery($sql, $params); - - $matriculas = array(); - - $matriculaTurma = new clsPmieducarMatriculaTurma(); - $matriculaTurma = $matriculaTurma->lista( - $matriculaId, - null, - null, - null, - null, - null, - null, - null, - 1, - $idsSerieCurso['serie_id'], - $idsSerieCurso['curso_id'] - ); - - $matriculaTurma = $matriculaTurma[0]; - - $dadosMatricula = array(); - - if (is_array($matriculaTurma) && count($matriculaTurma) > 0) { - $dadosMatricula['ano'] = $ano; - $dadosMatricula['instituicao_id'] = $matriculaTurma['ref_cod_instituicao']; - $dadosMatricula['escola_id'] = $matriculaTurma['ref_ref_cod_escola']; - $dadosMatricula['turma_id'] = $matriculaTurma['ref_cod_turma']; - $dadosMatricula['nome_serie'] = $this->getNomeSerie($matriculaTurma['ref_ref_cod_serie']); - - $dadosMatricula['nome_curso'] = $matriculaTurma['nm_curso']; - } else { - throw new Exception("Não foi possivel recuperar os dados da matricula: $matriculaId."); - } - - return $dadosMatricula; - } - - protected function getAlunoIdByMatriculaId($matriculaId) - { - $sql = "select ref_cod_aluno from pmieducar.matricula where cod_matricula = $1"; - - return Portabilis_Utils_Database::selectField($sql, $matriculaId); - } - - protected function getAnoMatricula($matriculaId) - { - $sql = "select ano from pmieducar.matricula where cod_matricula = $1"; - - return Portabilis_Utils_Database::selectField($sql, $matriculaId); - } - - protected function getNomeSerie($serieId) - { - $sql = "select nm_serie from pmieducar.serie where cod_serie = $1"; - - return Portabilis_String_Utils::toLatin1(Portabilis_Utils_Database::selectField($sql, $serieId)); - } - - protected function getSequencial($alunoId, $ano, $matriculaId) - { - $sql = "select sequencial from pmieducar.historico_escolar where ref_cod_aluno = $1 and ano = $2 - and ref_cod_instituicao = $3 and ref_cod_matricula = $4 and ativo = 1 limit 1"; - - $params = array($alunoId, $ano, $this->getRequest()->instituicao_id, $matriculaId); - return Portabilis_Utils_Database::selectField($sql, $params); - } - - protected function existsHistorico($alunoId, $ano, $matriculaId, $ativo = 1, $reload = false) - { - if (!isset($this->existsHistorico) || $reload) { - $sql = "select 1 from pmieducar.historico_escolar where ref_cod_aluno = $1 and ano = $2 - and ref_cod_instituicao = $3 and ref_cod_matricula = $4 and ativo = $5"; - - $params = array($alunoId, $ano, $this->getRequest()->instituicao_id, $matriculaId, $ativo); - $this->existsHistorico = Portabilis_Utils_Database::selectField($sql, $params) == 1; - } - - return $this->existsHistorico; - } - - protected function getSituacaoHistorico($alunoId, $ano, $matriculaId, $reload = false) - { - if ($this->existsHistorico($alunoId, $ano, $matriculaId, 1, $reload)) { - $situacao = 'Processado'; - } else { - $situacao = 'Sem histórico'; - } - - return $this->toUtf8($situacao); - } - - protected function getLinkToHistorico($alunoId, $ano, $matriculaId) - { - $sql = "select sequencial from pmieducar.historico_escolar where ref_cod_aluno = $1 and - ano = $2 and ref_cod_instituicao = $3 and ref_cod_matricula = $4 and ativo = 1"; - - $params = array($alunoId, $ano, $this->getRequest()->instituicao_id, $matriculaId); - $sequencial = Portabilis_Utils_DataBase::selectField($sql, $params); - - if (is_numeric($sequencial)) { - $link = "/intranet/educar_historico_escolar_det.php?ref_cod_aluno=$alunoId&sequencial=$sequencial"; - } else { - $link = ''; - } - - return $link; - } - - protected function getMatriculas() - { - $matriculas = array(); - - if ($this->canGetMatriculas()) { - $alunos = new clsPmieducarMatriculaTurma(); - $alunos->setOrderby('ref_cod_curso, ref_ref_cod_serie, ref_cod_turma, sequencial_fechamento, nome'); - - $alunos = $alunos->lista( - $this->getRequest()->matricula_id, - $this->getRequest()->turma_id, - null, - null, - null, - null, - null, - null, - 1, - $this->getRequest()->serie_id, - $this->getRequest()->curso_id, - $this->getRequest()->escola_id, - $this->getRequest()->instituicao_id, - $this->getRequest()->aluno_id, - null, - null, - null, - null, - $this->getRequest()->ano, - null, - true, - null, - null, - true, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - $this->getRequest()->dependencia - ); - - if (!is_array($alunos)) { - $alunos = array(); - } - - $situacoesMatricula = array( - 'aprovado' => App_Model_MatriculaSituacao::APROVADO, - 'reprovado' => App_Model_MatriculaSituacao::REPROVADO, - 'reprovado-faltas' => App_Model_MatriculaSituacao::REPROVADO_POR_FALTAS, - 'em-andamento' => App_Model_MatriculaSituacao::EM_ANDAMENTO, - 'aprovado-conselho' => App_Model_MatriculaSituacao::APROVADO_PELO_CONSELHO, - 'aprovado-dependencia' => App_Model_MatriculaSituacao::APROVADO_COM_DEPENDENCIA - ); - - foreach ($alunos as $aluno) { - - $situacaoMatricula = $this->getSituacaoMatricula($aluno['ref_cod_matricula']); - - if (in_array($situacaoMatricula, $situacoesMatricula)) { - $matricula = array(); - $matriculaId = $aluno['ref_cod_matricula']; - $matricula['matricula_id'] = $matriculaId; - $matricula['aluno_id'] = $aluno['ref_cod_aluno']; - $matricula['nome'] = $this->toUtf8($aluno['nome_aluno']); - $matricula['nome_curso'] = $this->toUtf8($aluno['nm_curso']); - $matricula['nome_serie'] = $this->toUtf8($this->getNomeSerie($aluno['ref_ref_cod_serie'])); - $matricula['nome_turma'] = $this->toUtf8($aluno['nm_turma']); - $matricula['situacao_historico'] = $this->getSituacaoHistorico($aluno['ref_cod_aluno'], $this->getRequest()->ano, $matriculaId, $reload = true); - $matricula['link_to_historico'] = $this->getLinkToHistorico($aluno['ref_cod_aluno'], $this->getRequest()->ano, $matriculaId); - $matriculas[] = $matricula; - } - } - } - - return $matriculas; - } - - protected function getObservacaoPadraoSerie() - { - if ($this->validatesPresenceOfSerieId(false, false)) { - $sql = "select coalesce(observacao_historico, '') as observacao_historico from pmieducar.serie - where cod_serie = $1"; - - $observacao = Portabilis_Utils_DataBase::selectField($sql, $this->getRequest()->serie_id); - } else { - $observacao = ''; - } - - return $this->toUtf8($observacao); - } - - protected function saveService() - { - try { - $this->getService()->save(); - } catch (CoreExt_Service_Exception $e) { - //excecoes ignoradas :( servico lanca excecoes de alertas, que não são exatamente erros. - //error_log('CoreExt_Service_Exception ignorada: ' . $e->getMessage()); - } - } - - protected function getService($raiseExceptionOnErrors = false, $appendMsgOnErrors = true) - { - if (isset($this->service) && !is_null($this->service)) { - return $this->service; - } - - $msg = 'Erro ao recuperar serviço boletim: serviço não definido.'; - if ($appendMsgOnErrors) { - $this->appendMsg($msg); - } - - if ($raiseExceptionOnErrors) { - throw new Exception($msg); - } - - return null; - } - - protected function canSetService($validatesPresenceOfMatriculaId = true) - { - try { - $this->requiresLogin(true); - if ($validatesPresenceOfMatriculaId) { - $this->validatesPresenceOfMatriculaId(true); - } - } catch (Exception $e) { - return false; - } - return true; - } - - protected function setService($matriculaId = null) - { - if ($this->canSetService($validatesPresenceOfMatriculaId = is_null($matriculaId))) { - try { - - if (!$matriculaId) { - $matriculaId = $this->getRequest()->matricula_id; - } - - $this->service = new Avaliacao_Service_Boletim( - array( - 'matricula' => $matriculaId, - 'usuario' => $this->getSession()->id_pessoa - ) - ); - - return true; - } catch (Exception $e) { - $this->appendMsg('Exception ao instanciar serviço boletim: ' . $e->getMessage(), 'error', $encodeToUtf8 = true); - } - } - return false; - } - - protected function notImplementedError() - { - $this->appendMsg("Operação '{$this->getRequest()->oper}' inválida para o att '{$this->getRequest()->att}'"); - } - - public function Gerar() - { - $this->msgs = array(); - $this->response = array(); - - if ($this->canAcceptRequest()) { - try { - - if (isset($this->getRequest()->matricula_id)) { - $this->appendResponse('matricula_id', $this->getRequest()->matricula_id); - } - - if ($this->getRequest()->oper == 'get') { - if ($this->getRequest()->att == 'matriculas') { - $matriculas = $this->getMatriculas(); - $this->appendResponse('matriculas', $matriculas); - $this->appendResponse('observacao_padrao', $this->getObservacaoPadraoSerie()); - } else { - $this->notImplementedError(); - } - - } elseif ($this->getRequest()->oper == 'post') { - if ($this->getRequest()->att == 'processamento') { - $this->postProcessamento(); - } else { - $this->notImplementedError(); - } - } elseif ($this->getRequest()->oper == 'delete') { - if ($this->getRequest()->att == 'historico') { - $this->deleteHistorico(); - } else { - $this->notImplementedError(); - } - } - } catch (Exception $e) { - $this->appendMsg('Exception: ' . $e->getMessage(), $type = 'error', $encodeToUtf8 = true); - } - } - echo $this->prepareResponse(); - } - - protected function appendResponse($name, $value) - { - $this->response[$name] = $value; - } - - protected function prepareResponse() - { - $msgs = array(); - $this->appendResponse('att', isset($this->getRequest()->att) ? $this->getRequest()->att : ''); - - foreach ($this->msgs as $m) { - $msgs[] = array('msg' => $m['msg'], 'type' => $m['type']); - } - $this->appendResponse('msgs', $msgs); - - echo json_encode($this->response); - } - - protected function appendMsg($msg, $type = "error", $encodeToUtf8 = false) - { - if ($encodeToUtf8) { - $msg = utf8_encode($msg); - } - - //error_log("$type msg: '$msg'"); - $this->msgs[] = array('msg' => $msg, 'type' => $type); - } - - public function generate(CoreExt_Controller_Page_Interface $instance) - { - header('Content-type: application/json'); - $instance->Gerar(); - } - - - // TODO remover metodo, ao migrar esta classe para novo padrao - - protected function toUtf8($str, $options = array()) - { - return Portabilis_String_Utils::toUtf8($str, $options); - } -} +appendMsg($msg); + } + + if ($raiseExceptionOnEmpty) { + throw new Exception($msg); + } + + return false; + } + return true; + } + + protected function validatesValueIsNumeric(&$value, $name, $raiseExceptionOnError = false, $msg = '', $addMsgOnError = true) + { + if (!is_numeric($value)) { + if ($addMsgOnError) { + $msg = empty($msg) ? "O valor recebido para variavel '$name' deve ser numerico" : $msg; + $this->appendMsg($msg); + } + + if ($raiseExceptionOnError) { + throw new Exception($msg); + } + + return false; + } + return true; + } + + protected function validatesValueIsArray(&$value, $name, $raiseExceptionOnError = false, $msg = '', $addMsgOnError = true) + { + + if (!is_array($value)) { + if ($addMsgOnError) { + $msg = empty($msg) ? "Deve ser recebido uma lista de '$name'" : $msg; + $this->appendMsg($msg); + } + + if ($raiseExceptionOnError) { + throw new Exception($msg); + } + + return false; + } + return true; + } + + protected function validatesValueInSetOf(&$value, $setExpectedValues, $name, $raiseExceptionOnError = false, $msg = '') + { + if (!in_array($value, $setExpectedValues)) { + $msg = empty($msg) ? "Valor recebido na variavel '$name' é invalido" : $msg; + $this->appendMsg($msg); + + if ($raiseExceptionOnError) { + throw new Exception($msg); + } + + return false; + } + return true; + } + + + protected function requiresLogin($raiseExceptionOnEmpty) + { + return $this->validatesPresenceOf($this->getSession()->id_pessoa, '', $raiseExceptionOnEmpty, 'Usuário deve estar logado'); + } + + protected function validatesPresenceOfInstituicaoId($raiseExceptionOnEmpty) + { + return $this->validatesPresenceOf($this->getRequest()->instituicao_id, 'instituicao_id', $raiseExceptionOnEmpty); + } + + protected function validatesPresenceOfEscolaId($raiseExceptionOnEmpty) + { + return $this->validatesPresenceOf($this->getRequest()->escola_id, 'escola_id', $raiseExceptionOnEmpty); + } + + protected function validatesPresenceOfCursoId($raiseExceptionOnEmpty) + { + return $this->validatesPresenceOf($this->getRequest()->curso_id, 'curso_id', $raiseExceptionOnEmpty); + } + + protected function validatesPresenceOfSerieId($raiseExceptionOnEmpty, $addMsgOnEmpty = true) + { + return $this->validatesPresenceOf($this->getRequest()->serie_id, 'serie_id', $raiseExceptionOnEmpty, '', $addMsgOnEmpty); + } + + protected function validatesPresenceOfAno($raiseExceptionOnEmpty) + { + return $this->validatesPresenceOf($this->getRequest()->ano, 'ano', $raiseExceptionOnEmpty); + } + + protected function validatesPresenceOfMatriculaId($raiseExceptionOnEmpty) + { + return $this->validatesPresenceOf($this->getRequest()->matricula_id, 'matricula_id', $raiseExceptionOnEmpty); + } + + protected function validatesValueIsInBd($fieldName, &$value, $schemaName, $tableName, $raiseExceptionOnError = true) + { + $sql = "select 1 from $schemaName.$tableName where $fieldName = $1"; + $isValid = Portabilis_Utils_DataBase::selectField($sql, $value) == '1'; + + if (!$isValid) { + $msg = "O valor informado {$value} para $tableName, não esta presente no banco de dados."; + $this->appendMsg($msg); + + if ($raiseExceptionOnError) { + throw new Exception($msg); + } + + return false; + } + + return true; + } + + protected function validatesPresenceAndValueInDbOfGradeCursoId($raiseExceptionOnError) + { + return $this->validatesPresenceOf($this->getRequest()->grade_curso_id, 'grade_curso_id', $raiseExceptionOnError) && + $this->validatesValueIsInBd('id', $this->getRequest()->grade_curso_id, 'pmieducar', 'historico_grade_curso', $raiseExceptionOnError); + } + + protected function validatesPresenceOfDiasLetivos($raiseExceptionOnEmpty) + { + return $this->validatesPresenceOf($this->getRequest()->dias_letivos, 'dias_letivos', $raiseExceptionOnEmpty); + } + + protected function validatesValueOfAttValueIsNumeric($raiseExceptionOnError) + { + return $this->validatesValueIsNumeric($this->getRequest()->att_value, 'att_value', $raiseExceptionOnError); + } + + protected function validatesPresenceOfAttValue($raiseExceptionOnEmpty) + { + return $this->validatesPresenceOf($this->getRequest()->att_value, 'att_value', $raiseExceptionOnEmpty); + } + + + protected function validatesPresenceAndValueInSetOfAtt($raiseExceptionOnError) + { + $result = $this->validatesPresenceOf($this->getRequest()->att, 'att', $raiseExceptionOnError); + + if ($result) { + $expectedAtts = array('matriculas', 'processamento', 'historico'); + $result = $this->validatesValueInSetOf($this->getRequest()->att, $expectedAtts, 'att', $raiseExceptionOnError); + } + return $result; + } + + + protected function validatesPresenceAndValueInSetOfOper($raiseExceptionOnError) + { + $result = $this->validatesPresenceOf($this->getRequest()->oper, 'oper', $raiseExceptionOnError); + + if ($result) { + $expectedOpers = array('post', 'get', 'delete'); + $result = $this->validatesValueInSetOf($this->getRequest()->oper, $expectedOpers, 'oper', $raiseExceptionOnError); + } + return $result; + } + + + protected function validatesPresenceAndValueInSetOfExtraCurricular($raiseExceptionOnError) + { + $result = $this->validatesPresenceOf($this->getRequest()->extra_curricular, 'extra_curricular', $raiseExceptionOnError); + + if ($result) { + $expectedOpers = array(0, 1); + $result = $this->validatesValueInSetOf($this->getRequest()->extra_curricular, $expectedOpers, 'extra_curricular', $raiseExceptionOnError); + } + return $result; + } + + protected function validatesPresenceAndValueOfPercentualFrequencia($raiseExceptionOnError) + { + $name = 'percentual_frequencia'; + $isValid = $this->validatesPresenceOf($this->getRequest()->percentual_frequencia, $name, $raiseExceptionOnError); + + if ($isValid && $this->getRequest()->percentual_frequencia != 'buscar-boletim') { + $isValid = $this->validatesValueIsNumeric($this->getRequest()->percentual_frequencia, $name, $raiseExceptionOnError); + } + + return $isValid; + } + + protected function validatesPresenceOfNotas($raiseExceptionOnError) + { + return $this->validatesPresenceOf($this->getRequest()->notas, 'notas', $raiseExceptionOnError); + } + + protected function validatesPresenceAndValueOfFaltas($raiseExceptionOnError) + { + $name = 'faltas'; + $isValid = $this->validatesPresenceOf($this->getRequest()->faltas, $name, $raiseExceptionOnError); + + if ($isValid && $this->getRequest()->faltas != 'buscar-boletim') { + $isValid = $this->validatesValueIsNumeric($this->getRequest()->faltas, $name, $raiseExceptionOnError); + } + + return $isValid; + } + + + protected function validatesPresenceAndValueOfDisciplinas($raiseExceptionOnError) + { + $name = 'disciplinas'; + $isValid = $this->validatesPresenceOf($this->getRequest()->disciplinas, $name, $raiseExceptionOnError); + + if ($isValid && $this->getRequest()->disciplinas != 'buscar-boletim') { + $isValid = $this->validatesValueIsArray($this->getRequest()->disciplinas, 'disciplinas', $raiseExceptionOnError); + if ($isValid) { + foreach ($this->getRequest()->disciplinas as $disciplina) { + $isValid = $this->validatesPresenceOf($disciplina['nome'], 'nome (para todas disciplinas)', $raiseExceptionOnError); + + if ($isValid && isset($disciplina['falta']) && trim($disciplina['falta']) != '') { + $isValid = $this->validatesValueIsNumeric($disciplina['falta'], 'falta (para todas disciplinas)', $raiseExceptionOnError); + } + } + } + } + return $isValid; + } + + protected function validatesPresenceAndValueInSetOfSituacao($raiseExceptionOnError) + { + $name = 'situacao'; + $isValid = $this->validatesPresenceOf($this->getRequest()->situacao, $name, $raiseExceptionOnError); + + if ($isValid) { + $expectedOpers = array('buscar-matricula', 'aprovado', 'reprovado', 'em-andamento', 'transferido'); + $isValid = $this->validatesValueInSetOf($this->getRequest()->situacao, $expectedOpers, $name, $raiseExceptionOnError); + } + + return $isValid; + } + + + /* esta funcao só pode ser chamada após setar $this->getService() */ + protected function validatesPresenceOfComponenteCurricularId($raiseExceptionOnEmpty, $addMsgOnEmpty = true) + { + return $this->validatesPresenceOf($this->getRequest()->componente_curricular_id, 'componente_curricular_id', $raiseExceptionOnEmpty, $msg = '', $addMsgOnEmpty); + } + + + protected function canAcceptRequest() + { + try { + $this->requiresLogin(true); + $this->validatesPresenceAndValueInSetOfAtt(true); + $this->validatesPresenceAndValueInSetOfOper(true); + } catch (Exception $e) { + return false; + } + return true; + } + + + protected function canGetMatriculas() + { + return $this->validatesPresenceOfAno(false) && + $this->validatesPresenceOfInstituicaoId(false) && + $this->validatesPresenceOfEscolaId(false); + } + + + protected function canPostProcessamento() + { + $canPost = $this->validatesPresenceOfInstituicaoId(false) && + $this->validatesPresenceOfMatriculaId(false) && + $this->validatesPresenceOfDiasLetivos(false) && + $this->validatesPresenceAndValueInSetOfSituacao(false) && + $this->validatesPresenceAndValueInSetOfExtraCurricular(false) && + $this->validatesPresenceAndValueInDbOfGradeCursoId(false) && + $this->validatesPresenceAndValueOfPercentualFrequencia(false) && + $this->validatesPresenceAndValueOfDisciplinas(false); + + if ($canPost && $this->getRequest()->disciplinas == 'buscar-boletim') { + $canPost = $this->validatesPresenceOfNotas(false) && $this->validatesPresenceAndValueOfFaltas(false); + } + + if ($canPost) { + $sql = "select 1 from pmieducar.matricula where cod_matricula = $1 and ativo = 1"; + + if (!Portabilis_Utils_Database::selectField($sql, $this->getRequest()->matricula_id)) { + $this->appendMsg("A matricula {$this->getRequest()->matricula_id} não existe ou esta desativa", 'error'); + $canPost = false; + } + } + + if ($canPost) { + $sql = "select 1 from pmieducar.matricula_turma where ref_cod_matricula = $1 and ativo = 1 limit 1"; + + if (!Portabilis_Utils_Database::selectField($sql, $this->getRequest()->matricula_id)) { + $this->appendMsg("A matricula {$this->getRequest()->matricula_id} não está enturmada.", 'error'); + $canPost = false; + } + } + return $canPost && $this->setService(); + } + + + protected function canDeleteHistorico() + { + return $this->validatesPresenceOfInstituicaoId(false) && + $this->validatesPresenceOfMatriculaId(false); + } + + + protected function deleteHistorico() + { + if ($this->canDeleteHistorico()) { + + $matriculaId = $this->getRequest()->matricula_id; + $alunoId = $this->getAlunoIdByMatriculaId($matriculaId); + $dadosMatricula = $this->getdadosMatricula($matriculaId); + $ano = $dadosMatricula['ano']; + + if ($this->existsHistorico($alunoId, $ano, $matriculaId)) { + $sequencial = $this->getSequencial($alunoId, $ano, $matriculaId); + $this->deleteHistoricoDisplinas($alunoId, $sequencial); + + $historicoEscolar = new clsPmieducarHistoricoEscolar( + $ref_cod_aluno = $alunoId, + $sequencial, + $ref_usuario_exc = $this->getSession()->id_pessoa, + $ref_usuario_cad = null, + //TODO nm_curso + $nm_serie = null, + $ano = $ano, + $carga_horaria = null, + $dias_letivos = null, + $escola = null, + $escola_cidade = null, + $escola_uf = null, + $observacao = null, + $aprovado = null, + $data_cadastro = null, + $data_exclusao = date('Y-m-d'), + $ativo = 0 + ); + $historicoEscolar->edita(); + + $this->appendMsg('Histórico escolar removido com sucesso', 'success'); + } else { + $this->appendMsg("Histórico matricula $matriculaId inexistente ou já removido", 'notice'); + } + + $situacaoHistorico = $this->getSituacaoHistorico($alunoId, $ano, $matriculaId, $reload = true); + + $this->appendResponse('situacao_historico', $situacaoHistorico); + $this->appendResponse('link_to_historico', ''); + } + } + + protected function deleteHistoricoDisplinas($alunoId, $historicoSequencial) + { + $historicoDisciplinas = new clsPmieducarHistoricoDisciplinas(); + $historicoDisciplinas->excluirTodos($alunoId, $historicoSequencial); + } + + + protected function getdadosEscola($escolaId) + { + $sql = "select + (select pes.nome from pmieducar.escola esc, cadastro.pessoa pes + where esc.ref_cod_instituicao = $1 and esc.cod_escola = $2 + and pes.idpes = esc.ref_idpes) as nome, + + (select coalesce((select coalesce((select municipio.nome from public.municipio, + cadastro.endereco_pessoa, cadastro.juridica, public.bairro, pmieducar.escola + where endereco_pessoa.idbai = bairro.idbai and bairro.idmun = municipio.idmun and + juridica.idpes = endereco_pessoa.idpes and juridica.idpes = escola.ref_idpes and + escola.cod_escola = $2),(select endereco_externo.cidade from cadastro.endereco_externo, + pmieducar.escola where endereco_externo.idpes = escola.ref_idpes and escola.cod_escola = $2))), + (select municipio from pmieducar.escola_complemento where ref_cod_escola = $2))) as cidade, + + (select coalesce((select coalesce((select municipio.sigla_uf from public.municipio, + cadastro.endereco_pessoa, cadastro.juridica, public.bairro, pmieducar.escola + where endereco_pessoa.idbai = bairro.idbai and bairro.idmun = municipio.idmun and + juridica.idpes = endereco_pessoa.idpes and juridica.idpes = escola.ref_idpes and + escola.cod_escola = $2),(select endereco_externo.sigla_uf from cadastro.endereco_externo, + pmieducar.escola where endereco_externo.idpes = escola.ref_idpes and escola.cod_escola = $2))), + (select inst.ref_sigla_uf from pmieducar.instituicao inst where inst.cod_instituicao = $1))) as uf"; + + $params = array('params' => array($this->getrequest()->instituicao_id, $escolaId), 'return_only' => 'first-line'); + return Portabilis_Utils_Database::fetchPreparedQuery($sql, $params); + } + + + protected function getNextHistoricoSequencial($alunoId) + { + //A consulta leva em consideração historicos inativos pois o sequencial é chave composta com ref_cod_aluno id + $sql = "select coalesce(max(sequencial), 0) + 1 from pmieducar.historico_escolar where ref_cod_aluno = $1"; + + return Portabilis_Utils_Database::selectField($sql, $alunoId); + } + + + protected function getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId) + { + $sql = "select coalesce(max(sequencial), 0) + 1 from pmieducar.historico_disciplinas where + ref_sequencial = $1 and ref_ref_cod_aluno = $2"; + + return Portabilis_Utils_Database::selectField($sql, array($historicoSequencial, $alunoId)); + } + + + protected function getSituacaoMatricula($matriculaId = null) + { + if (!is_null($matriculaId)) { + + if (!is_null($this->getService(false, false))) { + $situacao = $this->getService()->getOption('aprovado'); + } else { + $sql = "select aprovado from pmieducar.matricula where cod_matricula = $1"; + $situacao = Portabilis_Utils_Database::selectField($sql, $matriculaId); + } + + } else if ($this->getRequest()->situacao == 'buscar-matricula') { + $situacao = $this->getService()->getOption('aprovado'); + } else { + $situacoes = array( + 'aprovado' => App_Model_MatriculaSituacao::APROVADO, + 'reprovado' => App_Model_MatriculaSituacao::REPROVADO, + 'em-andamento' => App_Model_MatriculaSituacao::EM_ANDAMENTO, + 'transferido' => App_Model_MatriculaSituacao::TRANSFERIDO + ); + $situacao = $situacoes[$this->getRequest()->situacao]; + } + return $situacao; + } + + protected function getPercentualFrequencia() + { + if ($this->getRequest()->percentual_frequencia == 'buscar-boletim') { + $percentual = round($this->getService()->getSituacaoFaltas()->porcentagemPresenca, 2); + } else { + $percentual = $this->getRequest()->percentual_frequencia; + } + return str_replace(',', '.', $percentual); + } + + protected function getFaltaGlobalizada($defaultValue = null) + { + $faltaGeral = $this->getService()->getRegra()->get('tipoPresenca') == RegraAvaliacao_Model_TipoPresenca::GERAL; + + if (! $faltaGeral) { + return $defaultValue; + } + + return $this->getFalta(); + } + + protected function postProcessamento() + { + if ($this->canPostProcessamento()) { + $matriculaId = $this->getRequest()->matricula_id; + + try { + $alunoId = $this->getAlunoIdByMatriculaId($matriculaId); + $dadosMatricula = $this->getdadosMatricula($matriculaId); + $dadosEscola = $this->getdadosEscola($dadosMatricula['escola_id']); + $ano = $dadosMatricula['ano']; + $isNewHistorico = !$this->existsHistorico($alunoId, $ano, $matriculaId); + + if ($isNewHistorico) { + $sequencial = $this->getNextHistoricoSequencial($alunoId); + + $historicoEscolar = new clsPmieducarHistoricoEscolar( + $alunoId, + $sequencial, + $ref_usuario_exc = null, + $ref_usuario_cad = $this->getSession()->id_pessoa, + $dadosMatricula['nome_serie'], + $ano, + $this->getService()->getOption('serieCargaHoraria'), + $this->getRequest()->dias_letivos, + strtoupper($dadosEscola['nome']), + strtoupper($dadosEscola['cidade']), + $dadosEscola['uf'], + $this->getRequest()->observacao, + $this->getSituacaoMatricula(), + $data_cadastro = date('Y-m-d'), + $data_exclusao = null, + $ativo = 1, + $this->getFaltaGlobalizada($defaultValue = 'null'), + $dadosMatricula['instituicao_id'], + $origem = '', //TODO + $this->getRequest()->extra_curricular, + $matriculaId, + $this->getPercentualFrequencia(), + $this->getRequest()->registro, + $this->getRequest()->livro, + $this->getRequest()->folha, + $dadosMatricula['nome_curso'], + $this->getRequest()->grade_curso_id, + null, + $dadosMatricula['escola_id'], + $this->getRequest()->dependencia, + $this->getRequest()->posicao + ); + + $historicoEscolar->cadastra(); + $this->recreateHistoricoDisciplinas($sequencial, $alunoId, $dadosMatricula['turma_id']); + + $this->appendMsg('Histórico processado com sucesso', 'success'); + } else { + + $sequencial = $this->getSequencial($alunoId, $ano, $matriculaId); + + $historicoEscolar = new clsPmieducarHistoricoEscolar( + $alunoId, + $sequencial, + $this->getSession()->id_pessoa, + $ref_usuario_cad = null, + $dadosMatricula['nome_serie'], + $ano, + $this->getService()->getOption('serieCargaHoraria'), + $this->getRequest()->dias_letivos, + strtoupper($dadosEscola['nome']), + strtoupper($dadosEscola['cidade']), + $dadosEscola['uf'], + $this->getRequest()->observacao, + $this->getSituacaoMatricula(), + $data_cadastro = null, + $data_exclusao = null, + $ativo = 1, + $this->getFaltaGlobalizada($defaultValue = 'null'), + $dadosMatricula['instituicao_id'], + $origem = '', //TODO + $this->getRequest()->extra_curricular, + $matriculaId, + $this->getPercentualFrequencia(), + $this->getRequest()->registro, + $this->getRequest()->livro, + $this->getRequest()->folha, + $dadosMatricula['nome_curso'], + $this->getRequest()->grade_curso_id, + null, + $dadosMatricula['escola_id'], + $this->getRequest()->dependencia, + $this->getRequest()->posicao + ); + + $historicoEscolar->edita(); + $this->recreateHistoricoDisciplinas($sequencial, $alunoId, $dadosMatricula['turma_id']); + $this->appendMsg('Histórico reprocessado com sucesso', 'success'); + } + + } catch (Exception $e) { + $this->appendMsg('Erro ao processar histórico, detalhes:' . $e->getMessage(), 'error', true); + } + + $situacaoHistorico = $this->getSituacaoHistorico($alunoId, $ano, $matriculaId, $reload = true); + $linkToHistorico = $this->getLinkToHistorico($alunoId, $ano, $matriculaId); + + $this->appendResponse('situacao_historico', $situacaoHistorico); + $this->appendResponse('link_to_historico', $linkToHistorico); + } + } + + + protected function _createHistoricoDisciplinas($fields) + { + $historicoDisciplina = new clsPmieducarHistoricoDisciplinas( + $fields['sequencial'], + $fields['alunoId'], + $fields['historicoSequencial'], + $fields['nome'], + $fields['nota'], + $fields['falta'], + $fields['ordenamento'], + $fields['carga_horaria_disciplina'], + $fields['dependencia'] + ); + $historicoDisciplina->cadastra(); + } + + protected function shouldProcessAreaConhecimento($areaConhecimento) + { + if (!empty($this->getRequest()->area_conhecimento)) { + return in_array($areaConhecimento, $this->getRequest()->area_conhecimento); + } + return true; + } + + protected function recreateHistoricoDisciplinas($historicoSequencial, $alunoId, $turmaId = null) + { + + $this->deleteHistoricoDisplinas($alunoId, $historicoSequencial); + + if ($this->getRequest()->disciplinas == 'buscar-boletim') { + + $cnsNota = RegraAvaliacao_Model_Nota_TipoValor; + $tpNota = $this->getService()->getRegra()->get('tipoNota'); + $situacaoFaltasCc = $this->getService()->getSituacaoFaltas()->componentesCurriculares; + $mediasCc = $this->getService()->getMediasComponentes(); + $turmaId = $this->getRequest()->turma_id ?: $turmaId; + $mediaAreaConhecimento = $this->getRequest()->media_area_conhecimento; + $processarMediaGeral = $this->getRequest()->processar_media_geral; + + $aprovadoDependencia = $this->getSituacaoMatricula($aluno['ref_cod_matricula']) == 12; + + foreach ($this->getService()->getComponentes() as $componenteCurricular) { + if (!$this->shouldProcessAreaConhecimento($componenteCurricular->get('area_conhecimento'))) { + continue; + } + $ccId = $componenteCurricular->get('id'); + $reprovado = $mediasCc[$ccId][0]->situacao == 2; + $disciplinaDependencia = ($aprovadoDependencia && $reprovado); + $nome = $componenteCurricular->nome; + $ordenamento = $componenteCurricular->ordenamento; + $carga_horaria_disciplina = $componenteCurricular->carga_horaria_disciplina; + $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId); + $nota = ''; + $notaConceitualNumerica = ''; + + if (clsPmieducarTurma::verificaDisciplinaDispensada($turmaId, $ccId)) { + $nota = $this->DISCIPLINA_DISPENSADA; + } elseif ($this->getRequest()->notas == 'buscar-boletim') { + if ($tpNota == $cnsNota::CONCEITUAL) { + if ($GLOBALS['coreExt']['Config']->app->processar_historicos_conceituais == "1") { + $nota = (string)$mediasCc[$ccId][0]->mediaArredondada; + $notaConceitualNumerica = (string)$mediasCc[$ccId][0]->media; + } + } elseif ($tpNota == $cnsNota::NUMERICA) { + $nota = (string)$mediasCc[$ccId][0]->mediaArredondada; + } elseif ($tpNota == $cnsNota::NUMERICACONCEITUAL) { + $nota = (string)$mediasCc[$ccId][0]->mediaArredondada; + $notaConceitualNumerica = (string)$mediasCc[$ccId][0]->media; + } + } else { + $nota = $this->getRequest()->notas; + } + + if (is_numeric($nota)) { + $nota = sprintf("%.1f", $nota); + } + + if ($processarMediaGeral) { + $nota = '-'; + } + + if ($mediaAreaConhecimento) { + $nota = str_replace(',', '.', $nota); + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['nome'] = $componenteCurricular->area_conhecimento->nome; + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['nota'] += $nota; + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['nota_conceitual_numerica'] += $notaConceitualNumerica; + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['falta'] += $this->getFalta($situacaoFaltasCc[$ccId]); + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['ordenamento'] = $componenteCurricular->area_conhecimento->ordenamento; + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['carga_horaria_disciplina'] = $componenteCurricular->area_conhecimento->carga_horaria_disciplina; + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['dependencia'] = $disciplinaDependencia; + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['count']++; + } else { + $this->_createHistoricoDisciplinas( + array( + "sequencial" => $sequencial, + "alunoId" => $alunoId, + "historicoSequencial" => $historicoSequencial, + "nome" => $nome, + "nota" => $nota, + "falta" => $this->getFalta($situacaoFaltasCc[$ccId]), + "ordenamento" => $ordenamento, + "carga_horaria_disciplina" => $carga_horaria_disciplina, + "dependencia" => $disciplinaDependencia + ) + ); + } + } + + if ($mediaAreaConhecimento) { + foreach ($arrayAreaConhecimento as $key => $value) { + + $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId); + + if ($this->getRequest()->notas == 'buscar-boletim') { + $nota = number_format(($value['nota_conceitual_numerica'] / $value['count']), 2, ',', ''); + } + + if ($processarMediaGeral) { + $nota = '-'; + } + + $this->_createHistoricoDisciplinas( + array( + "sequencial" => $sequencial, + "alunoId" => $alunoId, + "historicoSequencial" => $historicoSequencial, + "nome" => $value['nome'], + "nota" => $nota, + "falta" => round($value['falta'] / $value['count']), + "ordenamento" => $value['ordenamento'], + "carga_horaria_disciplina" => $value['carga_horaria_disciplina'], + "dependencia" => $value['dependencia'] + ) + ); + } + } + if ($processarMediaGeral) { + $componentesCurriculares['media_geral'] = $this->insereComponenteMediaGeral($historicoSequencial, $alunoId); + } + } else { + foreach ($this->getRequest()->disciplinas as $disciplina) { + $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId); + + $this->_createHistoricoDisciplinas( + array( + "sequencial" => $sequencial, + "alunoId" => $alunoId, + "historicoSequencial" => $historicoSequencial, + "nome" => $disciplina['nome'], + "nota" => $disciplina['nota'], + "falta" => $falta = $disciplina['falta'], + "ordenamento" => $value['ordenamento'], + "carga_horaria_disciplina" => $value['carga_horaria_disciplina'], + "dependencia" => $value['dependencia'] + ) + ); + } + } + } + + protected function insereComponenteMediaGeral($historicoSequencial, $alunoId) + { + $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId); + $historicoEscolar = new clsPmieducarHistoricoEscolar($alunoId, $historicoSequencial); + + $historicoEscolar->insereComponenteMediaGeral($sequencial); + } + + protected function getFalta($situacaoFaltaComponenteCurricular = null) + { + if ($this->getRequest()->faltas == 'buscar-boletim') { + + $cnsPresenca = RegraAvaliacao_Model_TipoPresenca; + $tpPresenca = $this->getService()->getRegra()->get('tipoPresenca'); + + //retorna '' caso não exista situacaoFalta para o componente curricular, + //como nos casos em que a regra de avaliação muda + if ($tpPresenca == $cnsPresenca::POR_COMPONENTE && !is_null($situacaoFaltaComponenteCurricular)) { + $falta = $situacaoFaltaComponenteCurricular->total; + } elseif ($tpPresenca == $cnsPresenca::POR_COMPONENTE) { + $falta = ''; + } elseif ($tpPresenca == $cnsPresenca::GERAL) { + $falta = $this->getService()->getSituacaoFaltas()->totalFaltas; + } + } else { + $falta = $this->getRequest()->faltas; + } + + return $falta; + } + + protected function getDadosMatricula($matriculaId) + { + $ano = $this->getAnoMatricula($matriculaId); + $sql = "select ref_ref_cod_serie as serie_id, ref_cod_curso as curso_id from pmieducar.matricula + where cod_matricula = $1"; + + $params = array('params' => $matriculaId, 'return_only' => 'first-line'); + $idsSerieCurso = Portabilis_Utils_Database::fetchPreparedQuery($sql, $params); + + $matriculas = array(); + + $matriculaTurma = new clsPmieducarMatriculaTurma(); + $matriculaTurma = $matriculaTurma->lista( + $matriculaId, + null, + null, + null, + null, + null, + null, + null, + 1, + $idsSerieCurso['serie_id'], + $idsSerieCurso['curso_id'] + ); + + $matriculaTurma = $matriculaTurma[0]; + + $dadosMatricula = array(); + + if (is_array($matriculaTurma) && count($matriculaTurma) > 0) { + $dadosMatricula['ano'] = $ano; + $dadosMatricula['instituicao_id'] = $matriculaTurma['ref_cod_instituicao']; + $dadosMatricula['escola_id'] = $matriculaTurma['ref_ref_cod_escola']; + $dadosMatricula['turma_id'] = $matriculaTurma['ref_cod_turma']; + $dadosMatricula['nome_serie'] = $this->getNomeSerie($matriculaTurma['ref_ref_cod_serie']); + + $dadosMatricula['nome_curso'] = $matriculaTurma['nm_curso']; + } else { + throw new Exception("Não foi possivel recuperar os dados da matricula: $matriculaId."); + } + + return $dadosMatricula; + } + + protected function getAlunoIdByMatriculaId($matriculaId) + { + $sql = "select ref_cod_aluno from pmieducar.matricula where cod_matricula = $1"; + + return Portabilis_Utils_Database::selectField($sql, $matriculaId); + } + + protected function getAnoMatricula($matriculaId) + { + $sql = "select ano from pmieducar.matricula where cod_matricula = $1"; + + return Portabilis_Utils_Database::selectField($sql, $matriculaId); + } + + protected function getNomeSerie($serieId) + { + $sql = "select nm_serie from pmieducar.serie where cod_serie = $1"; + + return Portabilis_String_Utils::toLatin1(Portabilis_Utils_Database::selectField($sql, $serieId)); + } + + protected function getSequencial($alunoId, $ano, $matriculaId) + { + $sql = "select sequencial from pmieducar.historico_escolar where ref_cod_aluno = $1 and ano = $2 + and ref_cod_instituicao = $3 and ref_cod_matricula = $4 and ativo = 1 limit 1"; + + $params = array($alunoId, $ano, $this->getRequest()->instituicao_id, $matriculaId); + return Portabilis_Utils_Database::selectField($sql, $params); + } + + protected function existsHistorico($alunoId, $ano, $matriculaId, $ativo = 1, $reload = false) + { + if (!isset($this->existsHistorico) || $reload) { + $sql = "select 1 from pmieducar.historico_escolar where ref_cod_aluno = $1 and ano = $2 + and ref_cod_instituicao = $3 and ref_cod_matricula = $4 and ativo = $5"; + + $params = array($alunoId, $ano, $this->getRequest()->instituicao_id, $matriculaId, $ativo); + $this->existsHistorico = Portabilis_Utils_Database::selectField($sql, $params) == 1; + } + + return $this->existsHistorico; + } + + protected function getSituacaoHistorico($alunoId, $ano, $matriculaId, $reload = false) + { + if ($this->existsHistorico($alunoId, $ano, $matriculaId, 1, $reload)) { + $situacao = 'Processado'; + } else { + $situacao = 'Sem histórico'; + } + + return $this->toUtf8($situacao); + } + + protected function getLinkToHistorico($alunoId, $ano, $matriculaId) + { + $sql = "select sequencial from pmieducar.historico_escolar where ref_cod_aluno = $1 and + ano = $2 and ref_cod_instituicao = $3 and ref_cod_matricula = $4 and ativo = 1"; + + $params = array($alunoId, $ano, $this->getRequest()->instituicao_id, $matriculaId); + $sequencial = Portabilis_Utils_DataBase::selectField($sql, $params); + + if (is_numeric($sequencial)) { + $link = "/intranet/educar_historico_escolar_det.php?ref_cod_aluno=$alunoId&sequencial=$sequencial"; + } else { + $link = ''; + } + + return $link; + } + + protected function getMatriculas() + { + $matriculas = array(); + + if ($this->canGetMatriculas()) { + $alunos = new clsPmieducarMatriculaTurma(); + $alunos->setOrderby('ref_cod_curso, ref_ref_cod_serie, ref_cod_turma, sequencial_fechamento, nome'); + + $alunos = $alunos->lista( + $this->getRequest()->matricula_id, + $this->getRequest()->turma_id, + null, + null, + null, + null, + null, + null, + 1, + $this->getRequest()->serie_id, + $this->getRequest()->curso_id, + $this->getRequest()->escola_id, + $this->getRequest()->instituicao_id, + $this->getRequest()->aluno_id, + null, + null, + null, + null, + $this->getRequest()->ano, + null, + true, + null, + null, + true, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + $this->getRequest()->dependencia + ); + + if (!is_array($alunos)) { + $alunos = array(); + } + + $situacoesMatricula = array( + 'aprovado' => App_Model_MatriculaSituacao::APROVADO, + 'reprovado' => App_Model_MatriculaSituacao::REPROVADO, + 'reprovado-faltas' => App_Model_MatriculaSituacao::REPROVADO_POR_FALTAS, + 'em-andamento' => App_Model_MatriculaSituacao::EM_ANDAMENTO, + 'aprovado-conselho' => App_Model_MatriculaSituacao::APROVADO_PELO_CONSELHO, + 'aprovado-dependencia' => App_Model_MatriculaSituacao::APROVADO_COM_DEPENDENCIA + ); + + foreach ($alunos as $aluno) { + + $situacaoMatricula = $this->getSituacaoMatricula($aluno['ref_cod_matricula']); + + if (in_array($situacaoMatricula, $situacoesMatricula)) { + $matricula = array(); + $matriculaId = $aluno['ref_cod_matricula']; + $matricula['matricula_id'] = $matriculaId; + $matricula['aluno_id'] = $aluno['ref_cod_aluno']; + $matricula['nome'] = $this->toUtf8($aluno['nome_aluno']); + $matricula['nome_curso'] = $this->toUtf8($aluno['nm_curso']); + $matricula['nome_serie'] = $this->toUtf8($this->getNomeSerie($aluno['ref_ref_cod_serie'])); + $matricula['nome_turma'] = $this->toUtf8($aluno['nm_turma']); + $matricula['situacao_historico'] = $this->getSituacaoHistorico($aluno['ref_cod_aluno'], $this->getRequest()->ano, $matriculaId, $reload = true); + $matricula['link_to_historico'] = $this->getLinkToHistorico($aluno['ref_cod_aluno'], $this->getRequest()->ano, $matriculaId); + $matriculas[] = $matricula; + } + } + } + + return $matriculas; + } + + protected function getObservacaoPadraoSerie() + { + if ($this->validatesPresenceOfSerieId(false, false)) { + $sql = "select coalesce(observacao_historico, '') as observacao_historico from pmieducar.serie + where cod_serie = $1"; + + $observacao = Portabilis_Utils_DataBase::selectField($sql, $this->getRequest()->serie_id); + } else { + $observacao = ''; + } + + return $this->toUtf8($observacao); + } + + protected function saveService() + { + try { + $this->getService()->save(); + } catch (CoreExt_Service_Exception $e) { + //excecoes ignoradas :( servico lanca excecoes de alertas, que não são exatamente erros. + //error_log('CoreExt_Service_Exception ignorada: ' . $e->getMessage()); + } + } + + protected function getService($raiseExceptionOnErrors = false, $appendMsgOnErrors = true) + { + if (isset($this->service) && !is_null($this->service)) { + return $this->service; + } + + $msg = 'Erro ao recuperar serviço boletim: serviço não definido.'; + if ($appendMsgOnErrors) { + $this->appendMsg($msg); + } + + if ($raiseExceptionOnErrors) { + throw new Exception($msg); + } + + return null; + } + + protected function canSetService($validatesPresenceOfMatriculaId = true) + { + try { + $this->requiresLogin(true); + if ($validatesPresenceOfMatriculaId) { + $this->validatesPresenceOfMatriculaId(true); + } + } catch (Exception $e) { + return false; + } + return true; + } + + protected function setService($matriculaId = null) + { + if ($this->canSetService($validatesPresenceOfMatriculaId = is_null($matriculaId))) { + try { + + if (!$matriculaId) { + $matriculaId = $this->getRequest()->matricula_id; + } + + $this->service = new Avaliacao_Service_Boletim( + array( + 'matricula' => $matriculaId, + 'usuario' => $this->getSession()->id_pessoa + ) + ); + + return true; + } catch (Exception $e) { + $this->appendMsg('Exception ao instanciar serviço boletim: ' . $e->getMessage(), 'error', $encodeToUtf8 = true); + } + } + return false; + } + + protected function notImplementedError() + { + $this->appendMsg("Operação '{$this->getRequest()->oper}' inválida para o att '{$this->getRequest()->att}'"); + } + + public function Gerar() + { + $this->msgs = array(); + $this->response = array(); + + if ($this->canAcceptRequest()) { + try { + + if (isset($this->getRequest()->matricula_id)) { + $this->appendResponse('matricula_id', $this->getRequest()->matricula_id); + } + + if ($this->getRequest()->oper == 'get') { + if ($this->getRequest()->att == 'matriculas') { + $matriculas = $this->getMatriculas(); + $this->appendResponse('matriculas', $matriculas); + $this->appendResponse('observacao_padrao', $this->getObservacaoPadraoSerie()); + } else { + $this->notImplementedError(); + } + + } elseif ($this->getRequest()->oper == 'post') { + if ($this->getRequest()->att == 'processamento') { + $this->postProcessamento(); + } else { + $this->notImplementedError(); + } + } elseif ($this->getRequest()->oper == 'delete') { + if ($this->getRequest()->att == 'historico') { + $this->deleteHistorico(); + } else { + $this->notImplementedError(); + } + } + } catch (Exception $e) { + $this->appendMsg('Exception: ' . $e->getMessage(), $type = 'error', $encodeToUtf8 = true); + } + } + echo $this->prepareResponse(); + } + + protected function appendResponse($name, $value) + { + $this->response[$name] = $value; + } + + protected function prepareResponse() + { + $msgs = array(); + $this->appendResponse('att', isset($this->getRequest()->att) ? $this->getRequest()->att : ''); + + foreach ($this->msgs as $m) { + $msgs[] = array('msg' => $m['msg'], 'type' => $m['type']); + } + $this->appendResponse('msgs', $msgs); + + echo SafeJson::encode($this->response); + } + + protected function appendMsg($msg, $type = "error", $encodeToUtf8 = false) + { + if ($encodeToUtf8) { + $msg = utf8_encode($msg); + } + + //error_log("$type msg: '$msg'"); + $this->msgs[] = array('msg' => $msg, 'type' => $type); + } + + public function generate(CoreExt_Controller_Page_Interface $instance) + { + header('Content-type: application/json'); + $instance->Gerar(); + } + + + // TODO remover metodo, ao migrar esta classe para novo padrao + + protected function toUtf8($str, $options = array()) + { + return Portabilis_String_Utils::toUtf8($str, $options); + } +} From d0deee7d55f5bf9e3a987d20fc46b4bd550709e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89ber=20Freitas=20Dias?= Date: Tue, 5 Jun 2018 11:24:37 -0300 Subject: [PATCH 6/8] =?UTF-8?q?Corrigindo=20classe=20para=20seguir=20melho?= =?UTF-8?q?r=20os=20padr=C3=B5es;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #encoding-fix --- ieducar/lib/Utils/SafeJson.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ieducar/lib/Utils/SafeJson.php b/ieducar/lib/Utils/SafeJson.php index e820afb20b..2840bbe4aa 100644 --- a/ieducar/lib/Utils/SafeJson.php +++ b/ieducar/lib/Utils/SafeJson.php @@ -2,17 +2,17 @@ class SafeJson { - static function encode($value, $options = 0, $depth = 512) + public static function encode($value, $options = 0, $depth = 512) { return self::handle(json_encode($value, $options, $depth)); } - static function decode($json, $assoc = false) + public static function decode($json, $assoc = false) { return self::handle(json_decode($json, $assoc)); } - static private function handle($value) + private static function handle($value) { if ($value === false) { throw new Exception(json_last_error_msg()); From adf512a7e80834da5bc64916f98e90b2886298a2 Mon Sep 17 00:00:00 2001 From: Lucas Schmoeller da Silva Date: Tue, 5 Jun 2018 14:24:39 -0300 Subject: [PATCH 7/8] =?UTF-8?q?Corrige=20sincroniza=C3=A7=C3=A3o=20de=20di?= =?UTF-8?q?spensas=20de=20disciplinas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit O i-Educar grava no campo data de exclusão quando um registro é editado, por isso esses registros não devem ser excluídos da consulta Refs #3732 --- ieducar/modules/Api/Views/MatriculaController.php | 1 - 1 file changed, 1 deletion(-) diff --git a/ieducar/modules/Api/Views/MatriculaController.php b/ieducar/modules/Api/Views/MatriculaController.php index ac23981387..3bde9e06ee 100644 --- a/ieducar/modules/Api/Views/MatriculaController.php +++ b/ieducar/modules/Api/Views/MatriculaController.php @@ -575,7 +575,6 @@ protected function getDispensaDisciplina() { WHERE de.ref_cod_dispensa = dd.cod_dispensa ) AS td_dispensa_etapa WHERE dd.ativo = 1 - AND dd.data_exclusao IS NULL AND td_dispensa_etapa.etapas <> ''"; $dispensas = $this->fetchPreparedQuery($sql); From cb705a3963e4eceb46ace3e48ba91b3934051a42 Mon Sep 17 00:00:00 2001 From: bonot Date: Thu, 7 Jun 2018 10:28:49 -0300 Subject: [PATCH 8/8] =?UTF-8?q?Corrige=20verifica=C3=A7=C3=A3o=20de=20dado?= =?UTF-8?q?s=20de=20recursos=20inep?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit No sql o array inicia sempre de 1, por isso com 0 o valor vem sempre vazio --- ieducar/modules/Api/Views/EducacensoAnaliseController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ieducar/modules/Api/Views/EducacensoAnaliseController.php b/ieducar/modules/Api/Views/EducacensoAnaliseController.php index 914857f0b4..5bcc61c51a 100644 --- a/ieducar/modules/Api/Views/EducacensoAnaliseController.php +++ b/ieducar/modules/Api/Views/EducacensoAnaliseController.php @@ -1144,7 +1144,7 @@ protected function analisaEducacensoRegistro60() { municipio.cod_ibge AS municipio_inep, municipio.idmun AS idmun, aluno.cod_aluno AS cod_aluno, - aluno.recursos_prova_inep[0] AS recursos_prova_inep, + aluno.recursos_prova_inep[1] AS recursos_prova_inep, EXISTS (SELECT 1 FROM cadastro.fisica_deficiencia fd, cadastro.deficiencia d