/** * Search by the given word inside a model */ public static function onSearch($param = null) { $key = $param['key']; $seed = APPLICATION_NAME . 's8dkld83kf73kf094'; $hash = md5("{$seed}{$param['database']}{$param['key']}{$param['column']}{$param['model']}"); $operator = $param['operator'] ? $param['operator'] : 'like'; $mask = $param['mask']; if ($hash == $param['hash']) { try { TTransaction::open($param['database']); $repository = new TRepository($param['model']); $criteria = new TCriteria(); if ($param['criteria']) { $criteria = unserialize(base64_decode(str_replace(array('-', '_'), array('+', '/'), $param['criteria']))); } $column = $param['column']; if (stristr(strtolower($operator), 'like') !== FALSE) { $filter = new TFilter($column, $operator, "NOESC:'%{$param['value']}%'"); } else { $filter = new TFilter($column, $operator, "NOESC:'{$param['value']}'"); } $criteria->add($filter); $criteria->setProperty('order', $param['orderColumn']); $criteria->setProperty('limit', 1000); $collection = $repository->load($criteria, FALSE); $items = array(); if ($collection) { foreach ($collection as $object) { $k = $object->{$key}; $array_object = $object->toArray(); $maskvalues = $mask; foreach ($array_object as $property => $value) { $maskvalues = str_replace('{' . $property . '}', $value, $maskvalues); } $c = $maskvalues; if ($k != null && $c != null) { if (utf8_encode(utf8_decode($c)) !== $c) { $c = utf8_encode($c); } if (!empty($k) && !empty($c)) { $items[] = "{$k}::{$c}"; } } } } $ret = array(); $ret['result'] = $items; echo json_encode($ret); TTransaction::close(); } catch (Exception $e) { $ret = array(); $ret['result'] = array("1::" . $e->getMessage()); echo json_encode($ret); } } }
/** * Search by the given word inside a model */ public static function onSearch($param = null) { $seed = APPLICATION_NAME . 's8dkld83kf73kf094'; $hash = md5("{$seed}{$param['database']}{$param['column']}{$param['model']}"); $operator = $param['operator'] ? $param['operator'] : 'like'; if ($hash == $param['hash']) { try { TTransaction::open($param['database']); $repository = new TRepository($param['model']); $criteria = new TCriteria(); if ($param['criteria']) { $criteria = unserialize(base64_decode($param['criteria'])); } $column = $param['column']; if (stristr(strtolower($operator), 'like') !== FALSE) { $filter = new TFilter($column, $operator, "NOESC:'%{$param['query']}%'"); } else { $filter = new TFilter($column, $operator, "NOESC:'{$param['query']}'"); } $criteria->add($filter); $criteria->setProperty('order', $param['orderColumn']); $criteria->setProperty('limit', 1000); $collection = $repository->load($criteria, FALSE); $items = array(); if ($collection) { foreach ($collection as $object) { $c = $object->{$column}; if ($c != null) { if (utf8_encode(utf8_decode($c)) !== $c) { $c = utf8_encode($c); } if (!empty($c)) { $items[] = $c; } } } } $ret = array(); $ret['query'] = 'Unit'; $ret['suggestions'] = $items; echo json_encode($ret); TTransaction::close(); } catch (Exception $e) { $ret = array(); $ret['query'] = 'Unit'; $ret['suggestions'] = array($e->getMessage()); echo json_encode($ret); } } else { $ret = array(); $ret['query'] = 'Unit'; $ret['suggestions'] = NULL; echo json_encode($ret); } }
/** * method onReload() * Load the datagrid with the database objects */ public function onReload($param = NULL) { try { // open a transaction with database TTransaction::open($this->database); // instancia um repositório $repository = new TRepository($this->activeRecord); $limit = isset($this->limit) ? $this->limit > 0 ? $this->limit : NULL : 10; // creates a criteria $criteria = isset($this->criteria) ? clone $this->criteria : new TCriteria(); if ($this->order) { $criteria->setProperty('order', $this->order); $criteria->setProperty('direction', $this->direction); } $criteria->setProperties($param); // order, offset $criteria->setProperty('limit', $limit); // load the objects according to criteria $objects = $repository->load($criteria, FALSE); if (is_callable($this->transformCallback)) { call_user_func($this->transformCallback, $objects); } $this->datagrid->clear(); if ($objects) { // iterate the collection of active records foreach ($objects as $object) { // add the object inside the datagrid $this->datagrid->addItem($object); } } // reset the criteria for record count $criteria->resetProperties(); $count = $repository->count($criteria); if (isset($this->pageNavigation)) { $this->pageNavigation->setCount($count); // count of records $this->pageNavigation->setProperties($param); // order, page $this->pageNavigation->setLimit($limit); // limit } // close the transaction TTransaction::close(); $this->loaded = true; } catch (Exception $e) { // shows the exception error message new TMessage('error', $e->getMessage()); // undo all pending operations TTransaction::rollback(); } }
public function __construct() { //$this->objReader = new PHPExcel_Reader_Excel2007(); //$this->objReader->setReadDataOnly(true); TTransaction::open('saciq'); try { $this->referencia = array(); $rep = new TRepository('Referencia'); $import_name = $rep->load(); if ($import_name) { foreach ($import_name as $value) { $this->referencia[$value->nome] = $value->referencia; } } else { throw new Exception('Arquivo de configuração inválido'); } TTransaction::close(); } catch (Exception $ex) { new TMessage('error', $ex->getMessage()); TTransaction::rollback(); } //$objReader->setReadDataOnly(true); }
/** * Class Constructor * @param $name widget's name * @param $database database name * @param $model model class name * @param $key table field to be used as key in the combo * @param $value table field to be listed in the combo * @param $ordercolumn column to order the fields (optional) * @param $criteria criteria (TCriteria object) to filter the model (optional) */ public function __construct($name, $database, $model, $key, $value, $ordercolumn = NULL, TCriteria $criteria = NULL) { // executes the parent class constructor parent::__construct($name); if (empty($database)) { throw new Exception(AdiantiCoreTranslator::translate('The parameter (^1) of ^2 is required', 'database', __CLASS__)); } if (empty($model)) { throw new Exception(AdiantiCoreTranslator::translate('The parameter (^1) of ^2 is required', 'model', __CLASS__)); } if (empty($key)) { throw new Exception(AdiantiCoreTranslator::translate('The parameter (^1) of ^2 is required', 'key', __CLASS__)); } if (empty($value)) { throw new Exception(AdiantiCoreTranslator::translate('The parameter (^1) of ^2 is required', 'value', __CLASS__)); } // carrega objetos do banco de dados TTransaction::open($database); // instancia um repositório de Estado $repository = new TRepository($model); if (is_null($criteria)) { $criteria = new TCriteria(); } $criteria->setProperty('order', isset($ordercolumn) ? $ordercolumn : $key); // carrega todos objetos $collection = $repository->load($criteria, FALSE); // adiciona objetos na combo if ($collection) { $items = array(); foreach ($collection as $object) { $items[$object->{$key}] = $object->{$value}; } parent::addItems($items); } TTransaction::close(); }
/** * Load the datagrid with the active record objects */ public function onReload($param = NULL) { try { $model = TSession::getValue('standard_seek_model'); $database = TSession::getValue('standard_seek_database'); $pk = constant("{$model}::PRIMARYKEY"); // begins the transaction with database TTransaction::open($database); // creates a repository for the model $repository = new TRepository($model); $limit = 10; // creates a criteria if (TSession::getValue('standard_seek_criteria')) { $criteria = clone TSession::getValue('standard_seek_criteria'); } else { $criteria = new TCriteria(); // default order if (empty($param['order'])) { $param['order'] = $pk; $param['direction'] = 'asc'; } } $criteria->setProperties($param); // order, offset $criteria->setProperty('limit', $limit); if (TSession::getValue('tstandardseek_filter')) { // add the filter to the criteria $criteria->add(TSession::getValue('tstandardseek_filter')); } // load all objects according with the criteria $objects = $repository->load($criteria, FALSE); $this->datagrid->clear(); if ($objects) { $display_field = TSession::getValue('standard_seek_display_field'); foreach ($objects as $object) { $item = $object; $item->id = $object->{$pk}; $item->display_field = $object->{$display_field}; // add the object into the datagrid $this->datagrid->addItem($item); } } // clear the crieteria to count the records $criteria->resetProperties(); $count = $repository->count($criteria); $this->pageNavigation->setCount($count); // count of records $this->pageNavigation->setProperties($param); // order, page $this->pageNavigation->setLimit($limit); // limit // closes the transaction TTransaction::close(); $this->loaded = true; } catch (Exception $e) { // shows the exception genearated message new TMessage('error', '<b>Erro</b> ' . $e->getMessage()); // rollback all the database operations TTransaction::rollback(); } }
/** * method onGenerate() * Executed whenever the user clicks at the generate button */ function onGenerate() { try { // open a transaction with database 'saciq' TTransaction::open('saciq'); //TTransaction::setLogger(new TLoggerTXT("c:\\array\\LOG" . date("Ymd-His") . ".txt")); // get the form data into an active record $formdata = $this->form->getData(); $validadeI = $formdata->validadeI; $validadeF = TDate::date2us($formdata->validadeF); if (!$validadeI === 0) { $validadeI = '0'; } else { $validadeI = TDate::date2us($validadeI); } $this->form->validate(); $repository = new TRepository('Srp'); $criteria = new TCriteria(); $param['order'] = 'id'; $param['direction'] = 'desc'; $criteria->setProperties($param); if ($formdata->numeroProcessoI != '' && $formdata->numeroProcessoF != '') { $criteria->add(new TFilter('numeroProcesso', 'BETWEEN', "{$formdata->numeroProcessoI}", "{$formdata->numeroProcessoF}")); } if ($formdata->validadeI != '' && $formdata->validadeF != '') { $criteria->add(new TFilter('validade', 'between', "{$validadeI}", "{$validadeF}")); } if ($formdata->numeroSRPI != '' && $formdata->numeroSRPF != '') { $criteria->add(new TFilter('numeroSRP', 'between', "{$formdata->numeroSRPI}", "{$formdata->numeroSRPF}")); } if ($formdata->numeroIRPI != '' && $formdata->numeroIRPF != '') { $criteria->add(new TFilter('numeroIRP', 'between', "{$formdata->numeroIRPI}", "{$formdata->numeroIRPF}")); } $imprimeZero = true; if (isset($formdata->itensZero)) { if ($formdata->itensZero === '0') { $imprimeZero = false; } } $srps = $repository->load($criteria, true); if ($srps) { $this->pdf = new FPDF(); $this->pdf->AliasNbPages(); $this->pdf->SetMargins(10, 10, 10); $this->pdf->setHeaderCallback(array($this, 'header')); $this->pdf->setFooterCallback(array($this, 'footer')); $this->pdf->AddPage(); foreach ($srps as $srp) { $this->data = $srp; $this->srpHeader($imprimeZero); $this->srpItens($imprimeZero); } if (!file_exists("app/output/RelatorioSrp.pdf") or is_writable("app/output/RelatorioSrp.pdf")) { $this->pdf->Output("app/output/RelatorioSrp.pdf"); } else { throw new Exception('Permissão negada' . ': ' . "app/output/RelatorioSrp.pdf"); } parent::openFile("app/output/RelatorioSrp.pdf"); //new TMessage('info', 'Relatório gerado. Por favor, habilite o pop-up do seu browser.'); } else { new TMessage('error', 'Nenhum registro encontrado'); } // fill the form with the active record data $this->form->setData($formdata); // close the transaction TTransaction::close(); } catch (Exception $e) { // in case of exception if ($e->getCode() == 23000) { new TMessage('error', '<b>Registro duplicado</b><br>Verifique os campos inseridos e tente novamente'); } else { if ($e->getCode() == 0) { new TMessage('error', '<b>Error</b> <br>' . $e->getMessage()); } else { new TMessage('error', '<b>Error Desconhecido</b> <br>Código: ' . $e->getCode()); } } // desfazer todas as operacoes pendentes TTransaction::rollback(); } }
/** * Creates an ordered repository * @param $order = Order column * @param $direction = Order direction (asc, desc) * @returns the ordered TRepository object */ public static function orderBy($order, $direction = 'asc') { $class = get_called_class(); // get the Active Record class name $repository = new TRepository($class); // create the repository return $repository->orderBy($order, $direction); }
/** * method onReload() * carregar o datagrid com objetos do banco */ function onReload($param = NULL) { try { // open a transaction with database 'saciq' TTransaction::open('saciq'); // creates a repository for Funcionalidade $repository = new TRepository('Funcionalidade'); $limit = 10; // creates a criteria $criteria = new TCriteria(); if (!isset($param['order'])) { $param['order'] = 'id'; $param['direction'] = 'asc'; } $criteria->setProperties($param); // order, offset $criteria->setProperty('limit', $limit); if (TSession::getValue('Funcionalidade_nome_filter')) { // add the filter stored in the session to the criteria $criteria->add(TSession::getValue('Funcionalidade_nome_filter')); } if (TSession::getValue('Funcionalidade_control_filter')) { // add the filter stored in the session to the criteria $criteria->add(TSession::getValue('Funcionalidade_control_filter')); } // load the objects according to criteria $objects = $repository->load($criteria); $this->datagrid->clear(); if ($objects) { // iterate the collection of active records foreach ($objects as $object) { // add the object inside the datagrid $this->datagrid->addItem($object); } } // reset the criteria for record count $criteria->resetProperties(); $count = $repository->count($criteria); $this->pageNavigation->setCount($count); // count of records $this->pageNavigation->setProperties($param); // order, page $this->pageNavigation->setLimit($limit); // limit // close the transaction TTransaction::close(); $this->loaded = true; } catch (Exception $e) { if ($e->getCode() == 23000) { new TMessage('error', '<b>Registro duplicado</b><br>Verifique os campos inseridos e tente novamente'); } else { if ($e->getCode() == 0) { new TMessage('error', '<b>Error</b> <br>' . $e->getMessage()); } else { new TMessage('error', '<b>Error Desconhecido</b> <br>Código: ' . $e->getCode()); } } // desfazer todas as operacoes pendentes TTransaction::rollback(); } }
function onReload($param = NULL) { try { // abre uma transação com o banco 'saciq' TTransaction::open('saciq'); //TTransaction::setLogger(new \Adianti\Log\TLoggerTXT("c:\\array\\LOG".date("Ymd-His").".txt")); // cria um repository para Srp $repository = new TRepository('Srp'); $limit = 10; // cria um criteria $criteria = new TCriteria(); // ordem default if (empty($param['order'])) { $param['order'] = 'id'; $param['direction'] = 'asc'; } $criteria->setProperties($param); // ordem, offset $criteria->setProperty('limit', $limit); if (TSession::getValue('SrpList_filter_numeroSRP')) { $criteria->add(TSession::getValue('SrpList_filter_numeroSRP')); // add the session filter } if (TSession::getValue('SrpList_filter_numeroIRP')) { $criteria->add(TSession::getValue('SrpList_filter_numeroIRP')); // add the session filter } if (TSession::getValue('SrpList_filter_numeroProcesso')) { $criteria->add(TSession::getValue('SrpList_filter_numeroProcesso')); // add the session filter } if (TSession::getValue('SrpList_filter_uasg')) { $criteria->add(TSession::getValue('SrpList_filter_uasg')); // add the session filter } if (TSession::getValue('SrpList_filter_validade')) { $criteria->add(TSession::getValue('SrpList_filter_validade')); // add the session filter } if (TSession::getValue('SrpList_filter_nome')) { $criteria->add(TSession::getValue('SrpList_filter_nome')); // add the session filter } // carrega os objetos de acordo com os filtros $objects = $repository->load($criteria, FALSE); $this->datagrid->clear(); if ($objects) { // iterar a coleção de active records foreach ($objects as $object) { //muda a data para o formato brasileiro (DD/MM/YYYY) $object->validade = TDate::date2br($object->validade); //adiciona o objeto no datagrid $this->datagrid->addItem($object); } } // reseta o criteria (filtro) para contagem de registros $criteria->resetProperties(); $count = $repository->count($criteria); $this->pageNavigation->setCount($count); // contagem de registro $this->pageNavigation->setProperties($param); // ordem, pagina $this->pageNavigation->setLimit($limit); // limite // fecha a transação TTransaction::close(); $this->loaded = true; } catch (Exception $e) { if ($e->getCode() == 23000) { new TMessage('error', '<b>Registro duplicado</b><br>Verifique os campos inseridos e tente novamente'); } else { if ($e->getCode() == 0) { new TMessage('error', '<b>Error</b> <br>' . $e->getMessage()); } else { new TMessage('error', '<b>Error Desconhecido</b> <br>Código: ' . $e->getCode()); } } // desfazer todas as operacoes pendentes TTransaction::rollback(); } }
/** * Load the datagrid with the database objects */ function onReload($param = NULL) { try { // open a transaction with database 'samples' TTransaction::open('sobcontrole'); // creates a repository for City $repository = new TRepository('tipocontato'); $limit = 10; // creates a criteria $criteria = new TCriteria(); // default order if (!isset($param['order'])) { $param['order'] = 'idtipocontato'; $param['direction'] = 'asc'; } $criteria->setProperties($param); // order, offset $criteria->setProperty('limit', $limit); if (TSession::getValue('tipocontato_filtro')) { // add the filter stored in the session to the criteria $criteria->add(TSession::getValue('tipocontato_filtro')); } // load the objects according to the criteria $tiposdecontato = $repository->load($criteria); $this->datagrid->clear(); if ($tiposdecontato) { foreach ($tiposdecontato as $tipocontato) { // add the object inside the datagrid $this->datagrid->addItem($tipocontato); } } // reset the criteria for record count $criteria->resetProperties(); $count = $repository->count($criteria); $this->pageNavigation->setCount($count); // count of records $this->pageNavigation->setProperties($param); // order, page $this->pageNavigation->setLimit($limit); // limit // close the transaction TTransaction::close(); $this->loaded = true; } catch (Exception $e) { // shows the exception error message new TMessage('error', $e->getMessage()); // undo all pending operations TTransaction::rollback(); } }
function onReload($param) { $this->dg_UltImportacao->clear(); $this->dg_UltRequisicao->clear(); $this->dg_UltCesssao->clear(); $this->dg_SRPAVencer->clear(); try { TTransaction::open('saciq'); //TTransaction::setLogger(new TLoggerTXT("c:\\array\\LOG".date("Ymd-His").".txt")); //ultimas importações $criteriaUI = new TCriteria(); $param['order'] = 'id'; $param['direction'] = 'desc'; $criteriaUI->setProperties($param); $criteriaUI->setProperty('limit', 8); $repositoryUI = new TRepository('Srp'); $srps = $repositoryUI->load($criteriaUI, false); foreach ($srps as $srp) { $srp->validade = TDate::date2br($srp->validade); $this->dg_UltImportacao->addItem($srp); } //ultimas Requisições $criteriaUR = new TCriteria(); $param['order'] = 'emissao'; $param['direction'] = 'desc'; $criteriaUR->setProperties($param); $criteriaUR->setProperty('limit', 8); $repositoryUR = new TRepository('Requisicao'); $requisicoes = $repositoryUR->load($criteriaUR, false); foreach ($requisicoes as $requisicao) { $requisicao->numeroSRP = $requisicao->srp->numeroSRP; $requisicao->aprovado = $requisicao->aprovado == 0 ? 'Não' : 'Sim'; $requisicao->emissao = TDate::date2br($requisicao->emissao); $this->dg_UltRequisicao->addItem($requisicao); } //Atas a vencer $criteriaAV = new TCriteria(); $param['order'] = 'validade'; $param['direction'] = 'asc'; $criteriaAV->setProperties($param); $criteriaAV->setProperty('limit', 8); $criteriaAV->add(new TFilter('validade', '>=', date("Y-m-d"))); $repositoryAV = new TRepository('Srp'); $atasAVencer = $repositoryAV->load($criteriaAV, false); foreach ($atasAVencer as $atas) { $atas->validade = TDate::date2br($atas->validade); $this->dg_SRPAVencer->addItem($atas); } //ultimas Cessões $criteriaUC = new TCriteria(); $param['order'] = 'emissao'; $param['direction'] = 'desc'; $criteriaUC->setProperties($param); $criteriaUC->setProperty('limit', 8); $repositoryUC = new TRepository('Cessao'); $cessoes = $repositoryUC->load($criteriaUC, false); foreach ($cessoes as $cessao) { $cessao->numeroSRP = $cessao->srp->numeroSRP; $cessao->aprovado = $cessao->aprovado == 0 ? 'Não' : 'Sim'; $cessao->emissao = TDate::date2br($cessao->emissao); $this->dg_UltCesssao->addItem($cessao); } $this->loaded = true; TTransaction::close(); } catch (Exception $e) { if ($e->getCode() == 23000) { new TMessage('error', '<b>Registro duplicado</b><br>Verifique os campos inseridos e tente novamente'); } else { if ($e->getCode() == 0) { new TMessage('error', '<b>Error</b> <br>' . $e->getMessage()); } else { new TMessage('error', '<b>Error Desconhecido</b> <br>Código: ' . $e->getCode()); } } // desfazer todas as operacoes pendentes TTransaction::rollback(); } }
/** * Load aggregated objects (parts in aggregation relationship) * @param $aggregate_class Active Record Class for aggregated objects * @param $join_class Active Record Join Class (Parent / Aggregated) * @param $foreign_key_parent Foreign key in Join Class to parent object * @param $foreign_key_child Foreign key in Join Class to child object * @param $id Primary key of parent object * @returns Array of Active Records */ public function loadAggregate($aggregate_class, $join_class, $foreign_key_parent, $foreign_key_child, $id) { $criteria = new TCriteria(); $criteria->add(new TFilter($foreign_key_parent, '=', $id)); $repository = new TRepository($join_class); $objects = $repository->load($criteria); $aggregates = array(); if ($objects) { foreach ($objects as $object) { $aggregates[] = new $aggregate_class($object->{$foreign_key_child}); } } return $aggregates; }
/** * Returns a SystemUser object based on its login * @param $login String with user login */ public static function newFromLogin($login) { $repos = new TRepository('Usuario'); $criteria = new TCriteria(); $criteria->add(new TFilter('prontuario', '=', $login)); $objects = $repos->load($criteria); if (isset($objects[0])) { return $objects[0]; } }
/** * method onReload() * Load the datagrid with the database objects */ function onReload($param = NULL) { try { // open a transaction with database 'saciq' TTransaction::open('saciq'); //TTransaction::setLogger(new TLoggerTXT('c:\array\file.txt')); // creates a repository for Cessao $repository = new TRepository('Cessao'); $limit = 10; // creates a criteria $criteria = new TCriteria(); // default order if (empty($param['order'])) { $param['order'] = 'id'; $param['direction'] = 'asc'; } $criteria->setProperties($param); // order, offset $criteria->setProperty('limit', $limit); $criteria->add(new TFilter('aprovado', '=', '1')); if (TSession::getValue('CessaoList_filter_numeroCessao')) { $criteria->add(TSession::getValue('CessaoList_filter_numeroCessao')); // add the session filter } // load the objects according to criteria $objects = $repository->load($criteria, FALSE); $this->datagrid->clear(); if ($objects) { // iterate the collection of active records foreach ($objects as $object) { if ($object->srp->estaVencida()) { continue; } $object->emissao = TDate::date2br($object->emissao); $object->numeroSRP = $object->srp->numeroSRP; $this->datagrid->addItem($object); } } // close the transaction TTransaction::close(); $this->loaded = true; } catch (Exception $e) { if ($e->getCode() == 23000) { new TMessage('error', '<b>Registro duplicado</b><br>Verifique os campos inseridos e tente novamente'); } else { if ($e->getCode() == 0) { new TMessage('error', '<b>Error</b> <br>' . $e->getMessage()); } else { new TMessage('error', '<b>Error Desconhecido</b> <br>Código: ' . $e->getCode()); } } // desfazer todas as operacoes pendentes TTransaction::rollback(); } }
/** * Delete the object and its aggregates * @param $id object ID */ public function delete($id = NULL) { // delete the related System_groupSystem_program objects $id = isset($id) ? $id : $this->id; $repository = new TRepository('GrupoFuncionalidade'); $criteria = new TCriteria(); $criteria->add(new TFilter('grupo_id', '=', $id)); $repository->delete($criteria); // delete the object itself parent::delete($id); }
public function onGenerate($param) { //var_dump($param); $this->B = 0; $this->I = 0; $this->U = 0; $this->HREF = ''; $data = $this->form->getData(); $id = $data->cessao_id; $this->pdf = new FPDF(); $this->pdf->AliasNbPages(); setlocale(LC_ALL, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese'); try { TTransaction::open('saciq'); $this->form->validate(); $cessao = new Cessao($id); $itens_list = $cessao->getItems(); if (count($itens_list) == 0) { new TMessage('error', 'Nenhum item encontrado na cessão'); $this->form->sendData('doc_cessao_form', $data); return; } $memorando = utf8_decode($data->memorando); $emissao = TDate::date2us($data->emissao); $repository = new TRepository('Campus'); $criteria = new TCriteria(); $criteria->add(new TFilter('sigla', '=', CAMPUS)); $campus_list = $repository->load($criteria); $campus = $campus_list[0]; $this->cidade = $campus->nome; $destino = strtoupper($data->campusNome); $this->gerente = $data->gerente; $this->diretor = $data->diretor; $emissao = strtotime($emissao); $mes = ucfirst(strftime('%B', $emissao)); $emissao = $this->cidade . ', ' . strftime(" %d de {$mes} de %Y.", $emissao); $srp = $cessao->srp->numeroSRP; $natureza = $cessao->srp->natureza->descricao; $nomeSrp = $cessao->srp->nome; //$this->pdf->Open(); $this->pdf->SetMargins(25, 20, 25); $this->pdf->setHeaderCallback(array($this, 'Header')); //$this->pdf->setFooterCallback(array($this, 'Footer')); $this->pdf->AddPage(); $this->pdf->SetFont('Times', '', 12); //$this->pdf->Cell(15); $this->pdf->Cell(0, 5, "{$memorando}", 0, 1); $this->pdf->Ln(10); $this->pdf->Cell(0, 5, $emissao, 0, 0, 'R'); $this->pdf->Ln(10); $this->pdf->Cell(0, 5, utf8_decode('À'), 0, 1); $this->pdf->Cell(0, 5, utf8_decode("GERÊNCIA ADMINISTRATIVA DO CAMPUS {$destino}")); $this->pdf->Ln(10); $this->pdf->SetFont('Times', 'B', 12); $this->pdf->MultiCell(0, 5, utf8_decode("ASSUNTO: CESSÃO DE QUANTITATIVO - SRP {$srp} - {$natureza} - {$nomeSrp}")); $this->pdf->SetFont('Times', '', 12); $this->pdf->Ln(15); $this->pdf->SetX(21); $this->WriteHTML(utf8_decode("1.Conforme solicitação, autorizamos a utilização do quantitativo abaixo referido," . "referente a estimativa do Câmpus Capivari para a <B>SRP {$srp} - {$natureza} - {$nomeSrp}</B>")); $this->pdf->Ln(10); //cabecalho da tabela $y = $this->pdf->GetY(); $x = $this->pdf->GetX(); $this->pdf->SetFont('Times', 'B', 12); $width = array(18, 107, 38); $this->pdf->MultiCell($width[0], 10, utf8_decode('ITEM'), 1, 'C'); $this->pdf->SetXY($x += $width[0], $y); $this->pdf->MultiCell($width[1], 10, utf8_decode("DESCRIÇÃO"), 1, 'C'); $this->pdf->SetXY($x += $width[1], $y); $this->pdf->MultiCell($width[2], 10, utf8_decode('QUANT.'), 1, 'C'); $this->pdf->SetFont('Times', '', 12); $this->pdf->ln(0); $y = $this->pdf->GetY(); $x = $this->pdf->GetX(); usort($itens_list, array("DocCessaoForm", "cmp")); //preencher a tabela foreach ($itens_list as $item) { $numeroItem = $item->numeroItem; $descricaoSumaria = substr($item->descricaoSumaria, 0, 80); $quantidade = $item->quantidade; $t1 = $this->pdf->GetStringWidth($descricaoSumaria); $tamanhoTexto = $t1; $tamanhoDesc = $width[1]; $qtdLinha = 1; $offset = 0; $atualSize = 0; while (true) { $pos = strpos($descricaoSumaria, ' ', $offset); if ($pos === FALSE) { while ($tamanhoTexto > $tamanhoDesc) { $qtdLinha++; $tamanhoTexto -= $tamanhoDesc; } break; } $textCompare = substr($descricaoSumaria, $offset, $pos - $offset); $textSize = $this->pdf->GetStringWidth($textCompare . ' '); if ($textSize + $atualSize > $tamanhoDesc) { $qtdLinha++; $tamanhoTexto -= $atualSize; $atualSize = 0; } else { $atualSize += $textSize; $offset = $pos + 1; } } if ($qtdLinha == 1) { $qtdLinha = 2; } $alturaLinha = 5 * $qtdLinha; if ($this->pdf->GetY() + $alturaLinha > 280) { $this->pdf->Cell(array_sum($width), 0, '', 'T'); $this->pdf->AddPage(); $y = $this->pdf->GetY(); $x = $this->pdf->GetX(); } $this->pdf->MultiCell($width[0], $alturaLinha, utf8_decode($numeroItem), 'LRT', 'C'); $this->pdf->SetXY($x += $width[0], $y); $this->pdf->MultiCell($width[1], 5, utf8_decode($descricaoSumaria), 'LRT', 'J'); $this->pdf->SetXY($x += $width[1], $y); $this->pdf->MultiCell($width[2], $alturaLinha, utf8_decode($quantidade), 'LRT', 'C'); $this->pdf->Ln(0); $y = $this->pdf->GetY(); $x = $this->pdf->GetX(); } $this->pdf->Cell(array_sum($width), 0, '', 'T'); if ($this->pdf->GetY() + $alturaLinha > 210) { $this->pdf->AddPage(); $this->ImprimiNoRodape = false; } else { $this->ImprimiNoRodape = true; } $this->Footer(); if (!file_exists("app/output/doc.pdf") or is_writable("app/output/doc.pdf")) { $this->pdf->Output("app/output/doc.pdf"); } else { throw new Exception('Permissão negada' . ': ' . "app/output/doc.pdf"); } parent::openFile('app/output/doc.pdf'); $this->form->sendData('doc_cessao_form', $data); TTransaction::close(); } catch (Exception $e) { if ($e->getCode() == 23000) { new TMessage('error', '<b>Registro duplicado</b><br>Verifique os campos inseridos e tente novamente'); } else { if ($e->getCode() == 0) { new TMessage('error', '<b>Error</b> <br>' . $e->getMessage()); } else { new TMessage('error', '<b>Error Desconhecido</b> <br>Código: ' . $e->getCode()); } } // desfazer todas as operacoes pendentes TTransaction::rollback(); } }
public function onReload($param = null) { try { $this->list1->setDefault(); $this->list2->setDefault(); TTransaction::open('saciq'); if (isset($param['key'])) { $key = $param['key']; $grupo = new Grupo($key); if ($grupo->getFuncionalidades()) { $list2Items = array(); foreach ($grupo->getFuncionalidades() as $funcionalidade) { $list2Items[$funcionalidade->id] = $funcionalidade->nome; } $this->list2->addItems($list2Items); } } $repository = new TRepository('Funcionalidade'); $funcionalidades = $repository->load(); foreach ($funcionalidades as $f) { $id = $f->id; if (!isset($list2Items[$id])) { $list1Items[$id] = $f->nome; } } if (isset($list1Items)) { $this->list1->addItems($list1Items); } $this->loaded = true; TTransaction::close(); } catch (Exception $e) { if ($e->getCode() == 23000) { new TMessage('error', '<b>Registro duplicado</b><br>Verifique os campos inseridos e tente novamente'); } else { if ($e->getCode() == 0) { new TMessage('error', '<b>Error</b> <br>' . $e->getMessage()); } else { new TMessage('error', '<b>Error Desconhecido</b> <br>Código: ' . $e->getCode()); } } // desfazer todas as operacoes pendentes TTransaction::rollback(); } //$this->list1->addItems(array('1' => 'One', '2' => 'Two', '3' => 'Three')); }
public function createfile($filename) { //pega o usuário salvo na sessão $usuario = TSession::getValue('nome'); //adiciona o autor no arquivo $this->objPHPExcel->getProperties()->setCreator($usuario)->setLastModifiedBy($usuario); $sheet = $this->objPHPExcel->setActiveSheetIndex(0); $criteria = new TCriteria(); $criteria->add(new TFilter('sigla', '=', CAMPUS)); $rep = new TRepository('Campus'); $campusRep = $rep->load($criteria); if (isset($campusRep[0])) { $campus = $campusRep[0]; } else { throw new Exception('Erro na seleção do câmpus'); } $cabecalho = "REQUISIÇÕES DA ATA DE REGISTO DE PREÇOS SRP " . $this->array_obj[0]->NroSrp . " (" . $this->array_obj[0]->NomeLicitacao . ") - " . $campus->nome; //style $style_titulo = array('font' => array('name' => 'Arial', 'size' => 16, 'underline' => true, 'bold' => true), 'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER)); $style_headers = array('font' => array('name' => 'Arial', 'size' => 12, 'bold' => true), 'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, 'wrap' => true), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN, 'color' => array('argb' => 'FFFF0000')))); $style_data = array('font' => array('name' => 'Arial', 'size' => 12), 'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, 'wrap' => true), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN, 'color' => array('argb' => 'FFFF0000')))); $style_subtotal = array('font' => array('name' => 'Arial', 'size' => 12), 'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, 'wrap' => true), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN, 'color' => array('argb' => 'FF000000'))), 'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'startcolor' => array('argb' => 'FFD9D9D9'))); $sheet->getStyle('A1:W1')->applyFromArray($style_titulo); $sheet->getStyle('A2:W2')->applyFromArray($style_headers); $sheet->getDefaultRowDimension()->setRowHeight(72.75); //define a largura das colunas $sheet->getColumnDimension('A')->setWidth(18); $sheet->getColumnDimension('B')->setWidth(33); $sheet->getColumnDimension('C')->setWidth(12); $sheet->getColumnDimension('D')->setWidth(33); $sheet->getColumnDimension('E')->setWidth(12); $sheet->getColumnDimension('F')->setWidth(56); $sheet->getColumnDimension('G')->setWidth(19); $sheet->getColumnDimension('H')->setWidth(22); $sheet->getColumnDimension('I')->setWidth(24); $sheet->getColumnDimension('J')->setWidth(15); $sheet->getColumnDimension('K')->setWidth(15); $sheet->getColumnDimension('L')->setWidth(15); $sheet->getColumnDimension('M')->setWidth(15); $sheet->getColumnDimension('N')->setWidth(18); $sheet->getColumnDimension('O')->setWidth(12); $sheet->getColumnDimension('P')->setWidth(49); $sheet->getColumnDimension('Q')->setWidth(18); $sheet->getColumnDimension('R')->setWidth(20); $sheet->getColumnDimension('S')->setWidth(25); $sheet->getColumnDimension('T')->setWidth(84); $sheet->getColumnDimension('U')->setWidth(27); $sheet->getColumnDimension('V')->setWidth(25); $sheet->getColumnDimension('W')->setWidth(49); //adiciona o cabeçalho $sheet->setCellValue('A1', $cabecalho); $sheet->mergeCells('A1:W1'); $sheet->setCellValue('A2', 'DATA REQUISIÇÃO'); $sheet->setCellValue('B2', 'Nº PROC AQUISIÇÃO'); $sheet->setCellValue('C2', 'Nº SRP'); $sheet->setCellValue('D2', 'PROC ORIG'); $sheet->setCellValue('E2', 'UASG'); $sheet->setCellValue('F2', 'NOME DA LICITAÇÃO'); $sheet->setCellValue('G2', 'SUBELEMENTO'); $sheet->setCellValue('H2', 'VALIDADE DA ATA'); $sheet->setCellValue('I2', 'PRAZO DE ENTREGA'); $sheet->setCellValue('J2', 'ESTIMATIVO CAMPUS'); $sheet->setCellValue('K2', 'ORÇAMENTO CAMPUS'); $sheet->setCellValue('L2', 'CAMPUS DE DESTINO'); $sheet->setCellValue('M2', 'LOCAL DE ENTREGA'); $sheet->setCellValue('N2', "MARQUE COM UM 'X' NOS ITENS NÃO EMPENHADOS"); $sheet->setCellValue('O2', 'ITEM'); $sheet->setCellValue('P2', 'DESCRIÇÃO SUMÁRIA'); $sheet->setCellValue('Q2', 'QTD SOLICITADA'); $sheet->setCellValue('R2', 'VALOR LICITADO UNITÁRIO'); $sheet->setCellValue('S2', 'VALOR LICITADO TOTAL'); $sheet->setCellValue('T2', 'FORNECEDOR'); $sheet->setCellValue('U2', 'CNPJ'); $sheet->setCellValue('V2', 'CONTRATO'); $sheet->setCellValue('W2', 'JUSTIFICATIVA DA AQUISIÇÃO POR ITEM'); $row = 3; $fornecedor = $this->array_obj[0]->fornecedor; $fornecedor_startCel = "S{$row}"; $fornecedor_endCel = "S{$row}"; foreach ($this->array_obj as $obj) { if ($fornecedor != $obj->fornecedor) { $sheet->setCellValueByColumnAndRow(18, $row, "=SUBTOTAL(9,{$fornecedor_startCel}:{$fornecedor_endCel})"); $sheet->getStyleByColumnAndRow(18, $row)->getNumberFormat()->setFormatCode('_("R$ "* #.##0,00_);_("R$ "* (#.##0,00);_("R$ "* "-"??_);_(@_)'); $sheet->setCellValueByColumnAndRow(19, $row, $fornecedor . ' Total'); $sheet->getStyle("A{$row}:W{$row}")->applyFromArray($style_subtotal); $fornecedor = $obj->fornecedor; $row++; $fornecedor_startCel = "S{$row}"; } $sheet->setCellValueByColumnAndRow(0, $row, $obj->DataRequisicao); $sheet->setCellValueByColumnAndRow(1, $row, $obj->NroProcAquisicao); $sheet->setCellValueByColumnAndRow(2, $row, $obj->NroSrp); $sheet->setCellValueByColumnAndRow(3, $row, $obj->ProcOrig); $sheet->setCellValueByColumnAndRow(4, $row, $obj->UASG); $sheet->setCellValueByColumnAndRow(5, $row, $obj->NomeLicitacao); $sheet->setCellValueByColumnAndRow(6, $row, $obj->SubElemento); $sheet->setCellValueByColumnAndRow(7, $row, $obj->ValidadeAta); $sheet->setCellValueByColumnAndRow(8, $row, $obj->PrazoEntrega); $sheet->setCellValueByColumnAndRow(9, $row, $obj->EstimativoCampus); $sheet->setCellValueByColumnAndRow(10, $row, $obj->OrcamentoCampus); $sheet->setCellValueByColumnAndRow(11, $row, $obj->CampusDestino); $sheet->setCellValueByColumnAndRow(12, $row, $obj->LocalEntrega); $sheet->setCellValueByColumnAndRow(13, $row, ''); $sheet->setCellValueByColumnAndRow(14, $row, $obj->Item); $sheet->setCellValueByColumnAndRow(15, $row, $obj->DescricaoSumaria); $sheet->setCellValueByColumnAndRow(16, $row, $obj->QtdSolicitada); $sheet->setCellValueByColumnAndRow(17, $row, $obj->ValorLicitadoUnitario); $sheet->setCellValueByColumnAndRow(18, $row, "=Q{$row}*R{$row}"); $sheet->getStyleByColumnAndRow(18, $row)->getNumberFormat()->setFormatCode('_("R$ "* #.##0,00_);_("R$ "* (#.##0,00);_("R$ "* "-"??_);_(@_)'); $sheet->setCellValueByColumnAndRow(19, $row, $obj->fornecedor); $sheet->setCellValueByColumnAndRow(20, $row, $this->mask($obj->cnpj, '##.###.###/####-##')); $sheet->setCellValueByColumnAndRow(21, $row, ''); $sheet->setCellValueByColumnAndRow(22, $row, $obj->justificativa); $sheet->getStyle("A{$row}:W{$row}")->applyFromArray($style_data); $fornecedor_endCel = "S{$row}"; $row++; } //$sheet->setCellValueByColumnAndRow(18, $row, "=SUBTOTAL(9;{$fornecedor_startCel}:{$fornecedor_endCel})"); //$sheet->setCellValueExplicitByColumnAndRow(18, $row, '=SUM(S3:S4)'); $sheet->setCellValueByColumnAndRow(18, $row, "=SUBTOTAL(9,{$fornecedor_startCel}:{$fornecedor_endCel})"); $sheet->getStyleByColumnAndRow(18, $row)->getNumberFormat()->setFormatCode('_("R$ "* #.##0,00_);_("R$ "* (#.##0,00);_("R$ "* "-"??_);_(@_)'); $sheet->setCellValueByColumnAndRow(19, $row, $fornecedor . ' Total'); $sheet->getStyle("A{$row}:W{$row}")->applyFromArray($style_subtotal); $row++; $sheet->setCellValueByColumnAndRow(18, $row, "=SUBTOTAL(9,S3:{$fornecedor_endCel})"); $sheet->getStyleByColumnAndRow(18, $row)->getNumberFormat()->setFormatCode('_("R$ "* #.##0,00_);_("R$ "* (#.##0,00);_("R$ "* "-"??_);_(@_)'); $sheet->setCellValueByColumnAndRow(19, $row, 'Total Geral'); $sheet->getStyle("A{$row}:W{$row}")->applyFromArray($style_subtotal); $row++; $this->objPHPExcel->setActiveSheetIndex(0); /* // Redirect output to a client’s web browser (Excel2007) header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"'); header('Cache-Control: max-age=0'); // If you're serving to IE 9, then the following may be needed header('Cache-Control: max-age=1'); // If you're serving to IE over SSL, then the following may be needed header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified header('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header('Pragma: public'); // HTTP/1.0 */ $file = "app/output/" . $filename . ".xlsx"; $objWriter = PHPExcel_IOFactory::createWriter($this->objPHPExcel, 'Excel2007'); $objWriter->save($file); /* header("Pragma: public"); header("Expires: 0"); // set expiration time header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); header("Content-Length: " . filesize($file)); header("Content-disposition: inline; filename=\"{$file}\""); header("Content-Transfer-Encoding: binary"); //echo file_get_contents($file); readfile($file); */ }
public function onSelect($param) { try { //var_dump($param); $key = $param['key']; if (!$key) { return; } TTransaction::open('saciq'); //$srp = new Srp($key); $repository = new TRepository('Srp'); $criteria = new TCriteria(); $criteria->add(new TFilter('numeroSRP', '=', $key)); $srps = $repository->load($criteria); if (count($srps) > 0) { $srp = $srps[0]; } if ($srp->estaVencida()) { new TMessage('error', 'SRP Vencida!'); return; } $oldSRP = NULL; if ($oldSRP != TSession::getValue('SRP_id')) { $oldSRP = TSession::getValue('SRP_id'); } if ($oldSRP != $srp->id) { if (TSession::getValue('cessao_itens')) { $reloadForm = true; } TSession::delValue('cessao_itens'); $obj = new stdClass(); $obj->numeroItem = ''; $obj->descricaoSumaria = ''; $obj->valorUnitario = ''; $obj->quantidade = ''; //$obj->prazoEntrega = '60 Dias'; //$obj->justificativa = ''; TForm::sendData('form_itens', $obj); } TSession::setValue('SRP_id', $srp->id); $obj = new stdClass(); $obj->numeroSRP = $srp->numeroSRP; $obj->nome = $srp->nome; $obj->numeroProcessoOrigem = $srp->numeroProcesso; $obj->uasg = $srp->uasg; $obj->validade = TDate::date2br($srp->validade); TForm::sendData('form_cessao', $obj); TSession::setValue('form_cessao', $obj); if (isset($reloadForm) && $reloadForm) { TScript::create("__adianti_load_page2('engine.php?class=CessaoForm');"); //new TScript("__adianti_load_page('engine?class=CessaoForm');"); } //AdiantiCoreApplication::executeMethod('CessaoForm','onReload'); TTransaction::close(); parent::closeWindow(); } catch (Exception $e) { $obj = new stdClass(); $obj->numeroSRP = ''; $obj->nome = ''; $obj->numeroProcesso = ''; $obj->uasg = ''; $obj->validade = ''; TForm::sendData('cessao_form', $obj); TTransaction::rollback(); } }
function onImportFile() { $data = $this->form->getData(); $this->importacao = new Importar(); $this->importacao->loadFile($data->file); $this->importacao->setActiveRow(3); try { TTransaction::open('saciq'); $criteria = new TCriteria(); $criteria->add(new TFilter('numeroSRP', '=', $this->importacao->getNroSRP())); $criteria->add(new TFilter('numeroIRP', '=', $this->importacao->getNroIRP())); $criteria->add(new TFilter('numeroProcesso', '=', $this->importacao->getNumeroProcesso())); $criteria->add(new TFilter('uasg', '=', $this->importacao->getUasgGerenciadora())); $criteria->add(new TFilter('validade', '=', $this->importacao->getValidadeAta())); $repositorySrp = new TRepository('Srp'); $count = $repositorySrp->count($criteria); if ($count > 0) { $RepSRP = $repositorySrp->load($criteria); $RepSRP[0]->delete(); } $srp = null; while (!$this->importacao->eof()) { if (!$this->importacao->isValidRow()) { $this->importacao->nextRow(); continue; } $natureza = $this->LoadObjectByField('Natureza', 'descricao', $this->importacao->getNaturezaDespesa()); if (!isset($natureza)) { $natureza = new Natureza(); $natureza->descricao = $this->importacao->getNaturezaDespesa(); $natureza->store(); } $subelemento = $this->LoadObjectByField('Subelemento', 'descricao', $this->importacao->getDescricaoSubElemento()); if (!isset($subelemento)) { $subelemento = new Subelemento(); $subelemento->id = $this->importacao->getNumeroSubElemento(); $subelemento->descricao = $this->importacao->getDescricaoSubElemento(); $subelemento->store(); } $fornecedor = $this->LoadObjectByField('Fornecedor', 'cnpj', $this->importacao->getCNPJ()); if (!isset($fornecedor)) { $fornecedor = new Fornecedor(); $fornecedor->nome = $this->importacao->getFornecedor(); $fornecedor->cnpj = $this->importacao->getCNPJ(); $fornecedor->store(); } if (!isset($srp)) { $srp = new Srp(); $srp->numeroSRP = $this->importacao->getNroSRP(); $srp->numeroIRP = $this->importacao->getNroIRP(); $srp->numeroProcesso = $this->importacao->getNumeroProcesso(); $srp->uasg = $this->importacao->getUasgGerenciadora(); $srp->validade = $this->importacao->getValidadeAta(); $srp->nome = $this->importacao->getNomeProcesso(); $srp->natureza = $natureza; } $item = new Item(); $item->numeroItem = $this->importacao->getItem(); $item->descricaoSumaria = $this->importacao->getDescricaoSumaria(); $item->descricaoCompleta = $this->importacao->getDescricaoCompleta(); $item->descricaoPosLicitacao = $this->importacao->getDescricaoPosLicitacao(); $item->unidadeMedida = $this->importacao->getUnidadeDeMedida(); $item->marca = $this->importacao->getMarca(); $item->valorUnitario = $this->importacao->getValorUnitarioLicitado(); $item->quantidadeDisponivel = $this->importacao->getOrgao(CAMPUS); $item->estoqueDisponivel = $item->quantidadeDisponivel; $item->fabricante = $this->importacao->getFabricante(); $item->fornecedor = $fornecedor; $item->subelemento = $subelemento; $srp->addItem($item); $this->importacao->nextRow(); } $srp->store(); new TMessage('info', 'Planilha importada com sucesso'); TTransaction::close(); } catch (Exception $e) { if ($e->getCode() == 23000) { new TMessage('error', '<b>Registro duplicado</b><br>Verifique os campos inseridos e tente novamente'); } else { if ($e->getCode() == 0) { new TMessage('error', '<b>Error</b> <br>' . $e->getMessage()); } else { new TMessage('error', '<b>Error Desconhecido</b> <br>Código: ' . $e->getCode()); } } // desfazer todas as operacoes pendentes TTransaction::rollback(); } $this->notebook->setCurrentPage(0); $this->form->setData($data); $this->step->select('Seleção'); }
/** * method onReload() * carregar o datagrid com objetos do banco */ function onReload($param = NULL) { try { // abre uma transacao com o banco 'saciq' TTransaction::open('saciq'); if (!isset($param['order'])) { $param['order'] = 'id'; $param['direction'] = 'asc'; } // cria um repository para Grupo $repository = new TRepository('Grupo'); $limit = 10; // cria um criteria $criteria = new TCriteria(); $criteria->setProperties($param); // order, offset $criteria->setProperty('limit', $limit); if (TSession::getValue('s_nome_filter')) { // adiciona o filtro gravado na sessao para o obj criteria. $criteria->add(TSession::getValue('s_nome_filter')); } if (TSession::getValue('s_sigla_filter')) { // adiciona o filtro gravado na sessao para o obj criteria. $criteria->add(TSession::getValue('s_sigla_filter')); } // carrega os objetos de acordo o filtro criteria $objects = $repository->load($criteria); $this->datagrid->clear(); if ($objects) { // iterar a coleção de active records foreach ($objects as $object) { // adiciona o objeto dentro do datagrid $this->datagrid->addItem($object); } } // reset o criteria para o record count $criteria->resetProperties(); $count = $repository->count($criteria); $this->pageNavigation->setCount($count); // quantidade de registros $this->pageNavigation->setProperties($param); // ordem, pagina $this->pageNavigation->setLimit($limit); // limite // fecha a transacao TTransaction::close(); $this->loaded = true; } catch (Exception $e) { if ($e->getCode() == 23000) { new TMessage('error', '<b>Registro duplicado</b><br>Verifique os campos inseridos e tente novamente'); } else { if ($e->getCode() == 0) { new TMessage('error', '<b>Error</b> <br>' . $e->getMessage()); } else { new TMessage('error', '<b>Error Desconhecido</b> <br>Código: ' . $e->getCode()); } } // desfazer todas as operacoes pendentes TTransaction::rollback(); } }
public function onSelect($param) { try { if (!$param['key']) { return; } if (!TSession::getValue('SRP_id') && !$this->continue) { $this->closeWindow(); new TMessage('error', 'Número SRP Inválido'); $this->message = false; return; } $key = $param['key']; TTransaction::open('saciq'); //TTransaction::setLogger(new TLoggerTXT('c:\array\file.txt')); $repository = new TRepository('Item'); $criteria = new TCriteria(); $criteria->add(new TFilter('numeroItem', '=', $key)); if (TSession::getValue('SRP_id')) { $criteria->add(new TFilter('srp_id', '=', TSession::getValue('SRP_id'))); } $itens = $repository->load($criteria); if (count($itens) > 0) { $item = $itens[0]; $itens_o = TSession::getValue('cessao_itens_o'); if (isset($itens_o) && isset($itens_o[$item->numeroItem])) { $item->estoqueDisponivel += $itens_o[$item->numeroItem]->quantidade; } if ($item->estoqueDisponivel == 0) { $obj = new stdClass(); $obj->numeroItem = ''; $obj->item_id = ''; $obj->numeroItem = ''; $obj->descricaoSumaria = ''; $obj->valorUnitario = ''; //$obj->quantidade = ''; $obj->prazoEntrega = '60 Dias'; $obj->justificativa = ''; TForm::sendData('form_itens', $obj); $this->closeWindow(); new TMessage('error', 'Item sem quantidade disponível'); $this->message = false; return; } $obj = new stdClass(); $obj->item_id = $item->id; if (strpos($item->descricaoSumaria, '–')) { $item->descricaoSumaria = str_replace('–', '-', $item->descricaoSumaria); $item->store(); } $obj->numeroItem = $item->numeroItem; $obj->descricaoSumaria = $item->descricaoSumaria; $obj->valorUnitario = $item->valorUnitario; TForm::sendData('form_itens', $obj); parent::closeWindow(); } else { $obj = new stdClass(); $obj->item_id = ''; $obj->numeroItem = ''; $obj->descricaoSumaria = ''; $obj->valorUnitario = ''; //$obj->quantidade = ''; $obj->prazoEntrega = '60 Dias'; $obj->justificativa = ''; TForm::sendData('form_itens', $obj); parent::closeWindow(); } TTransaction::close(); } catch (Exception $e) { $obj = new stdClass(); $obj->item_id = ''; $obj->descricaoSumaria = ''; $obj->valorUnitario = ''; $obj->quantidade = ''; $obj->prazoEntrega = '60 Dias'; $obj->justificativa = ''; TForm::sendData('form_itens', $obj); TTransaction::rollback(); } }
/** * method onReload() * Load the datagrid with the database objects */ public function onReload($param = NULL) { try { // open a transaction with database TTransaction::open($this->database); // instancia um repositório $repository = new TRepository($this->activeRecord); $limit = isset($this->limit) ? $this->limit > 0 ? $this->limit : NULL : 10; // creates a criteria $criteria = new TCriteria(); if ($this->order) { $criteria->setProperty('order', $this->order); $criteria->setProperty('direction', $this->direction); } $criteria->setProperties($param); // order, offset $criteria->setProperty('limit', $limit); $criteria->add(new TFilter("system_user_id", "=", TSession::getValue("userid"))); if (TSession::getValue($this->activeRecord . '_filter')) { // add the filter stored in the session to the criteria $criteria->add(TSession::getValue($this->activeRecord . '_filter')); } // load the objects according to criteria $objects = $repository->load($criteria, FALSE); $this->datagrid->clear(); if ($objects) { // iterate the collection of active records foreach ($objects as $object) { // add the object inside the datagrid $this->datagrid->addItem($object); } } // reset the criteria for record count $criteria->resetProperties(); $count = $repository->count($criteria); if (isset($this->pageNavigation)) { $this->pageNavigation->setCount($count); // count of records $this->pageNavigation->setProperties($param); // order, page $this->pageNavigation->setLimit($limit); // limit } // close the transaction TTransaction::close(); $this->loaded = true; } catch (Exception $e) { // in case of exception // shows the exception error message new TMessage('error', '<b>Error</b> ' . $e->getMessage()); // undo all pending operations TTransaction::rollback(); } }