HL
Dashboard duplicando o valores na inserção de dados
Estou com seguinte erro RANKING TOP 5 CLIENTES. Quando faço uma inserção de outros dados ou seja de contratos, exibe o mesmo valor do dado anterior para o próximo dado
-- view
create view view_contratos as
select c.id as contrato_id,
c.cliente_id,
c.tipo_contrato_id,
c.dt_inicio,
c.dt_fim,
tc.no_nome as tipo_contrato ,
p.nome as nome_cliente,
m.no_nome as cidade,
e.sg_uf as uf,
e.no_nome as nome_estado,
g.no_nome as nome_grupo,
st_ativo as ativo,
(select sum(nu_total) as total from rl_contrato_servico cs join tb_contrato c
on c.id =cs.contrato_id ) as "total"
from tb_contrato c join tb_tipo_contrato tc
on tc.id = c.tipo_contrato_id
join tb_pessoa p
on p.id = c.cliente_id
join tb_municipio m
on m.id = p.municipio_id
join tb_estado e
on e.id = m.estado_id
join tb_grupo g
on g.id = p.grupo_id;
-- view
create view view_contratos as
select c.id as contrato_id,
c.cliente_id,
c.tipo_contrato_id,
c.dt_inicio,
c.dt_fim,
tc.no_nome as tipo_contrato ,
p.nome as nome_cliente,
m.no_nome as cidade,
e.sg_uf as uf,
e.no_nome as nome_estado,
g.no_nome as nome_grupo,
st_ativo as ativo,
(select sum(nu_total) as total from rl_contrato_servico cs join tb_contrato c
on c.id =cs.contrato_id ) as "total"
from tb_contrato c join tb_tipo_contrato tc
on tc.id = c.tipo_contrato_id
join tb_pessoa p
on p.id = c.cliente_id
join tb_municipio m
on m.id = p.municipio_id
join tb_estado e
on e.id = m.estado_id
join tb_grupo g
on g.id = p.grupo_id;
- <?php
- /**
- * ContratoDashboard
- *
- * @version 1.0
- * @subpackage control
- * @copyright Copyright (c) 2006 Adianti Solutions Ltd. (http://www.adianti.com.br)
- * @license http://www.adianti.com.br/framework-license
- */
- class ContratoDashboard extends TPage
- {
- /**
- * Class constructor
- * Creates the page
- */
- function __construct()
- {
- parent::__construct();
- $vbox = new TVBox;
- $vbox->style = 'width: 100%';
- $div = new TElement('div');
- $div->class = "row";
- try
- {
- TTransaction::open('sys_db');
- $total_ativos = Contrato::where('st_ativo','=','Y')->count();
- $total_renovar = Contrato::where('st_ativo','=','Y')->where('dt_fim', '<=', date('Y-m-d'))->count();
- $contratos_grupo = ViewContratos::where('ativo','=','Y')->groupBy('nome_grupo')->sumBy('total');
- $contratos_tipo = ViewContratos::where('ativo','=','Y')->groupBy('tipo_contrato')->sumBy('total');
- $top_clientes = ViewContratos::where('ativo','=','Y')->groupBy('nome_cliente')->take(5)->orderBy('total', 'desc')->sumBy('total');
- $old_clientes = ViewContratos::where('ativo','=','Y')->take(5)->orderBy('dt_inicio')->load();
- var_dump($top_clientes);
- TTransaction::close();
- $indicator1 = new THtmlRenderer('app/resources/info-box.html');
- $indicator1->enableSection('main', ['title' => 'Contratos ativos', 'icon' => 'check-double', 'background' => 'green', 'value' => $total_ativos ] );
- $indicator2 = new THtmlRenderer('app/resources/info-box.html');
- $indicator2->enableSection('main', ['title' => 'Renovações pendentes', 'icon' => 'hourglass-start', 'background' => 'orange', 'value' => $total_renovar ] );
- $data = [];
- $data[] = [ 'Estado', 'Contratos' ];
- if ($contratos_grupo)
- {
- foreach($contratos_grupo as $contrato_grupo)
- {
- $data[] = [ $contrato_grupo->nome_grupo, (float) $contrato_grupo->total ];
- }
- }
- $grafico1 = new THtmlRenderer('app/resources/google_pie_chart.html');
- $grafico1->enableSection('main', ['data' => json_encode($data), 'width' => '100%', 'height' => '400px',
- 'title' => 'Contratos por grupo', 'ytitle' => 'Estado', 'xtitle' => 'Contratos', 'uniqid' => uniqid()]);
- $data = [];
- $data[] = [ 'Estado', 'Contratos' ];
- if ($contratos_tipo)
- {
- foreach($contratos_tipo as $contrato_tipo)
- {
- $data[] = [ $contrato_tipo->tipo_contrato, (float) $contrato_tipo->total ];
- }
- }
- $grafico2 = new THtmlRenderer('app/resources/google_pie_chart.html');
- $grafico2->enableSection('main', ['data' => json_encode($data), 'width' => '100%', 'height' => '400px',
- 'title' => 'Contratos por tipo', 'ytitle' => 'Tipo', 'xtitle' => 'Contratos', 'uniqid' => uniqid()]);
- $table1 = TTable::create( [ 'class' => 'table table-striped table-hover', 'style' => 'border-collapse:collapse' ] );
- $table1->addSection('thead');
- $table1->addRowSet('Cliente', 'Quantidade');
- if ($top_clientes)
- {
- $table1->addSection('tbody');
- foreach ($top_clientes as $top_cliente)
- {
- $row = $table1->addRow();
- $row->addCell($top_cliente->nome_cliente);
- $row->addCell('R$ ' . number_format($top_cliente->total,2,',','.'))->style = 'text-align:right';
- }
- }
- $table2 = TTable::create( [ 'class' => 'table table-striped table-hover', 'style' => 'border-collapse:collapse' ] );
- $table2->addSection('thead');
- $table2->addRowSet('Cliente', 'Data');
- if ($old_clientes)
- {
- $table2->addSection('tbody');
- foreach ($old_clientes as $old_cliente)
- {
- $row = $table2->addRow();
- $row->addCell($old_cliente->nome_cliente);
- $row->addCell(TDate::convertToMask($old_cliente->dt_inicio, 'yyyy-mm-dd', 'dd/mm/yyyy'));
- }
- }
- $div->add( TElement::tag('div', $indicator1, ['class' => 'col-sm-6']) );
- $div->add( TElement::tag('div', $indicator2, ['class' => 'col-sm-6']) );
- $div->add( TElement::tag('div', $grafico1, ['class' => 'col-sm-6']) );
- $div->add( TElement::tag('div', $grafico2, ['class' => 'col-sm-6']) );
- $div->add( TElement::tag('div', TPanelGroup::pack('Ranking TOP 5 Clientes', $table1), ['class' => 'col-sm-6']) );
- $div->add( TElement::tag('div', TPanelGroup::pack('Raking 5 Clientes mais antigos', $table2), ['class' => 'col-sm-6']) );
- //$vbox->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- $vbox->add($div);
- }
- catch (Exception $e)
- {
- new TMessage('error', $e->getMessage());
- }
- parent::add($vbox);
- }
- }
- <?php
- /**
- * ContratoForm
- *
- * @version 1.0
- * @subpackage control
- * @copyright Copyright (c) 2006 Adianti Solutions Ltd. (http://www.adianti.com.br)
- * @license http://www.adianti.com.br/framework-license
- */
- class ContratoForm extends TWindow
- {
- protected $form; // form
- protected $fieldlist;
- /**
- * Class constructor
- * Creates the page and the registration form
- */
- function __construct($param)
- {
- parent::__construct($param);
- parent::setSize(0.8, null);
- parent::removePadding();
- parent::removeTitleBar();
- //parent::disableEscape();
- // creates the form
- $this->form = new BootstrapFormBuilder('form_Contrato');
- $this->form->setFormTitle('Contrato');
- $this->form->setClientValidation(true);
- // master fields
- $id = new TEntry('id');
- $cliente_id = new TDBUniqueSearch('cliente_id', 'sys_db', 'Pessoa', 'id', 'nome_fantasia');
- $tipo_contrato_id = new TDBUniqueSearch('tipo_contrato_id', 'sys_db', 'TipoContrato', 'id', 'no_nome');
- $ativo = new TRadioGroup('st_ativo');
- $dt_inicio = new TDate('dt_inicio');
- $dt_fim = new TDate('dt_fim');
- $obs = new TText('ds_obs');
- $cliente_id->setMinLength(0);
- $tipo_contrato_id->setMinLength(0);
- $ativo->addItems( ['Y' => 'Sim', 'N' => 'Não'] );
- $ativo->setLayout('horizontal');
- $dt_inicio->setMask('dd/mm/yyyy');
- $dt_fim->setMask('dd/mm/yyyy');
- $dt_inicio->setDatabaseMask('yyyy-mm-dd');
- $dt_fim->setDatabaseMask('yyyy-mm-dd');
- $dt_inicio->setSize('100%');
- $dt_fim->setSize('100%');
- $obs->setSize('100%', 60);
- $ativo->setValue('Y');
- $cliente_id->addValidation('Cliente', new TRequiredValidator);
- $tipo_contrato_id->addValidation('Tipo contrato', new TRequiredValidator);
- $ativo->addValidation('Ativo', new TRequiredValidator);
- $dt_inicio->addValidation('Data início', new TRequiredValidator);
- $dt_fim->addValidation('Data fim', new TRequiredValidator);
- // sizes
- $id->setSize('100%');
- $cliente_id->setSize('100%');
- $tipo_contrato_id->setSize('100%');
- $ativo->setSize('100%');
- $dt_inicio->setSize('100%');
- $dt_fim->setSize('100%');
- $id->setEditable(FALSE);
- // add form fields to the form
- $this->form->addFields( [new TLabel('Id')], [$id] );
- $this->form->addFields( [new TLabel('Cliente')], [$cliente_id] );
- $this->form->addFields( [new TLabel('Tipo Contrato')], [$tipo_contrato_id] );
- $this->form->addFields( [new TLabel('Ativo')], [$ativo] );
- $this->form->addFields( [new TLabel('Dt Inicio')], [$dt_inicio], [new TLabel('Dt Fim')], [$dt_fim] );
- $this->form->addFields( [new TLabel('Obs')], [$obs] );
- // detail fields
- $this->fieldlist = new TFieldList;
- $this->fieldlist-> width = '100%';
- $this->fieldlist->enableSorting();
- $servico_id = new TDBUniqueSearch('list_servico_id[]', 'sys_db', 'Servico', 'id', 'no_nome', null, TCriteria::create( ['st_ativo' => 'Y'] ));
- $valor = new TNumeric('list_valor[]', 2, ',', '.');
- $quantidade = new TNumeric('list_quantidade[]', 2, ',', '.');
- $servico_id->setChangeAction(new TAction(array($this, 'onChangeServico')));
- $servico_id->setSize('100%');
- $servico_id->setMinLength(0);
- $valor->setSize('100%');
- $quantidade->setSize('100%');
- $this->fieldlist->addField( '<b>Serviço</b>', $servico_id, ['width' => '40%']);
- $this->fieldlist->addField( '<b>Valor</b>', $valor, ['width' => '30%']);
- $this->fieldlist->addField( '<b>Quantidade</b>', $quantidade, ['width' => '30%']);
- $this->form->addField($servico_id);
- $this->form->addField($valor);
- $this->form->addField($quantidade);
- $detail_wrapper = new TElement('div');
- $detail_wrapper->add($this->fieldlist);
- $detail_wrapper->style = 'overflow-x:auto';
- $this->form->addContent( [ TElement::tag('h5', 'Itens do contrato', [ 'style'=>'background: whitesmoke; padding: 5px; border-radius: 5px; margin-top: 5px'] ) ] );
- $this->form->addContent( [ $detail_wrapper ] );
- // create actions
- //$this->form->addAction( _t('Save'), new TAction( [$this, 'onSave'] ), 'fa:save green' );
- $btn = $this->form->addAction( _t('Save'), new TAction( [$this, 'onSave'] ), 'fa:save default' );
- $btn->class = 'btn btn-sm btn-success';
- $this->form->addAction( _t('Clear'), new TAction( [$this, 'onClear'] ), 'fa:eraser red' );
- $this->form->addHeaderActionLink( _t('Close'), new TAction([$this, 'onClose']), 'fa:times red');
- // create the page container
- $container = new TVBox;
- $container->style = 'width: 100%';
- //$container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- $container->add($this->form);
- parent::add($container);
- }
- /**
- * Executed whenever the user clicks at the edit button da datagrid
- */
- function onEdit($param)
- {
- try
- {
- TTransaction::open('sys_db');
- if (isset($param['key']))
- {
- $key = $param['key'];
- $object = new Contrato($key);
- $this->form->setData($object);
- $items = ContratoItem::where('contrato_id', '=', $key)->load();
- if ($items)
- {
- $this->fieldlist->addHeader();
- foreach($items as $item )
- {
- $detail = new stdClass;
- $detail->list_servico_id = $item->servico_id;
- $detail->list_valor = $item->nu_valor;
- $detail->list_quantidade = $item->qt_qtde;
- $this->fieldlist->addDetail($detail);
- }
- $this->fieldlist->addCloneAction();
- }
- else
- {
- $this->onClear($param);
- }
- TTransaction::close(); // close transaction
- }
- else
- {
- $this->onClear($param);
- }
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage());
- TTransaction::rollback();
- }
- }
- /**
- * Clear form
- */
- public function onClear($param)
- {
- $this->fieldlist->addHeader();
- $this->fieldlist->addDetail( new stdClass );
- $this->fieldlist->addCloneAction();
- }
- /**
- * Save the Contrato and the ContratoItem's
- */
- public static function onSave($param)
- {
- try
- {
- TTransaction::open('sys_db');
- $id = (int) $param['id'];
- $master = new Contrato;
- $master->fromArray( $param);
- $master->dt_inicio = TDateTime::convertToMask($param['dt_inicio'], 'dd/mm/yyyy', 'yyyy-mm-dd');
- $master->dt_fim = TDateTime::convertToMask($param['dt_fim'], 'dd/mm/yyyy', 'yyyy-mm-dd');
- $master->store(); // save master object
- // delete details
- ContratoItem::where('contrato_id', '=', $master->id)->delete();
- if( !empty($param['list_servico_id']) AND is_array($param['list_servico_id']) )
- {
- foreach( $param['list_servico_id'] as $row => $servico_id)
- {
- if (!empty($servico_id))
- {
- $detail = new ContratoItem;
- $detail->contrato_id = $master->id;
- $detail->servico_id = $param['list_servico_id'][$row];
- $detail->valor = (float) str_replace(['.',','], ['','.'], $param['list_valor'][$row]);
- $detail->quantidade = (float) str_replace(['.',','], ['','.'], $param['list_quantidade'][$row]);
- $detail->total = round($detail->valor * $detail->quantidade,2);
- $detail->store();
- }
- }
- }
- $data = new stdClass;
- $data->id = $master->id;
- TForm::sendData('form_Contrato', $data);
- TTransaction::close(); // close the transaction
- new TMessage('info', AdiantiCoreTranslator::translate('Record saved'));
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage());
- TTransaction::rollback();
- }
- }
- /**
- * Change servico
- */
- public static function onChangeServico($param)
- {
- $input_id = $param['_field_id'];
- $servico_id = $param['_field_value'];
- $input_pieces = explode('_', $input_id);
- $unique_id = end($input_pieces);
- if ($servico_id)
- {
- $response = new stdClass;
- try
- {
- TTransaction::open('sys_db');
- $servico = Servico::find($servico_id);
- $response->{'list_quantidade_'.$unique_id} = '1,00';
- $response->{'list_valor_'.$unique_id} = number_format($servico->nu_valor,2,',', '.');
- TForm::sendData('form_Contrato', $response);
- TTransaction::close();
- }
- catch (Exception $e)
- {
- TTransaction::rollback();
- }
- }
- }
- /**
- * Close
- */
- public static function onClose($param)
- {
- parent::closeWindow();
- }
- }