<?xml version="1.0" encoding="UTF-8"?>
<panel-form xmlns="http://www.davinti.com.br/vitruvio/form/panel" 
			xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
			xsi:schemaLocation="http://www.davinti.com.br/vitruvio/form/panel https://bitbucket.org/davinTI/vitruvio-xds/raw/master/vitruvio-panel-form.xsd"
			>
	<form formKey="formCadastro" width="100%" height="100%">
    	<name>Lançar Valor</name>
      	<description>Regras Contábeis</description>
      	<initScript language="JavaScript">
      		<![CDATA[
      		importClass(Packages.br.com.davinti.base.vaadin.components.icons.IconFactory);
			importClass(Packages.br.com.davinti.base.vaadin.components.resources.icons16x16.IconLibraryAPISmall);
			
			function fncLimpaCampos(){
				engine.getField('dataLancamento')["setValue(java.lang.Object)"](null);
				engine.getField('cliente')["setValue(java.lang.Object)"](null);
				engine.getField('categoria')["setValue(java.lang.Object)"](null);
				engine.getField('subCategoria')["setValue(java.lang.Object)"](null);
				engine.getField('nrDocumento')['setValue(java.lang.String)'](null);
				engine.getField('formaPagamento')["setValue(java.lang.Object)"](null);
				engine.getField('placa')["setValue(java.lang.Object)"](null);
				engine.getField('funcionario')["setValue(java.lang.Object)"](null);
				engine.getField('fornecedor')["setValue(java.lang.Object)"](null);
				engine.getField('valor')['setValue(java.lang.String)'](null);
				engine.getField('observacao')['setValue(java.lang.String)'](null);
				
				engine.getField('dataPessoal')["setValue(java.lang.Object)"](null);
				engine.getField('categoriaPessoal')["setValue(java.lang.Object)"](null);
				engine.getField('responsavelPessoal')["setValue(java.lang.Object)"](null);
				engine.getField('valorPessoal')['setValue(java.lang.String)'](null);
				engine.getField('observacaoPessoal')['setValue(java.lang.String)'](null);
				
				engine.getField('dataCombustivel')["setValue(java.lang.Object)"](null);
				engine.getField('placaCombustivel')["setValue(java.lang.Object)"](null);
				engine.getField('clienteCombustivel')["setValue(java.lang.Object)"](null);
				engine.getField('observacaoCombustivel')['setValue(java.lang.String)'](null);
				engine.getField('combustivel')["setValue(java.lang.Object)"](null);
				engine.getField('litrosCombustivel')['setValue(java.lang.String)'](null);
				engine.getField('valorCombustivel')['setValue(java.lang.String)'](null);
				engine.getField('totalCombustivel')['setValue(java.lang.String)'](null);
				engine.getField('kmInicial')['setValue(java.lang.String)'](null);
				engine.getField('kmFinal')['setValue(java.lang.String)'](null);
				engine.getField('kmRodado')['setValue(java.lang.String)'](null);
			}
			
			function fncSubTotal() {
				var params = {id: 0};
				var db = vScriptService.loadScript('db', 'javascript');
			    var vitruvio = new db('vitruvio');
			    var sql = "Select replace(replace(replace(to_char(sum(cdo.valor), 'L9G999G990D99'),',','-' ),'.',','),'-','.') total from controle_despesas_operacionais cdo where cdo.data between '" + engine.getField('dataInicio') + "' and '" + engine.getField('dataFinal') + "'";
			    vitruvio.query(sql).each(function (r) {
		            if (r.total) {
		            	engine.getLabel('sub').setValue('<b><font color="red">Subtotal R' + r.total + '</font></b>');
		            } else {
		            	engine.getLabel('sub').setValue('<b><font color="red">Subtotal R$ 0,00</font></b>');
		            }
		         }); 
			}
			
			function fncSubTotalPessoal() {
				var params = {id: 0};
				var db = vScriptService.loadScript('db', 'javascript');
			    var vitruvio = new db('vitruvio');
			    var sql = "Select replace(replace(replace(to_char(sum(cdp.valor), 'L9G999G990D99'),',','-' ),'.',','),'-','.') total from controle_despesas_pessoais cdp where cdp.data between '" + engine.getField('dataInicioPessoal') + "' and '" + engine.getField('dataFinalPessoal') + "'";
			    if (engine.getField('ftResponsavelPessoal').getValue()) {
					sql += " and cdp.chave_responsavel = " + engine.getField('ftResponsavelPessoal').getValue();
				}
			    vitruvio.query(sql).each(function (r) {
		            if (r.total) {
		            	engine.getLabel('subPessoal').setValue('<b><font color="red">Subtotal R' + r.total + '</font></b>');
		            } else {
		            	engine.getLabel('subPessoal').setValue('<b><font color="red">Subtotal R$ 0,00</font></b>');
		            }
		         }); 
			}
			
			function fncSubTotalCombustivel() {
				var params = {id: 0};
				var db = vScriptService.loadScript('db', 'javascript');
			    var vitruvio = new db('vitruvio');
			    var sql = "Select replace(replace(replace(to_char(sum(cdc.total_combustivel), 'L9G999G990D99'),',','-' ),'.',','),'-','.') total from controle_despesas_combustiveis cdc where cdc.data between '" + engine.getField('dataInicioCombustivel') + "' and '" + engine.getField('dataFinalCombustivel') + "'";
			    if (engine.getField('ftPlacaCombustivel').getValue()) {
					sql += " and cdc.chave_veiculo = " + engine.getField('ftPlacaCombustivel').getValue();
				}
				if (engine.getField('ftCombustivel').getValue()) {
					sql += " and cdc.chave_combustivel = " + engine.getField('ftCombustivel').getValue();
				}
				if (engine.getField('ftClienteCombustivel').getValue()) {
					sql += " and cdc.chave_cliente = " + engine.getField('ftClienteCombustivel').getValue();
				}
			    vitruvio.query(sql).each(function (r) {
		            if (r.total) {
		            	engine.getLabel('subCombustivel').setValue('<b><font color="red">Subtotal R' + r.total + '</font></b>');
		            } else {
		            	engine.getLabel('subCombustivel').setValue('<b><font color="red">Subtotal R$ 0,00</font></b>');
		            }
		         }); 
			}
			
			function run() {
				engine.getField('totalCombustivel').setEnabled(false);
				engine.getField('kmRodado').setEnabled(false);
				engine.getField('mediaCombustivel').setEnabled(false);
			
				
				var d = new java.util.Date();
				engine.setGlobalVariable('fncLimpaCampos', fncLimpaCampos);
				engine.setGlobalVariable('fncSubTotal', fncSubTotal);
				engine.setGlobalVariable('fncSubTotalPessoal', fncSubTotalPessoal);
				engine.setGlobalVariable('fncSubTotalCombustivel', fncSubTotalCombustivel);
				engine.getField('dataInicio').setValue(d);
				engine.getField('dataFinal').setValue(d);
				engine.getField('dataInicioPessoal').setValue(d);
				engine.getField('dataFinalPessoal').setValue(d);
				engine.getField('dataInicioCombustivel').setValue(d);
				engine.getField('dataFinalCombustivel').setValue(d);
				engine.getField('tbLancamentos').refresh();
				engine.getField('tbPessoal').refresh();
				engine.getField('tbTotalSocios').refresh();
				engine.getField('tbCombustivel').refresh();
				engine.getField('tbTotalCombustivel').refresh();
				engine.getGlobalVariable('fncSubTotal')();
				engine.getGlobalVariable('fncSubTotalPessoal')();
				engine.getGlobalVariable('fncSubTotalCombustivel')();
				
				// Registrando icones
				engine.getWidgetController('btnGravar').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.SALVAR));
				engine.getWidgetController('btnFiltrar').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.FILTRAR));
				engine.getWidgetController('btnLimparFiltro').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.LIMPAR));
				engine.getWidgetController('btnGravarPessoal').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.SALVAR));
				engine.getWidgetController('btnFiltrarPessoal').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.FILTRAR));
				engine.getWidgetController('btnLimparFiltroPessoal').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.LIMPAR));
				engine.getWidgetController('btnGravarCombustivel').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.SALVAR));
				engine.getWidgetController('btnFiltrarCombustivel').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.FILTRAR));
				engine.getWidgetController('btnLimparFiltroCombustivel').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.LIMPAR));
			}
		]]>
	  	</initScript>

      	<components>
      		<VerticalLayout margin="true" width="100%" >
	      		<TabLayout align="BOTTOM_LEFT" id="credito" compact="true" width="100%" height="100%" >
	      			<TabChangeScript language="JavaScript">
	      				<![CDATA[
	      					function run() {
	      						var index = engine.getLayout('credito').getSelectedTab();
	      						if (index == 0) {
	      							engine.getField('dataLancamento').setRequired(true);
	      							engine.getField('dataPessoal').setRequired(false);
	      							engine.getField('dataCombustivel').setRequired(false);
	      							engine.getField('placa').setRequired(false); 
	      							engine.getField('cliente').setRequired(true);
	      							engine.getField('categoria').setRequired(true);
	      							engine.getField('valor').setRequired(true);
	      							
	      							engine.getField('categoriaPessoal').setRequired(false);
	      							engine.getField('responsavelPessoal').setRequired(false);
	      							engine.getField('valorPessoal').setRequired(false);
	      							
	      							engine.getField('placaCombustivel').setRequired(false);
	      							engine.getField('clienteCombustivel').setRequired(false);
	      							engine.getField('combustivel').setRequired(false);
								} else if (index == 1) {
									engine.getField('dataLancamento').setRequired(false);
	      							engine.getField('dataPessoal').setRequired(true);
	      							engine.getField('dataCombustivel').setRequired(false);
	      							engine.getField('placa').setRequired(false); 
	      							engine.getField('cliente').setRequired(false);
	      							engine.getField('categoria').setRequired(false);
	      							engine.getField('valor').setRequired(false);
	      							engine.getField('categoriaPessoal').setRequired(true);
	      							engine.getField('responsavelPessoal').setRequired(true);
	      							engine.getField('valorPessoal').setRequired(true);
	      							engine.getField('placaCombustivel').setRequired(false);
	      							engine.getField('clienteCombustivel').setRequired(false);
	      							engine.getField('combustivel').setRequired(false);
								} else if (index == 2) {
									engine.getField('dataLancamento').setRequired(false);
	      							engine.getField('dataPessoal').setRequired(false);
	      							engine.getField('dataCombustivel').setRequired(true);
	      							engine.getField('placa').setRequired(false); 
	      							engine.getField('cliente').setRequired(false);
	      							engine.getField('categoria').setRequired(false);
	      							engine.getField('valor').setRequired(false);
	      							engine.getField('categoriaPessoal').setRequired(false);
	      							engine.getField('responsavelPessoal').setRequired(false);
	      							engine.getField('valorPessoal').setRequired(false);
	      							engine.getField('placaCombustivel').setRequired(true);
	      							engine.getField('clienteCombustivel').setRequired(true);
	      							engine.getField('combustivel').setRequired(true);
								}
	      					}
	      				]]>
	      			</TabChangeScript>
	      			<Tab caption="Operacionais">
						<VerticalLayout spacing="true" width="100%" height="100%">
						   <Panel caption=" " width="100%" expandRatio="0.1" align="TOP_LEFT" height="100%">
								<VerticalLayout width="100%" margin="true" spacing="true">
									<HorizontalLayout width="100%" spacing="true" height="100%">
								      <ImageWidget id="img1" height="46" width="68" align="TOP_LEFT">
								      		<image>
								      			<base64 extension="jpg">
								      				<![CDATA[
								      					,[encoded data, 25976 characters]
								      				]]>
								      			</base64>
								      		</image>
								      	</ImageWidget>
								      	<DateField type="date" id="dataLancamento" align="TOP_LEFT" caption="Data" width="100%" expandRatio="0.15" required="true" resolution="DAY" description="Informe a data do lançamento" format="dd/MM/yyyy" />
								      	<DBComboBox type="string" id="placa" width="100%" required="false" expandRatio="0.2" align="TOP_LEFT" caption="Placa">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from veiculo
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>PLACA</caption-field>
								      	</DBComboBox>
								      	<DBComboBox type="string" id="cliente" required="true" width="100%" expandRatio="0.2" align="TOP_LEFT" caption="Cliente">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from clientes
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>NOME</caption-field>
								      	</DBComboBox>
								      	<DBComboBox type="string" id="categoria" required="true" width="100%" expandRatio="0.2" align="TOP_LEFT" caption="Categoria">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from categoria
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>DESCRICAO</caption-field>
								      	</DBComboBox>
								      	<DBComboBox type="string" id="subCategoria" width="100%" expandRatio="0.2" align="TOP_LEFT" caption="Sub-Categoria">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from subcategoria where codigo_categoria = ${categoria}
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>DESCRICAO</caption-field>
								      		<bind>
								      			<parameter value-type="number" defaultValue="-1" parameterName="categoria" field-ref="categoria" />
								      		</bind>
								      	</DBComboBox>
								    </HorizontalLayout>
								    <HorizontalLayout spacing="true" width="100%" height="100%" >
								      	<DBComboBox type="string" id="funcionario" width="100%" expandRatio="0.25" align="TOP_LEFT" caption="Funcionário">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from funcionario
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>NOME</caption-field>
								      	</DBComboBox>
								      	<TextField type="number" id="nrDocumento" caption="Número do documento" width="100%" expandRatio="0.25" align="TOP_LEFT" />
								      	<DBComboBox type="string" id="formaPagamento" width="100%" expandRatio="0.25" align="TOP_LEFT" caption="Forma pagamento" >
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from forma_pagamento
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>NOME</caption-field>
								      	</DBComboBox>
								      	<DBComboBox type="string" id="fornecedor" width="100%" expandRatio="1" align="TOP_LEFT" caption="Fornecedor">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from fornecedor
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>RAZAO_SOCIAL</caption-field>
								      	</DBComboBox>
								      	<DecimalField type="decimal" id="valor" caption="Valor (R$)" format="#,##0.00" required="true" description="Valor da despesa" width="100%" expandRatio="0.2" />
									</HorizontalLayout>
									<HorizontalLayout width="100%" spacing="true">
										<TextField type="string" id="observacao" text-transform="uppercase" align="TOP_LEFT" width="100%" expandRatio="1" caption="Observações" >
											<events>
								      			<valueChange>
								      				<script language="JavaScript">
								      					<![CDATA[
								      						function run() {
										      					importClass(Packages.com.vaadin.ui.Notification);
																function run() {
																	if (engine.isValid()) {
																		var db = libService.loadScript('db');
																		var dbVitruvio = new db('vitruvio');
																		var sql;
																		dbVitruvio.transaction(function() {
																			sql = 	"insert into controle_despesas_operacionais (chave_despesa_operacional,data,chave_cliente,chave_categoria,chave_subcategoria,numero_documento,chave_forma_pagamento,chave_veiculo,chave_funcionario,chave_fornecedor,observacoes,valor) " +
																					" values (" + dbVitruvio.getSequenceNextValSql('controle_desp_op_seq') + ",:data,:chave_cliente,:chave_categoria,:chave_subcategoria,:numero_documento,:chave_forma_pagamento,:chave_veiculo,:chave_funcionario,:chave_fornecedor,:observacoes,:valor)";
																		   	this.update(sql, {
																				data: engine.getField('dataLancamento').getValue(),
																				chave_cliente: Number(engine.getField('cliente').getValue()),
																				chave_categoria: Number(engine.getField('categoria').getValue()),
																				chave_subcategoria: Number(engine.getField('subCategoria').getValue()),
																				numero_documento: Number(engine.getField('nrDocumento').getValue()),
																				chave_forma_pagamento: Number(engine.getField('formaPagamento').getValue()),
																				chave_veiculo: Number(engine.getField('placa').getValue()),
																				chave_funcionario: Number(engine.getField('funcionario').getValue()),
																				chave_fornecedor: Number(engine.getField('fornecedor').getValue()),
																				observacoes: engine.getField('observacao').getValue(),
																				valor: engine.getField('valor').getConvertedValue()
																		   });
																        });
																        engine.getField('tbLancamentos').refresh();
																        engine.getGlobalVariable('fncLimpaCampos')();
																        engine.getGlobalVariable('fncSubTotal')();
																		Notification.show(null, 'Dados salvos', Notification.Type.TRAY_NOTIFICATION);
																	}
																}
										      				}
								      					]]>
								      				</script>
								      			</valueChange>
								      		</events>
										</TextField>
										<ButtonWidget id="btnGravar" caption="Gravar" align="BOTTOM_RIGHT" description="Grava o lançamento" width="100" >
											<onClickScript language="JavaScript">
												<![CDATA[
													importClass(Packages.com.vaadin.ui.Notification);
													function run() {
														if (engine.isValid()) {
															var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															var sql;
															dbVitruvio.transaction(function() {
																sql = 	"insert into controle_despesas_operacionais (chave_despesa_operacional,data,chave_cliente,chave_categoria,chave_subcategoria,numero_documento,chave_forma_pagamento,chave_veiculo,chave_funcionario,chave_fornecedor,observacoes,valor) " +
																		" values (" + dbVitruvio.getSequenceNextValSql('controle_desp_op_seq') + ",:data,:chave_cliente,:chave_categoria,:chave_subcategoria,:numero_documento,:chave_forma_pagamento,:chave_veiculo,:chave_funcionario,:chave_fornecedor,:observacoes,:valor)";
															   	this.update(sql, {
																	data: engine.getField('dataLancamento').getValue(),
																	chave_cliente: Number(engine.getField('cliente').getValue()),
																	chave_categoria: Number(engine.getField('categoria').getValue()),
																	chave_subcategoria: Number(engine.getField('subCategoria').getValue()),
																	numero_documento: Number(engine.getField('nrDocumento').getValue()),
																	chave_forma_pagamento: Number(engine.getField('formaPagamento').getValue()),
																	chave_veiculo: Number(engine.getField('placa').getValue()),
																	chave_funcionario: Number(engine.getField('funcionario').getValue()),
																	chave_fornecedor: Number(engine.getField('fornecedor').getValue()),
																	observacoes: engine.getField('observacao').getValue(),
																	valor: engine.getField('valor').getConvertedValue()
															   });
													        });
													        engine.getField('tbLancamentos').refresh();
													        engine.getGlobalVariable('fncLimpaCampos')();
													        engine.getGlobalVariable('fncSubTotal')();
															Notification.show(null, 'Dados salvos', Notification.Type.TRAY_NOTIFICATION);
														}
													}
												]]>
											</onClickScript>
										</ButtonWidget>
									</HorizontalLayout>
								</VerticalLayout>
							</Panel>
			
							<Panel width="100%" margin="true" >
								<VerticalLayout width="100%" spacing="true" align="TOP_LEFT" >
									<HorizontalLayout width="100%" spacing="true" align="TOP_LEFT">
										<DateField type="date" id="dataInicio" caption="Data inicial" align="TOP_LEFT" width="100%" expandRatio="0.2" description="Data inicial da exibição" format="dd/MM/yyyy" />
										<DateField type="date" id="dataFinal" caption="Data final" align="TOP_LEFT" width="100%" expandRatio="0.2" description="Data final da exibição" format="dd/MM/yyyy" />
										<DBComboBox type="number" id="ftFuncionario" caption="Funcionários" width="100%" expandRatio="0.2" allowNullSelection="true" >
											<datasource>
												<freeQuery connection-key="vitruvio">
													<![CDATA[
														Select codigo, nome from funcionario
													]]>
												</freeQuery>
											</datasource>
											<key-field>CODIGO</key-field>
											<caption-field>NOME</caption-field>
										</DBComboBox>
										<DBComboBox type="number" id="ftPlaca" caption="Placa" width="100%" expandRatio="0.15" allowNullSelection="true" >
											<datasource>
												<freeQuery connection-key="vitruvio">
													<![CDATA[
														Select codigo, placa from veiculo
													]]>
												</freeQuery>
											</datasource>
											<key-field>CODIGO</key-field>
											<caption-field>PLACA</caption-field>
										</DBComboBox>
										<DBComboBox type="number" id="ftCliente" caption="Clientes" width="100%" expandRatio="0.2" allowNullSelection="true" >
											<datasource>
												<freeQuery connection-key="vitruvio">
													<![CDATA[
														Select codigo, nome from clientes
													]]>
												</freeQuery>
											</datasource>
											<key-field>CODIGO</key-field>
											<caption-field>NOME</caption-field>
										</DBComboBox>
										<DBComboBox type="number" id="ftFornecedor" caption="Fornecedores" width="100%" expandRatio="0.2" allowNullSelection="true" >
											<datasource>
												<freeQuery connection-key="vitruvio">
													<![CDATA[
														Select codigo, razao_social from fornecedor
													]]>
												</freeQuery>
											</datasource>
											<key-field>CODIGO</key-field>
											<caption-field>RAZAO_SOCIAL</caption-field>
										</DBComboBox>
										<ButtonWidget id="btnFiltrar" caption="Filtrar" align="BOTTOM_RIGHT" description="Aplica filtro de data" width="100" >
											<onClickScript language="JavaScript">
												<![CDATA[
													function run() {
														engine.getField('tbLancamentos').refresh();
														engine.getGlobalVariable('fncSubTotal')();
													}
												]]>
											</onClickScript>
										</ButtonWidget>
										<ButtonWidget id="btnLimparFiltro" caption="Limpar" align="BOTTOM_LEFT" description="Limpar filtro" width="100" >
											<onClickScript language="JavaScript">
												<![CDATA[
													function run() {
														var d = new java.util.Date();
														engine.getField('dataInicio').setValue(d);
														engine.getField('dataFinal').setValue(d);
														engine.getField('ftFuncionario')["setValue(java.lang.Object)"](null);
														engine.getField('ftPlaca')["setValue(java.lang.Object)"](null);
														engine.getField('ftCliente')["setValue(java.lang.Object)"](null);
														engine.getField('ftFornecedor')["setValue(java.lang.Object)"](null);
														engine.getField('tbLancamentos').refresh();
														engine.getGlobalVariable('fncSubTotal')();
													}
												]]>
											</onClickScript>
										</ButtonWidget>
										<Label id="sub" align="BOTTOM_RIGHT" width="100%" expandRatio="1" contentMode="HTML">
											<value>
												
											</value>
										</Label>
									</HorizontalLayout>
									<DBTable id="tbLancamentos" type="number" width="100%" rows="7" exportXLS="true" editable="true"  >
										<datasource>
											<sqlBuilderDataSource connection-key="vitruvio" language="JavaScript">
												<![CDATA[
													function buildSQL(params) {
														var sql = 	"Select cdo.chave_despesa_operacional," +
																	" cdo.data," +
																	" (select co.nome from clientes co where co.codigo = cdo.chave_cliente) cliente," +
																	" (select cc.descricao from categoria cc where cc.codigo = cdo.chave_categoria) categoria," +
																	" (select cs.descricao from subcategoria cs where cs.codigo = cdo.chave_subcategoria) subcategoria," +
																	" cdo.numero_documento," +
																	" (select cfp.nome from forma_pagamento cfp where cfp.codigo = cdo.chave_forma_pagamento) formapagamento," +
																	" (select cv.placa from veiculo cv where cv.codigo = cdo.chave_veiculo) veiculo," +
																	" (select cf.nome from funcionario cf where cf.codigo = cdo.chave_funcionario) funcionario," +
																	" (select cf.razao_social from fornecedor cf where cf.codigo = cdo.chave_fornecedor) fornecedor," +
																	" cdo.observacoes," +
																	" replace(replace(replace(to_char(cdo.valor, 'L9G999G990D99'),',','-' ),'.',','),'-','.') valor " +
																	" from controle_despesas_operacionais cdo where 1=2";
														if (engine) {
															sql = 	"Select 	cdo.chave_despesa_operacional," +
																	" cdo.data," +
																	" (select co.nome from clientes co where co.codigo = cdo.chave_cliente) cliente," +
																	" (select cc.descricao from categoria cc where cc.codigo = cdo.chave_categoria) categoria," +
																	" (select cs.descricao from subcategoria cs where cs.codigo = cdo.chave_subcategoria) subcategoria," +
																	" cdo.numero_documento," +
																	" (select cfp.nome from forma_pagamento cfp where cfp.codigo = cdo.chave_forma_pagamento) formapagamento," +
																	" (select cv.placa from veiculo cv where cv.codigo = cdo.chave_veiculo) veiculo," +
																	" (select cf.nome from funcionario cf where cf.codigo = cdo.chave_funcionario) funcionario," +
																	" (select cf.razao_social from fornecedor cf where cf.codigo = cdo.chave_fornecedor) fornecedor," +
																	" cdo.observacoes," +
																	" cdo.valor valor " +
																	//" trim(replace(replace(replace(to_char(cdo.valor, '9999999999D99'),',','-' ),'.',','),'-','.')) valor " +
																	" from controle_despesas_operacionais cdo where cdo.data between '" + engine.getField('dataInicio') + "' and '" + engine.getField('dataFinal') + "'";
																	if (engine.getField('ftFuncionario').getValue()) {
																		sql += " and cdo.chave_funcionario = " + engine.getField('ftFuncionario').getValue();
																	}
																	if (engine.getField('ftPlaca').getValue()) {
																		sql += " and cdo.chave_veiculo = " + engine.getField('ftPlaca').getValue();
																	}
																	if (engine.getField('ftCliente').getValue()) {
																		sql += " and cdo.chave_cliente = " + engine.getField('ftCliente').getValue();
																	}
																	if (engine.getField('ftFornecedor').getValue()) {
																		sql += " and cdo.chave_fornecedor = " + engine.getField('ftFornecedor').getValue();
																	}
																	sql += " order by data desc";
														}
														return sql;
													}
												]]>
											</sqlBuilderDataSource>
										</datasource>
										<key-field>chave_despesa_operacional</key-field>
										<columns>									
											<generated name="EXCLUIR" caption="" expand-ratio="0.02" >
												<scriptColumnGenerator language="JavaScript">
													<![CDATA[
														 importClass(Packages.br.com.davinti.base.vaadin.components.layout.ConfirmationBox);
							                                 importClass(Packages.br.com.davinti.base.vaadin.components.resources.icons16x16.IconLibraryAPISmall);
							                                 importClass(Packages.br.com.davinti.base.vaadin.components.icons.IconFactory); 
							                                 importClass(Packages.br.com.davinti.vitruvio.spi.is.DatabaseSnippet);                                
							                                 
							                                 function Generator() {
							                                     var comp = libService.loadScript('vaadinComponents');                                    
							                                     this.generate = function (itemId, columnId, item, container) {
							                                         var btn = comp.buttonIcon('excluir', function () {  
							                                          
							                                          var deletar = function(idRegistro) {
																	        var sql = 'delete from controle_despesas_operacionais where chave_despesa_operacional = :id';
																	        vQueryService.doInTransaction('vitruvio', new DatabaseSnippet() {
																	            execute: function(db, transaction) {
																	                var params = new java.util.HashMap();
																	                params.put('id', idRegistro);
																	                db.update(sql, params);
																	            }
																	        });
																	        engine.getField('tbLancamentos').refresh();
																	        engine.getGlobalVariable('fncSubTotal')();
																	    }                                                                                               
							                                          var msg = 'Confirma a exclusão?'
							                                                                                                       
							                                          ConfirmationBox.show( 'Confirmar operação'
							                                                         , msg
							                                                         , new ConfirmationBox.ConfirmationBoxListener() {
							                                                               dialogEnd: function(context, action) {
							                                                                  if(action == ConfirmationBox.Action.YES) {
							                                                                     if(deletar){
							                                                                        deletar(itemId);                                                                          
							                                                                     }
							                                                                  }
							                                                               }
							                                                            }
							                                                         ); 
							                                         }, 'trash');                                          
							                                      
							                                         return btn;
							                                     }
							                                 }
							                                 var script = new Generator();
													]]>
												</scriptColumnGenerator>
											</generated>
											<column name="DATA" caption="Data" expand-ratio="0.05" editable="true" editValueRequired="false" commitOnValueChange="true"/>
											<generated name="CLIENTE" caption="Cliente" cache="false" expand-ratio="0.1" >
												<scriptColumnGenerator language="JavaScript">
													<![CDATA[
														importClass(Packages.com.vaadin.ui.ComboBox);
														importClass(Packages.br.com.davinti.base.vaadin.components.data.container.ContainerUtils);
														importClass(Packages.com.vaadin.data.Property);
														
														var setUsuario = function(chave, cliente) {
															var sqlAtualiza = "UPDATE controle_despesas_operacionais SET chave_cliente = ? "+
																	  " WHERE CHAVE_DESPESA_OPERACIONAL = ? ";
															var sql = "Select codigo from clientes where nome = '" + cliente + "'";
												         	var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															var row = dbVitruvio.queryRow(sql);		  
															var params = new java.util.ArrayList();
															params.add(row.codigo);
															params.add(chave);
															vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
														};
														
														function generate(itemId, columnId, item, container) {
															
															var sql = "Select codigo, nome from clientes";
															
															var ds = vQueryService.executeQuery('vitruvio', sql);
															
															if(ds == null){
																return null;
															}
															
															var map = new java.util.LinkedHashMap();
															
															while(ds.next()) {
																map.put(ds.getString('NOME'), ds.getString('NOME'));
															}
															
															var combo = new ComboBox();
															combo.setWidth("120");
															ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
															
															var linha = item;
															if(linha.getItemProperty('CLIENTE').getValue()) {
																combo.setValue(linha.getItemProperty('CLIENTE').getValue());
															}
															
															
															combo.addValueChangeListener(new Property.ValueChangeListener() {
																	valueChange: function(event) {
																		setUsuario(linha.getItemProperty('CHAVE_DESPESA_OPERACIONAL').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<generated name="CATEGORIA" caption="Categoria" cache="false" expand-ratio="0.15" >
												<scriptColumnGenerator language="JavaScript">
													<![CDATA[
														importClass(Packages.com.vaadin.ui.ComboBox);
														importClass(Packages.br.com.davinti.base.vaadin.components.data.container.ContainerUtils);
														importClass(Packages.com.vaadin.data.Property);
														
														var setUsuario = function(chave, cliente) {
															var sqlAtualiza = "UPDATE controle_despesas_operacionais SET chave_categoria = ? "+
																	  " WHERE CHAVE_DESPESA_OPERACIONAL = ? ";
															var sql = "Select codigo from categoria where descricao = '" + cliente + "'";
												         	var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															var row = dbVitruvio.queryRow(sql);		  
															var params = new java.util.ArrayList();
															params.add(row.codigo);
															params.add(chave);
															vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
														};
														
														function generate(itemId, columnId, item, container) {
															
															var sql = "Select codigo, descricao from categoria";
															
															var ds = vQueryService.executeQuery('vitruvio', sql);
															
															if(ds == null){
																return null;
															}
															
															var map = new java.util.LinkedHashMap();
															
															while(ds.next()) {
																map.put(ds.getString('DESCRICAO'), ds.getString('DESCRICAO'));
															}
															
															var combo = new ComboBox();
															combo.setWidth("120");
															ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
															
															var linha = item;
															if(linha.getItemProperty('CATEGORIA').getValue()) {
																combo.setValue(linha.getItemProperty('CATEGORIA').getValue());
															}
															
															
															combo.addValueChangeListener(new Property.ValueChangeListener() {
																	valueChange: function(event) {
																		setUsuario(linha.getItemProperty('CHAVE_DESPESA_OPERACIONAL').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<generated name="SUBCATEGORIA" caption="Sub-categoria" cache="false"  expand-ratio="0.15" >
												<scriptColumnGenerator language="JavaScript">
													<![CDATA[
														importClass(Packages.com.vaadin.ui.ComboBox);
														importClass(Packages.br.com.davinti.base.vaadin.components.data.container.ContainerUtils);
														importClass(Packages.com.vaadin.data.Property);
														
														var setUsuario = function(chave, cliente) {
															var sqlAtualiza = "UPDATE controle_despesas_operacionais SET chave_subcategoria = ? "+
																	  " WHERE CHAVE_DESPESA_OPERACIONAL = ? ";
															var sql = "Select codigo from subcategoria where descricao = '" + cliente + "'";
												         	var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															var row = dbVitruvio.queryRow(sql);		  
															var params = new java.util.ArrayList();
															params.add(row.codigo);
															params.add(chave);
															vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
														};
														
														function generate(itemId, columnId, item, container) {
															
															var sql = "Select codigo, descricao from subcategoria";
															
															var ds = vQueryService.executeQuery('vitruvio', sql);
															
															if(ds == null){
																return null;
															}
															
															var map = new java.util.LinkedHashMap();
															
															while(ds.next()) {
																map.put(ds.getString('DESCRICAO'), ds.getString('DESCRICAO'));
															}
															
															var combo = new ComboBox();
															combo.setWidth("130");
															ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
															
															var linha = item;
															if(linha.getItemProperty('SUBCATEGORIA').getValue()) {
																combo.setValue(linha.getItemProperty('SUBCATEGORIA').getValue());
															}
															
															
															combo.addValueChangeListener(new Property.ValueChangeListener() {
																	valueChange: function(event) {
																		setUsuario(linha.getItemProperty('CHAVE_DESPESA_OPERACIONAL').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<column name="NUMERO_DOCUMENTO" caption="Nr. documento" expand-ratio="0.05" commitOnEnter="true" commitOnValueChange="true" editable="true" />
											<generated name="FORMAPAGAMENTO" caption="Forma pagamento" cache="false"  expand-ratio="0.1" >
												<scriptColumnGenerator language="JavaScript">
													<![CDATA[
														importClass(Packages.com.vaadin.ui.ComboBox);
														importClass(Packages.br.com.davinti.base.vaadin.components.data.container.ContainerUtils);
														importClass(Packages.com.vaadin.data.Property);
														
														var setUsuario = function(chave, cliente) {
															var sqlAtualiza = "UPDATE controle_despesas_operacionais SET chave_forma_pagamento = ? "+
																	  " WHERE CHAVE_DESPESA_OPERACIONAL = ? ";
															var sql = "Select codigo from forma_pagamento where nome = '" + cliente + "'";
												         	var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															var row = dbVitruvio.queryRow(sql);		  
															var params = new java.util.ArrayList();
															params.add(row.codigo);
															params.add(chave);
															vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
														};
														
														function generate(itemId, columnId, item, container) {
															
															var sql = "Select codigo, nome from forma_pagamento";
															
															var ds = vQueryService.executeQuery('vitruvio', sql);
															
															if(ds == null){
																return null;
															}
															
															var map = new java.util.LinkedHashMap();
															
															while(ds.next()) {
																map.put(ds.getString('NOME'), ds.getString('NOME'));
															}
															
															var combo = new ComboBox();
															combo.setWidth("120");
															ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
															
															var linha = item;
															if(linha.getItemProperty('FORMAPAGAMENTO').getValue()) {
																combo.setValue(linha.getItemProperty('FORMAPAGAMENTO').getValue());
															}
															
															
															combo.addValueChangeListener(new Property.ValueChangeListener() {
																	valueChange: function(event) {
																		setUsuario(linha.getItemProperty('CHAVE_DESPESA_OPERACIONAL').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<generated name="VEICULO" caption="Placa" cache="false"  expand-ratio="0.05" >
												<scriptColumnGenerator language="JavaScript">
													<![CDATA[
														importClass(Packages.com.vaadin.ui.ComboBox);
														importClass(Packages.br.com.davinti.base.vaadin.components.data.container.ContainerUtils);
														importClass(Packages.com.vaadin.data.Property);
														
														var setUsuario = function(chave, cliente) {
															var sqlAtualiza = "UPDATE controle_despesas_operacionais SET chave_veiculo = ? "+
																	  " WHERE CHAVE_DESPESA_OPERACIONAL = ? ";
															var sql = "Select codigo from veiculo where placa = '" + cliente + "'";
												         	var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															var row = dbVitruvio.queryRow(sql);		  
															var params = new java.util.ArrayList();
															params.add(row.codigo);
															params.add(chave);
															vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
														};
														
														function generate(itemId, columnId, item, container) {
															
															var sql = "Select codigo, placa from veiculo";
															
															var ds = vQueryService.executeQuery('vitruvio', sql);
															
															if(ds == null){
																return null;
															}
															
															var map = new java.util.LinkedHashMap();
															
															while(ds.next()) {
																map.put(ds.getString('PLACA'), ds.getString('PLACA'));
															}
															
															var combo = new ComboBox();
															combo.setWidth("100");
															ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
															
															var linha = item;
															if(linha.getItemProperty('VEICULO').getValue()) {
																combo.setValue(linha.getItemProperty('VEICULO').getValue());
															}
															
															
															combo.addValueChangeListener(new Property.ValueChangeListener() {
																	valueChange: function(event) {
																		setUsuario(linha.getItemProperty('CHAVE_DESPESA_OPERACIONAL').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<generated name="FUNCIONARIO" caption="Funcionário" cache="false"  expand-ratio="0.1">
												<scriptColumnGenerator language="JavaScript">
													<![CDATA[
														importClass(Packages.com.vaadin.ui.ComboBox);
														importClass(Packages.br.com.davinti.base.vaadin.components.data.container.ContainerUtils);
														importClass(Packages.com.vaadin.data.Property);
														
														var setUsuario = function(chave, cliente) {
															var sqlAtualiza = "UPDATE controle_despesas_operacionais SET chave_funcionario = ? "+
																	  " WHERE CHAVE_DESPESA_OPERACIONAL = ? ";
															var sql = "Select codigo from funcionario where nome = '" + cliente + "'";
												         	var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															var row = dbVitruvio.queryRow(sql);		  
															var params = new java.util.ArrayList();
															params.add(row.codigo);
															params.add(chave);
															vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
														};
														
														function generate(itemId, columnId, item, container) {
															
															var sql = "Select codigo, nome from funcionario";
															
															var ds = vQueryService.executeQuery('vitruvio', sql);
															
															if(ds == null){
																return null;
															}
															
															var map = new java.util.LinkedHashMap();
															
															while(ds.next()) {
																map.put(ds.getString('NOME'), ds.getString('NOME'));
															}
															
															var combo = new ComboBox();
															combo.setWidth("100%");
															ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
															
															var linha = item;
															if(linha.getItemProperty('FUNCIONARIO').getValue()) {
																combo.setValue(linha.getItemProperty('FUNCIONARIO').getValue());
															}
															
															
															combo.addValueChangeListener(new Property.ValueChangeListener() {
																	valueChange: function(event) {
																		setUsuario(linha.getItemProperty('CHAVE_DESPESA_OPERACIONAL').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<generated name="FORNECEDOR" caption="Fornecedor" cache="false"  expand-ratio="0.1">
												<scriptColumnGenerator language="JavaScript">
													<![CDATA[
														importClass(Packages.com.vaadin.ui.ComboBox);
														importClass(Packages.br.com.davinti.base.vaadin.components.data.container.ContainerUtils);
														importClass(Packages.com.vaadin.data.Property);
														
														var setUsuario = function(chave, cliente) {
															var sqlAtualiza = "UPDATE controle_despesas_operacionais SET chave_fornecedor = ? "+
																	  " WHERE CHAVE_DESPESA_OPERACIONAL = ?";
															var sql = "Select codigo from fornecedor where razao_social = '" + cliente + "'";
												         	var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															var row = dbVitruvio.queryRow(sql);		  
															var params = new java.util.ArrayList();
															params.add(row.codigo);
															params.add(chave);
															vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
														};
														
														function generate(itemId, columnId, item, container) {
															
															var sql = "Select codigo, razao_social from fornecedor";
															
															var ds = vQueryService.executeQuery('vitruvio', sql);
															
															if(ds == null){
																return null;
															}
															
															var map = new java.util.LinkedHashMap();
															
															while(ds.next()) {
																map.put(ds.getString('RAZAO_SOCIAL'), ds.getString('RAZAO_SOCIAL'));
															}
															
															var combo = new ComboBox();
															combo.setWidth("120");
															ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
															
															var linha = item;
															if(linha.getItemProperty('FORNECEDOR').getValue()) {
																combo.setValue(linha.getItemProperty('FORNECEDOR').getValue());
															}
															
															
															combo.addValueChangeListener(new Property.ValueChangeListener() {
																	valueChange: function(event) {
																		setUsuario(linha.getItemProperty('CHAVE_DESPESA_OPERACIONAL').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<column name="VALOR" caption="Valor" format="#.##0,00" editable="true" commitOnEnter="true" commitOnValueChange="true" align="RIGHT" decimalSeparator="," />
											<generated name="OBSERVACOES" caption="Observações" expand-ratio="0.2">
												<scriptColumnGenerator language="JavaScript">
													  importClass(Packages.br.com.davinti.vitruvio.ui.core.VitruvioTheme);
													  importClass(Packages.com.vaadin.ui.VerticalLayout);
                                          
			                                          function Generator() {
			                                             var com = libService.loadScript('vaadinComponents');
			                                             this.generate = function(itemId, columnId, item, container) {
			                                             	var titulo = item.getItemProperty('OBSERVACOES').getValue();
			                                             	if (titulo.length() >= 20) {
			                                             		titulo = titulo.substring(0,19) + '...';
			                                             	}
			                                                var btn = com.linkButton(titulo, function(){
			                                                   var subContent = new VerticalLayout();
			                                                   subContent.setId('teste');
			                                                   subContent.setMargin(true);
			                                                   var linha = item;
			                                                   
			                                                   var textArea = com.textArea(null, item.getItemProperty('OBSERVACOES').getValue());
			                                                   var instGravar = function run() {
			                                                   		var sqlAtualiza = 'UPDATE controle_despesas_operacionais SET observacoes = ? ' + 
																					  ' WHERE CHAVE_DESPESA_OPERACIONAL = ? '; 	  
																   	var params = new java.util.ArrayList();
																   	params.add(textArea.getValue());
																   	params.add(linha.getItemProperty('CHAVE_DESPESA_OPERACIONAL').getValue().longValue());
																   	vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
																   	engine.getField('tbLancamentos').refresh();
																   	window.close();
			                                                   };
			                                                   var gravar = com.button('Gravar',instGravar,null);
			                                                   subContent.addComponent(textArea);
			                                                   subContent.addComponent(gravar);
			                                                   var window = com.openWindow(item.getItemProperty('CLIENTE').getValue(), subContent,500,200);
			                                                   
			                                                   textArea.setSizeFull();
			                                                   textArea.addStyleName(com.theme().TEXTAREA_BORDERLESS);
			                                                   window.setModal(true);
			                                                });
			                                                btn.setDescription(item.getItemProperty('OBSERVACOES').getValue());
			                                                var container = com.horizontalLayout([btn]);
			                                                container.setSpacing(false);
			                                                return container;
			                                             }
			                                          }
			                                          var script = new Generator();
												</scriptColumnGenerator>
											</generated>
										</columns>
										<events>
											<itemChange>
												<script language="JavaScript">
													<![CDATA[
														function onChange(event) {
															var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															dbVitruvio.transaction(function() {
															   var sqlAtualiza = "UPDATE controle_despesas_operacionais SET data = :data, numero_documento = :nrDocumento, valor = :valor " + 
																	  " WHERE CHAVE_DESPESA_OPERACIONAL = :chave";
															   this.update(sqlAtualiza, {
																	chave: Number(event.getItemId()),
																	data: event.getField('DATA').getValue(),
																	nrDocumento: Number(event.getField('NUMERO_DOCUMENTO').getValue()),
																	valor: event.getField('VALOR').getConvertedValue()
															   });
													        });
															engine.getGlobalVariable('fncSubTotal')();
															event.commit();	
														}
													]]>
												</script>
											</itemChange>
										</events>
									</DBTable>
								</VerticalLayout>
							</Panel>	
			         	</VerticalLayout>
		         	</Tab> 
		         	
		         	
		         	<!-- AQUI INICIA PAINEL PARTICULARES -->
		         	
		         	
		         	<Tab caption="Particulares">
		         		<VerticalLayout width="100%" spacing="true">
		         			 <Panel caption=" " width="100%" expandRatio="0.1" align="TOP_LEFT" height="100%">
								<VerticalLayout width="100%" margin="true" spacing="true">
									<HorizontalLayout width="100%" spacing="true" height="100%">
								      <ImageWidget id="img1" height="46" width="46" align="TOP_LEFT">
								      		<image>
								      			<base64 extension="jpg">
								      				<![CDATA[
								      					,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA8AAD/4QMraHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjMtYzAxMSA2Ni4xNDU2NjEsIDIwMTIvMDIvMDYtMTQ6NTY6MjcgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzYgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjM5ODI5MTUwOTFEQTExRTg4NjlCRTA3Njc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QTQf//Z
								      				]]>
								      			</base64>
								      		</image>
								      	</ImageWidget>
								      	<DateField type="date" id="dataPessoal" align="TOP_LEFT" caption="Data" width="100%" expandRatio="0.15" required="false" resolution="DAY" description="Informe a data do lançamento" format="dd/MM/yyyy" />
								      	<DBComboBox type="string" id="categoriaPessoal" width="100%" expandRatio="0.2" align="TOP_LEFT" caption="Categoria">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from categoria
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>DESCRICAO</caption-field>
								      	</DBComboBox>
								      	<DBComboBox type="string" id="responsavelPessoal" width="100%" expandRatio="0.2" align="TOP_LEFT" caption="Responsável">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from socios
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>NOME</caption-field>
								      	</DBComboBox>
								      	<DecimalField type="decimal" id="valorPessoal" caption="Valor (R$)" format="#,##0.00" description="Valor da despesa" width="100%" expandRatio="0.15" />
								    </HorizontalLayout>
								    <HorizontalLayout spacing="true" width="100%" height="100%" >
								      	<TextField type="string" id="observacaoPessoal" caption="Observações" width="100%" expandRatio="1" />
								      	<ButtonWidget id="btnGravarPessoal" caption="Gravar" align="BOTTOM_RIGHT" description="Grava o lançamento" width="100" >
											<onClickScript language="JavaScript">
												<![CDATA[
													importClass(Packages.com.vaadin.ui.Notification);
													function run() {
														if (engine.isValid()) {
															var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															var sql;
															dbVitruvio.transaction(function() {
																sql = 	"insert into controle_despesas_pessoais (chave_pessoal,data,chave_categoria,chave_responsavel,valor,observacoes) " +
																		" values (" + dbVitruvio.getSequenceNextValSql('controle_desp_pes_seq') + ",:data,:chave_categoria,:chave_responsavel,:valor,:observacoes)";
															   	this.update(sql, {
																	data: engine.getField('dataPessoal').getValue(),
																	chave_categoria: Number(engine.getField('categoriaPessoal').getValue()),
																	chave_responsavel: Number(engine.getField('responsavelPessoal').getValue()),
																	valor: engine.getField('valorPessoal').getConvertedValue(),
																	observacoes: engine.getField('observacaoPessoal').getValue()
															   });
													        });
													        engine.getField('tbPessoal').refresh();
													        engine.getField('tbTotalSocios').refresh();
													        engine.getGlobalVariable('fncLimpaCampos')();
													        engine.getGlobalVariable('fncSubTotalPessoal')();
															Notification.show(null, 'Dados salvos', Notification.Type.TRAY_NOTIFICATION);
														}
													}
												]]>
											</onClickScript>
										</ButtonWidget>
									</HorizontalLayout>
								</VerticalLayout>
							</Panel>
			
							<Panel width="100%" margin="true" >
								<VerticalLayout width="100%" spacing="true" align="TOP_LEFT" >
									<HorizontalLayout width="80%" spacing="true" align="TOP_LEFT">
										<DateField type="date" id="dataInicioPessoal" caption="Data inicial" align="TOP_LEFT" width="100%" expandRatio="0.2" description="Data iniacial da exibição" format="dd/MM/yyyy" />
										<DateField type="date" id="dataFinalPessoal" caption="Data final" align="TOP_LEFT" width="100%" expandRatio="0.2" description="Data final da exibição" format="dd/MM/yyyy" />
										<DBComboBox type="string" id="ftResponsavelPessoal" width="100%" expandRatio="0.6" align="TOP_LEFT" caption="Responsável" allowNullSelection="true">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from socios
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>NOME</caption-field>
								      	</DBComboBox>
										<ButtonWidget id="btnFiltrarPessoal" caption="Filtrar" align="BOTTOM_RIGHT" description="Aplica filtro de data" width="100" >
											<onClickScript language="JavaScript">
												<![CDATA[
													function run() {
														engine.getField('tbPessoal').refresh();
														engine.getField('tbTotalSocios').refresh();
														engine.getGlobalVariable('fncSubTotalPessoal')();
													}
												]]>
											</onClickScript>
										</ButtonWidget>
										<ButtonWidget id="btnLimparFiltroPessoal" caption="Limpar" align="BOTTOM_LEFT" description="Limpar filtro" width="100" >
											<onClickScript language="JavaScript">
												<![CDATA[
													function run() {
														var d = new java.util.Date();
														engine.getField('dataInicioPessoal').setValue(d);
														engine.getField('dataFinalPessoal').setValue(d);
														engine.getField('ftResponsavelPessoal')["setValue(java.lang.Object)"](null);
														engine.getField('tbPessoal').refresh();
														engine.getField('tbTotalSocios').refresh();
														engine.getGlobalVariable('fncSubTotalPessoal')();
													}
												]]>
											</onClickScript>
										</ButtonWidget>
										<Label id="subPessoal" align="BOTTOM_RIGHT" width="100%" expandRatio="1" contentMode="HTML">
											<value>
												
											</value>
										</Label>
									</HorizontalLayout>
									<HorizontalLayout width="100%" spacing="true">
										<DBTable id="tbPessoal" type="number" width="100%" height="100%" expandRatio="1" rows="10" selectable="false" exportXLS="true" editable="true" >
											<datasource>
												<sqlBuilderDataSource connection-key="vitruvio" language="JavaScript">
													<![CDATA[
														function buildSQL(params) {
															var sql = 	"Select 	cdp.chave_pessoal," +
																		" cdp.data," +
																		" (select cc.descricao from categoria cc where cc.codigo = cdp.chave_categoria) categoria," +
																		" (select cs.nome from socios cs where cs.codigo = cdp.chave_responsavel) responsavel," +
																		" cdp.observacoes," +
																		" cdp.valor" +
																		" from controle_despesas_pessoais cdp where 1=2";
															if (engine) {
																sql = 	"Select 	cdp.chave_pessoal," +
																		" cdp.data," +
																		" (select cc.descricao from categoria cc where cc.codigo = cdp.chave_categoria) categoria," +
																		" (select cs.nome from socios cs where cs.codigo = cdp.chave_responsavel) responsavel," +
																		" cdp.observacoes," +
																		" cdp.valor valor" +
																		" from controle_despesas_pessoais cdp where cdp.data between '" + engine.getField('dataInicioPessoal') + "' and '" + engine.getField('dataFinalPessoal') + "'";
																		if (engine.getField('ftResponsavelPessoal').getValue()) {
																			sql += " and cdp.chave_responsavel = " + engine.getField('ftResponsavelPessoal').getValue();
																		}
																		sql += " order by data desc";
															}
															return sql;
														}
													]]>
												</sqlBuilderDataSource>
											</datasource>
											<key-field>chave_pessoal</key-field>
											<columns>
												<generated name="EXCLUIR" caption="Excluir" expand-ratio="0.1">
													<scriptColumnGenerator language="JavaScript">
														<![CDATA[
															importClass(Packages.br.com.davinti.base.vaadin.components.layout.ConfirmationBox);
							                                 importClass(Packages.br.com.davinti.base.vaadin.components.resources.icons16x16.IconLibraryAPISmall);
							                                 importClass(Packages.br.com.davinti.base.vaadin.components.icons.IconFactory); 
							                                 importClass(Packages.br.com.davinti.vitruvio.spi.is.DatabaseSnippet);                                
							                                 
							                                 function Generator() {
							                                     var comp = libService.loadScript('vaadinComponents');                                    
							                                     this.generate = function (itemId, columnId, item, container) {
							                                         var btn = comp.buttonIcon('excluir', function () {  
							                                          
							                                          var deletar = function(idRegistro) {
																	        var sql = 'delete from controle_despesas_pessoais where chave_pessoal = :id';
																	        vQueryService.doInTransaction('vitruvio', new DatabaseSnippet() {
																	            execute: function(db, transaction) {
																	                var params = new java.util.HashMap();
																	                params.put('id', idRegistro);
																	                db.update(sql, params);
																	            }
																	        });
																	        engine.getField('tbPessoal').refresh();
																	        engine.getField('tbTotalSocios').refresh();
																	        engine.getGlobalVariable('fncSubTotalPessoal')();
																	    }                                                                                               
							                                          var msg = 'Confirma a exclusão?'
							                                                                                                       
							                                          ConfirmationBox.show( 'Confirmar operação'
							                                                         , msg
							                                                         , new ConfirmationBox.ConfirmationBoxListener() {
							                                                               dialogEnd: function(context, action) {
							                                                                  if(action == ConfirmationBox.Action.YES) {
							                                                                     if(deletar){
							                                                                        deletar(itemId);                                                                          
							                                                                     }
							                                                                  }
							                                                               }
							                                                            }
							                                                         ); 
							                                         }, 'trash');                                          
							                                      
							                                         return btn;
							                                     }
							                                 }
							                                 var script = new Generator();
														]]>
													</scriptColumnGenerator>
												</generated>
												<column name="DATA" caption="Data" format="dd/MM/yyyy" expand-ratio="0.05" commitOnValueChange="true" editable="true" />
												<generated name="CATEGORIA" caption="Categoria" cache="false" expand-ratio="0.15" >
													<scriptColumnGenerator language="JavaScript">
														<![CDATA[
															importClass(Packages.com.vaadin.ui.ComboBox);
															importClass(Packages.br.com.davinti.base.vaadin.components.data.container.ContainerUtils);
															importClass(Packages.com.vaadin.data.Property);
															
															var setUsuario = function(chave, cliente) {
																var sqlAtualiza = "UPDATE controle_despesas_pessoais SET chave_categoria = ? "+
																		  " WHERE CHAVE_PESSOAL = ? ";
																var sql = "Select codigo from categoria where descricao = '" + cliente + "'";
													         	var db = libService.loadScript('db');
																var dbVitruvio = new db('vitruvio');
																var row = dbVitruvio.queryRow(sql);		  
																var params = new java.util.ArrayList();
																params.add(row.codigo);
																params.add(chave);
																vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
															};
															
															function generate(itemId, columnId, item, container) {
																
																var sql = "Select codigo, descricao from categoria";
																
																var ds = vQueryService.executeQuery('vitruvio', sql);
																
																if(ds == null){
																	return null;
																}
																
																var map = new java.util.LinkedHashMap();
																
																while(ds.next()) {
																	map.put(ds.getString('DESCRICAO'), ds.getString('DESCRICAO'));
																}
																
																var combo = new ComboBox();
																combo.setWidth("100%");
																ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
																
																var linha = item;
																if(linha.getItemProperty('CATEGORIA').getValue()) {
																	combo.setValue(linha.getItemProperty('CATEGORIA').getValue());
																}
																
																
																combo.addValueChangeListener(new Property.ValueChangeListener() {
																		valueChange: function(event) {
																			setUsuario(linha.getItemProperty('CHAVE_PESSOAL').getValue().longValue(),
																		   	event.getProperty().getValue());
																		},
																		hashCode: function() {
																			return combo.hashCode();
																		}
																	});
																
																return combo;
															}
														]]>
													</scriptColumnGenerator>
												</generated>
												<generated name="RESPONSAVEL" caption="Responsável" cache="false" expand-ratio="0.15" >
													<scriptColumnGenerator language="JavaScript">
														<![CDATA[
															importClass(Packages.com.vaadin.ui.ComboBox);
															importClass(Packages.br.com.davinti.base.vaadin.components.data.container.ContainerUtils);
															importClass(Packages.com.vaadin.data.Property);
															
															var setUsuario = function(chave, cliente) {
																var sqlAtualiza = "UPDATE controle_despesas_pessoais SET chave_responsavel = ? "+
																		  " WHERE CHAVE_PESSOAL = ? ";
																var sql = "Select codigo from socios where nome = '" + cliente + "'";
													         	var db = libService.loadScript('db');
																var dbVitruvio = new db('vitruvio');
																var row = dbVitruvio.queryRow(sql);		  
																var params = new java.util.ArrayList();
																params.add(row.codigo);
																params.add(chave);
																vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
															};
															
															function generate(itemId, columnId, item, container) {
																
																var sql = "Select codigo, nome from socios";
																
																var ds = vQueryService.executeQuery('vitruvio', sql);
																
																if(ds == null){
																	return null;
																}
																
																var map = new java.util.LinkedHashMap();
																
																while(ds.next()) {
																	map.put(ds.getString('NOME'), ds.getString('NOME'));
																}
																
																var combo = new ComboBox();
																combo.setWidth("100%");
																ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
																
																var linha = item;
																if(linha.getItemProperty('RESPONSAVEL').getValue()) {
																	combo.setValue(linha.getItemProperty('RESPONSAVEL').getValue());
																}
																
																
																combo.addValueChangeListener(new Property.ValueChangeListener() {
																		valueChange: function(event) {
																			setUsuario(linha.getItemProperty('CHAVE_PESSOAL').getValue().longValue(),
																		   	event.getProperty().getValue());
																		},
																		hashCode: function() {
																			return combo.hashCode();
																		}
																	});
																
																return combo;
															}
														]]>
													</scriptColumnGenerator>
												</generated>
												<column name="VALOR" caption="Valor" format="#.##0,00" expand-ratio="0.1" commitOnValueChange="true" editable="true" align="RIGHT" decimalSeparator="," />
												<generated name="OBSERVACOES" caption="Observações" expand-ratio="0.2">
													<scriptColumnGenerator language="JavaScript">
														  importClass(Packages.br.com.davinti.vitruvio.ui.core.VitruvioTheme);
														  importClass(Packages.com.vaadin.ui.VerticalLayout);
	                                          
				                                          function Generator() {
				                                             var com = libService.loadScript('vaadinComponents');
				                                             this.generate = function(itemId, columnId, item, container) {
				                                             	var titulo = item.getItemProperty('OBSERVACOES').getValue();
				                                             	if (titulo.length() >= 20) {
				                                             		titulo = titulo.substring(0,19) + '...';
				                                             	}
				                                                var btn = com.linkButton(titulo, function(){
				                                                   var subContent = new VerticalLayout();
				                                                   subContent.setId('teste');
				                                                   subContent.setMargin(true);
				                                                   var linha = item;
				                                                   
				                                                   var textArea = com.textArea(null, item.getItemProperty('OBSERVACOES').getValue());
				                                                   var instGravar = function run() {
				                                                   		var sqlAtualiza = 'UPDATE controle_despesas_pessoais SET observacoes = ? ' + 
																						  ' WHERE CHAVE_PESSOAL = ? '; 	  
																	   	var params = new java.util.ArrayList();
																	   	params.add(textArea.getValue());
																	   	params.add(linha.getItemProperty('CHAVE_PESSOAL').getValue().longValue());
																	   	vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
																	   	engine.getField('tbPessoal').refresh();
																	   	window.close();
				                                                   };
				                                                   var gravar = com.button('Gravar',instGravar,null);
				                                                   subContent.addComponent(textArea);
				                                                   subContent.addComponent(gravar);
				                                                   var window = com.openWindow(item.getItemProperty('CATEGORIA').getValue(), subContent,500,200);
				                                                   
				                                                   textArea.setSizeFull();
				                                                   textArea.addStyleName(com.theme().TEXTAREA_BORDERLESS);
				                                                   window.setModal(true);
				                                                });
				                                                btn.setDescription(item.getItemProperty('OBSERVACOES').getValue());
				                                                var container = com.horizontalLayout([btn]);
				                                                container.setSpacing(false);
				                                                return container;
				                                             }
				                                          }
				                                          var script = new Generator();
													</scriptColumnGenerator>
												</generated>
											</columns>
											<events>
												<itemChange>
													<script language="JavaScript">
														<![CDATA[
															function onChange(event) {
																var db = libService.loadScript('db');
																var dbVitruvio = new db('vitruvio');
																dbVitruvio.transaction(function() {
																   //if (event.isChanged('DATA')) {
																	   var sqlAtualiza = "UPDATE controle_despesas_pessoais SET data = :data, valor = :valor " + 
																			  " WHERE CHAVE_PESSOAL = :chave";
																   //}
																   this.update(sqlAtualiza, {
																		chave: Number(event.getItemId()),
																		data: event.getField('DATA').getValue(),
																		valor: event.getField('VALOR').getConvertedValue()
																   });
														        });
																engine.getGlobalVariable('fncSubTotalPessoal')();
																engine.getField('tbTotalSocios').refresh();
																event.commit();	
															}
														]]>
													</script>
												</itemChange>
											</events>
										</DBTable>
										<DBTable id="tbTotalSocios" align="TOP_LEFT" type="string" width="100%" expandRatio="0.3" rows="10" exportXLS="true" editable="false" selectable="false">
											<datasource>
												<sqlBuilderDataSource connection-key="vitruvio" language="JavaScript">
													<![CDATA[
														function buildSQL(params) {
															var sql = 	"Select cs.nome, sum(cdp.valor) total " +
																		"from controle_despesas_pessoais " +
																		"cdp inner join socios cs on cs.codigo = cdp.chave_responsavel " +
																		"where 1=2 group by cs.nome";
															if (engine) {
																sql = 	"Select cs.nome, replace(replace(replace(to_char(sum(cdp.valor), '9999999999D99'),',','-' ),'.',','),'-','.') total " +
																		"from controle_despesas_pessoais " +
																		"cdp inner join socios cs on cs.codigo = cdp.chave_responsavel " +
																		"where cdp.data between '" + engine.getField('dataInicioPessoal') + "' and '" + engine.getField('dataFinalPessoal') + "'";
																		if (engine.getField('ftResponsavelPessoal').getValue()) {
																			sql += " and cdp.chave_responsavel = " + engine.getField('ftResponsavelPessoal').getValue();
																		}
																		sql += " group by cs.nome";
															}
															return sql;
														}
													]]>
												</sqlBuilderDataSource>
											</datasource>
											<key-field>NOME</key-field>
											<columns>
												<column name="NOME" caption="Responsável" expand-ratio="1" />
												<column name="TOTAL" caption="Total" expand-ratio="0.2" />
											</columns>
										</DBTable>
									</HorizontalLayout>
								</VerticalLayout>
							</Panel>
		         		</VerticalLayout>
		         	</Tab>
		         	
		         	
		         	<!-- AQUI INICIA O PAINEL COMBUSTÍVEIS -->
		         	
		         	<Tab caption="Combustíveis">
		         		<VerticalLayout width="100%" spacing="true">
		         			 <Panel caption=" " width="100%" expandRatio="0.1" align="TOP_LEFT" height="100%">
								<VerticalLayout width="100%" margin="true" spacing="true">
									<HorizontalLayout width="100%" spacing="true" height="100%">
								      <ImageWidget id="img1" height="46" width="46" align="TOP_LEFT">
								      		<image>
								      			<base64 extension="jpg">
								      				<![CDATA[
								      					,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdW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KcOI4lFZBlr1Si1bj3/FYxFpY5znGpyinIgbq0dK6tQEQ/5wvf+bpf0nPTDr/20X03c4QvhrtYSXh9wivmUsxIuhuVJVMqbUw+yG3EqwLkSUGcpzSNcKt8+Y4byDZ4HNNag1GdEW9m6N1ahL1cPMrl0ndPikU5vVWwVDooiueKZpwrBr0y1eCEo31cUztxUpiwjHT4s/rRPdmcmrRzJVSUrtS+hhlM1LISkDVANtbvnkEbBVzipXvDRU5grC9nN+y+4aMO63eKW2XrS8emOw+HN7p3bRgw9Gfnyqt7Y7THw1XrhkoUcv2We8KVU0QAdOlbWoKPKnwxSt/eWNqTNB19LdfCOFM7S+w+y/NrRN5h5lZQ6goUnWCJERz6WJ0bi14LXDQU4a4EVC0iNerIxYvTRW6srHQ2w2VHadg8Z2QXZ2M1y7DE0uPQOMqOSVrBVxTWyWJm3N4jJdSodZewDkTHUNybiZZNqfalOc+ofbKkV1dmU0zNUpD9CLIxYsjFi8Vy9k4B3/dy7OOWLm7XkhXvPueH/ZwU7Wfk08yng2lfYqjr/uhiOHe6+xP9uKTceCVyY/01/qTRnetNF2o/dDGPWxbN5ilz4erBFn4JXLWvbxfgtJO9fgklL3Tcp7rg3PZ3csPRF6tdjgGyw4OzSnQlUmKvtVrwrrBC0WRixf/Z
								      				]]>
								      			</base64>
								      		</image>
								      	</ImageWidget>
								      	<DateField type="date" id="dataCombustivel" align="TOP_LEFT" caption="Data" width="100%" expandRatio="0.15" required="false" resolution="DAY" description="Informe a data do lançamento" format="dd/MM/yyyy" />
								      	<DBComboBox type="string" id="placaCombustivel" width="100%" expandRatio="0.2" align="TOP_LEFT" caption="Placa">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from veiculo
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>PLACA</caption-field>
								      	</DBComboBox>
								      	<DBComboBox type="string" id="clienteCombustivel" width="100%" expandRatio="0.2" align="TOP_LEFT" caption="Cliente">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from clientes
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>NOME</caption-field>
								      	</DBComboBox>
								      	<TextField type="string" id="observacaoCombustivel" caption="Observações" width="100%" expandRatio="1" />
								    </HorizontalLayout>
								    <HorizontalLayout spacing="true" width="100%" height="100%" >
								      	<DBComboBox type="string" id="combustivel" width="100%" expandRatio="0.2" align="TOP_LEFT" caption="Combustível">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from combustivel
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>DESCRICAO</caption-field>
								      	</DBComboBox>
								      	<DecimalField type="decimal" id="litrosCombustivel" caption="Litros" format="#,##0.000" immediate="true" groupingSeparator="." updatable="true" >
								      		<events>
								      			<valueChange>
								      				<script language="JavaScript">
								      					<![CDATA[
								      						function run() {
								      							var total = engine.getField('litrosCombustivel').getConvertedValue() * engine.getField('valorCombustivel').getConvertedValue();
								      							var media = engine.getField('kmRodado').getConvertedValue() / engine.getField('litrosCombustivel').getConvertedValue()
								      							engine.getField('mediaCombustivel').setValue(media); 
								      							engine.getField('totalCombustivel').setValue(total); 
								      						}
								      					]]>
								      				</script>
								      			</valueChange>
								      		</events>
								      	</DecimalField>
								      	<DecimalField type="decimal" id="valorCombustivel" caption="Valor/Litro" format="#,##0.000" immediate="true" updatable="true" groupingSeparator="." >
								      		<events>
								      			<valueChange>
								      				<script language="JavaScript">
								      					<![CDATA[
								      						function run() {
								      							var total = engine.getField('litrosCombustivel').getConvertedValue() * engine.getField('valorCombustivel').getConvertedValue();
								      							engine.getField('totalCombustivel').setValue(total); 
								      						}
								      					]]>
								      				</script>
								      			</valueChange>
								      		</events>
								      	</DecimalField>
								      	<DecimalField type="decimal" id="totalCombustivel" caption="Valor Total" format="#,##0.00" />
								      	<DecimalField type="decimal" id="kmInicial" caption="Km Inicial" immediate="true" updatable="true" groupingSeparator=".">
								      		<events>
								      			<valueChange>
								      				<script language="JavaScript">
								      					<![CDATA[
								      						function run() {
								      							var rodado = engine.getField('kmFinal').getConvertedValue() - engine.getField('kmInicial').getConvertedValue();
								      							engine.getField('kmRodado').setValue(rodado);
								      							var media = engine.getField('kmRodado').getConvertedValue() / engine.getField('litrosCombustivel').getConvertedValue()
								      							engine.getField('mediaCombustivel').setValue(media); 
								      						}
								      					]]>
								      				</script>
								      			</valueChange>
								      		</events>
								      	</DecimalField>
								      	<DecimalField type="decimal" id="kmFinal" caption="Km Final" immediate="true" updatable="true" groupingSeparator="." >
								      		<events>
								      			<valueChange>
								      				<script language="JavaScript">
								      					<![CDATA[
								      						function run() {
								      							var rodado = engine.getField('kmFinal').getConvertedValue() - engine.getField('kmInicial').getConvertedValue();
								      							engine.getField('kmRodado').setValue(rodado);
								      							var media = engine.getField('kmRodado').getConvertedValue() / engine.getField('litrosCombustivel').getConvertedValue()
								      							engine.getField('mediaCombustivel').setValue(media); 
								      						}
								      					]]>
								      				</script>
								      			</valueChange>
								      		</events>
								      	</DecimalField>
								      	<DecimalField type="decimal" id="kmRodado" caption="Km Rodados" />
								      	<DecimalField type="decimal" id="mediaCombustivel" caption="Média Consumo" />
								      	<ButtonWidget id="btnGravarCombustivel" caption="Gravar" align="BOTTOM_RIGHT" description="Grava o lançamento" width="100" >
											<onClickScript language="JavaScript">
												<![CDATA[
													importClass(Packages.com.vaadin.ui.Notification);
													function run() {
														if (engine.isValid()) {
															var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															var sql;
															dbVitruvio.transaction(function() {
																sql = 	"insert into controle_despesas_combustiveis (chave_despesa_combustivel,data,chave_veiculo,chave_cliente,observacoes,chave_combustivel,litros,valor_litro,total_combustivel,km_inicial,km_final,km_rodado,media_consumo) " +
																		" values (" + dbVitruvio.getSequenceNextValSql('controle_desp_comb_seq') + ",:data,:chave_veiculo,:chave_cliente,:observacoes,:chave_combustivel,:litro,:valor_litro,:total_combustivel,:km_inicial,:km_final,:km_rodado,:media_combustivel)";
															   	this.update(sql, {
																	data: engine.getField('dataCombustivel').getValue(),
																	chave_veiculo: Number(engine.getField('placaCombustivel').getValue()),
																	chave_cliente: Number(engine.getField('clienteCombustivel').getValue()),
																	observacoes: engine.getField('observacaoCombustivel').getValue(),
																	chave_combustivel: Number(engine.getField('combustivel').getValue()),
																	litro: engine.getField('litrosCombustivel').getConvertedValue(),
																	valor_litro: engine.getField('valorCombustivel').getConvertedValue(),
																	total_combustivel: engine.getField('totalCombustivel').getConvertedValue(),
																	km_inicial: engine.getField('kmInicial').getConvertedValue(),
																	km_final: engine.getField('kmFinal').getConvertedValue(),
																	km_rodado: engine.getField('kmRodado').getConvertedValue(),
																	media_combustivel: engine.getField('mediaCombustivel').getConvertedValue()
															   });
													        });
													        engine.getField('tbCombustivel').refresh();
													        engine.getField('tbTotalCombustivel').refresh();
													        engine.getGlobalVariable('fncLimpaCampos')();
													        engine.getGlobalVariable('fncSubTotalCombustivel')();
															Notification.show(null, 'Dados salvos', Notification.Type.TRAY_NOTIFICATION);
														}
													}
												]]>
											</onClickScript>
										</ButtonWidget>
									</HorizontalLayout>
								</VerticalLayout>
							</Panel>
			
							<Panel width="100%" margin="true" >
								<VerticalLayout width="100%" spacing="true" align="TOP_LEFT" >
									<HorizontalLayout width="100%" spacing="true" align="TOP_LEFT">
										<DateField type="date" id="dataInicioCombustivel" caption="Data inicial" align="TOP_LEFT" width="100%" expandRatio="0.15" description="Data iniacial da exibição" format="dd/MM/yyyy" />
										<DateField type="date" id="dataFinalCombustivel" caption="Data final" align="TOP_LEFT" width="100%" expandRatio="0.15" description="Data final da exibição" format="dd/MM/yyyy" />
										<DBComboBox type="string" id="ftPlacaCombustivel" width="100%" expandRatio="0.15" align="TOP_LEFT" caption="Placa" allowNullSelection="true">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from veiculo
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>PLACA</caption-field>
								      	</DBComboBox>
								      	<DBComboBox type="string" id="ftCombustivel" width="100%" expandRatio="0.2" align="TOP_LEFT" caption="Combustível" allowNullSelection="true">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from combustivel
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>DESCRICAO</caption-field>
								      	</DBComboBox>
								      	<DBComboBox type="string" id="ftClienteCombustivel" width="100%" expandRatio="0.2" align="TOP_LEFT" caption="Cliente" allowNullSelection="true">
								      		<datasource>
								      			<freeQuery connection-key="vitruvio">
								      				<![CDATA[
								      					Select * from clientes
								      				]]>
								      			</freeQuery>
								      		</datasource>
								      		<key-field>CODIGO</key-field>
								      		<caption-field>NOME</caption-field>
								      	</DBComboBox>
										<ButtonWidget id="btnFiltrarCombustivel" caption="Filtrar" align="BOTTOM_RIGHT" description="Aplica filtro de data" width="100" >
											<onClickScript language="JavaScript">
												<![CDATA[
													function run() {
														engine.getField('tbCombustivel').refresh();
														engine.getField('tbTotalCombustivel').refresh();
														engine.getGlobalVariable('fncSubTotalCombustivel')();
													}
												]]>
											</onClickScript>
										</ButtonWidget>
										<ButtonWidget id="btnLimparFiltroCombustivel" caption="Limpar" align="BOTTOM_LEFT" description="Limpar filtro" width="100" >
											<onClickScript language="JavaScript">
												<![CDATA[
													function run() {
														var d = new java.util.Date();
														engine.getField('dataInicioCombustivel').setValue(d);
														engine.getField('dataFinalCombustivel').setValue(d);
														engine.getField('ftPlacaCombustivel')["setValue(java.lang.Object)"](null);
														engine.getField('ftCombustivel')["setValue(java.lang.Object)"](null);
														engine.getField('ftClienteCombustivel')["setValue(java.lang.Object)"](null);
														engine.getField('tbCombustivel').refresh();
														engine.getField('tbTotalCombustivel').refresh();
														engine.getGlobalVariable('fncSubTotalCombustivel')();
													}
												]]>
											</onClickScript>
										</ButtonWidget>
										<Label id="subCombustivel" align="BOTTOM_RIGHT" width="100%" expandRatio="1" contentMode="HTML">
											<value>
												
											</value>
										</Label>
									</HorizontalLayout>
									<HorizontalLayout width="100%" spacing="true">
										<DBTable id="tbCombustivel" requireFilter="true" showRowCount="true" type="number" width="100%" height="100%" expandRatio="0.75" rows="10" selectable="false" exportXLS="true" editable="true" >
											<datasource>
												<sqlBuilderDataSource connection-key="vitruvio" language="JavaScript">
													<![CDATA[
														function buildSQL(params) {
															var sql = 	"select cdc.chave_despesa_combustivel, " +
																		"cdc.data, " +
																		"(Select v.placa from veiculo v where v.codigo = cdc.chave_veiculo) placa, " +
																		"(Select o.nome from clientes o where o.codigo = cdc.chave_cliente) cliente, " +
																		"cdc.observacoes, " +
																		"(Select c.descricao from combustivel c where c.codigo = cdc.chave_combustivel) combustivel, " +
																		"cdc.litros, " +
																		"cdc.valor_litro, " +
																		"cdc.total_combustivel, " +
																		"cdc.km_inicial, " +
																		"cdc.km_final, " +
																		"cdc.km_rodado, " +
																		"cdc.media_consumo " +
																		"from controle_despesas_combustiveis cdc where 1=2";
															if (engine) {
																sql = 	"select cdc.chave_despesa_combustivel, " +
																		"cdc.data, " +
																		"(Select v.placa from veiculo v where v.codigo = cdc.chave_veiculo) placa, " +
																		"(Select o.nome from clientes o where o.codigo = cdc.chave_cliente) cliente, " +
																		"cdc.observacoes, " +
																		"(Select c.descricao from combustivel c where c.codigo = cdc.chave_combustivel) combustivel, " +
																		"cdc.litros, " +
																		"cdc.valor_litro valor_litro, " +
																		"cdc.total_combustivel total_combustivel, " +
																		"cdc.km_inicial, " +
																		"cdc.km_final, " +
																		"cdc.km_rodado, " +
																		"cdc.media_consumo " +
																		"from controle_despesas_combustiveis cdc where cdc.data between '" + engine.getField('dataInicioCombustivel') + "' and '" + engine.getField('dataFinalCombustivel') + "'";
																		if (engine.getField('ftPlacaCombustivel').getValue()) {
																			sql += " and cdc.chave_veiculo = " + engine.getField('ftPlacaCombustivel').getValue();
																		}
																		if (engine.getField('ftCombustivel').getValue()) {
																			sql += " and cdc.chave_combustivel = " + engine.getField('ftCombustivel').getValue();
																		}
																		if (engine.getField('ftClienteCombustivel').getValue()) {
																			sql += " and cdc.chave_cliente = " + engine.getField('ftClienteCombustivel').getValue();
																		}
																		sql += " order by data desc";
															}
															return sql;
														}
													]]>
												</sqlBuilderDataSource>
											</datasource>
											<key-field>chave_despesa_combustivel</key-field>
											<columns>
												<generated name="EXCLUIR" caption="" expand-ratio="0.05">
													<scriptColumnGenerator language="JavaScript">
														<![CDATA[
															importClass(Packages.br.com.davinti.base.vaadin.components.layout.ConfirmationBox);
							                                 importClass(Packages.br.com.davinti.base.vaadin.components.resources.icons16x16.IconLibraryAPISmall);
							                                 importClass(Packages.br.com.davinti.base.vaadin.components.icons.IconFactory); 
							                                 importClass(Packages.br.com.davinti.vitruvio.spi.is.DatabaseSnippet);                                
							                                 
							                                 function Generator() {
							                                     var comp = libService.loadScript('vaadinComponents');                                    
							                                     this.generate = function (itemId, columnId, item, container) {
							                                         var btn = comp.buttonIcon('excluir', function () {  
							                                          
							                                          var deletar = function(idRegistro) {
																	        var sql = 'delete from controle_despesas_combustiveis where chave_despesa_combustivel = :id';
																	        vQueryService.doInTransaction('vitruvio', new DatabaseSnippet() {
																	            execute: function(db, transaction) {
																	                var params = new java.util.HashMap();
																	                params.put('id', idRegistro);
																	                db.update(sql, params);
																	            }
																	        });
																	        engine.getField('tbCombustivel').refresh();
																	        engine.getField('tbTotalCombustivel').refresh();
																	        engine.getGlobalVariable('fncSubTotalCombustivel')();
																	    }                                                                                               
							                                          var msg = 'Confirma a exclusão?'
							                                                                                                       
							                                          ConfirmationBox.show( 'Confirmar operação'
							                                                         , msg
							                                                         , new ConfirmationBox.ConfirmationBoxListener() {
							                                                               dialogEnd: function(context, action) {
							                                                                  if(action == ConfirmationBox.Action.YES) {
							                                                                     if(deletar){
							                                                                        deletar(itemId);                                                                          
							                                                                     }
							                                                                  }
							                                                               }
							                                                            }
							                                                         ); 
							                                         }, 'trash');                                          
							                                      
							                                         return btn;
							                                     }
							                                 }
							                                 var script = new Generator();
														]]>
													</scriptColumnGenerator>
												</generated>
												<column name="DATA" caption="Data" format="dd/MM/yyyy" expand-ratio="0.05" commitOnValueChange="true" editable="true" />
												<generated name="PLACA" caption="Veículo" cache="false"  expand-ratio="0.05" >
													<scriptColumnGenerator language="JavaScript">
														<![CDATA[
															importClass(Packages.com.vaadin.ui.ComboBox);
															importClass(Packages.br.com.davinti.base.vaadin.components.data.container.ContainerUtils);
															importClass(Packages.com.vaadin.data.Property);
															
															var setUsuario = function(chave, cliente) {
																var sqlAtualiza = "UPDATE controle_despesas_combustiveis SET chave_veiculo = ? "+
																		  " WHERE CHAVE_DESPESA_COMBUSTIVEL = ? ";
																var sql = "Select codigo from veiculo where placa = '" + cliente + "'";
													         	var db = libService.loadScript('db');
																var dbVitruvio = new db('vitruvio');
																var row = dbVitruvio.queryRow(sql);		  
																var params = new java.util.ArrayList();
																params.add(row.codigo);
																params.add(chave);
																vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
															};
															
															function generate(itemId, columnId, item, container) {
																
																var sql = "Select codigo, placa from veiculo";
																
																var ds = vQueryService.executeQuery('vitruvio', sql);
																
																if(ds == null){
																	return null;
																}
																
																var map = new java.util.LinkedHashMap();
																
																while(ds.next()) {
																	map.put(ds.getString('PLACA'), ds.getString('PLACA'));
																}
																
																var combo = new ComboBox();
																combo.setWidth("100%");
																ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
																
																var linha = item;
																if(linha.getItemProperty('PLACA').getValue()) {
																	combo.setValue(linha.getItemProperty('PLACA').getValue());
																}
																
																
																combo.addValueChangeListener(new Property.ValueChangeListener() {
																		valueChange: function(event) {
																			setUsuario(linha.getItemProperty('CHAVE_DESPESA_COMBUSTIVEL').getValue().longValue(),
																		   	event.getProperty().getValue());
																		},
																		hashCode: function() {
																			return combo.hashCode();
																		}
																	});
																
																return combo;
															}
														]]>
													</scriptColumnGenerator>
												</generated>
												<generated name="CLIENTE" caption="Cliente" cache="false" expand-ratio="0.1" >
													<scriptColumnGenerator language="JavaScript">
														<![CDATA[
															importClass(Packages.com.vaadin.ui.ComboBox);
															importClass(Packages.br.com.davinti.base.vaadin.components.data.container.ContainerUtils);
															importClass(Packages.com.vaadin.data.Property);
															
															var setUsuario = function(chave, cliente) {
																var sqlAtualiza = "UPDATE controle_despesas_combustiveis SET chave_cliente = ? "+
																		  " WHERE CHAVE_DESPESA_COMBUSTIVEL = ? ";
																var sql = "Select codigo from clientes where nome = '" + cliente + "'";
													         	var db = libService.loadScript('db');
																var dbVitruvio = new db('vitruvio');
																var row = dbVitruvio.queryRow(sql);		  
																var params = new java.util.ArrayList();
																params.add(row.codigo);
																params.add(chave);
																vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
															};
															
															function generate(itemId, columnId, item, container) {
																
																var sql = "Select codigo, nome from clientes";
																
																var ds = vQueryService.executeQuery('vitruvio', sql);
																
																if(ds == null){
																	return null;
																}
																
																var map = new java.util.LinkedHashMap();
																
																while(ds.next()) {
																	map.put(ds.getString('NOME'), ds.getString('NOME'));
																}
																
																var combo = new ComboBox();
																combo.setWidth("100%");
																ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
																
																var linha = item;
																if(linha.getItemProperty('CLIENTE').getValue()) {
																	combo.setValue(linha.getItemProperty('CLIENTE').getValue());
																}
																
																
																combo.addValueChangeListener(new Property.ValueChangeListener() {
																		valueChange: function(event) {
																			setUsuario(linha.getItemProperty('CHAVE_DESPESA_COMBUSTIVEL').getValue().longValue(),
																		   	event.getProperty().getValue());
																		},
																		hashCode: function() {
																			return combo.hashCode();
																		}
																	});
																
																return combo;
															}
														]]>
													</scriptColumnGenerator>
												</generated>
												<generated name="OBSERVACOES" caption="Observações" expand-ratio="0.2">
													<scriptColumnGenerator language="JavaScript">
														  importClass(Packages.br.com.davinti.vitruvio.ui.core.VitruvioTheme);
														  importClass(Packages.com.vaadin.ui.VerticalLayout);
	                                          
				                                          function Generator() {
				                                             var com = libService.loadScript('vaadinComponents');
				                                             this.generate = function(itemId, columnId, item, container) {
				                                             	var titulo = item.getItemProperty('OBSERVACOES').getValue();
				                                             	if (titulo.length() >= 20) {
				                                             		titulo = titulo.substring(0,19) + '...';
				                                             	}
				                                                var btn = com.linkButton(titulo, function(){
				                                                   var subContent = new VerticalLayout();
				                                                   subContent.setId('teste');
				                                                   subContent.setMargin(true);
				                                                   var linha = item;
				                                                   
				                                                   var textArea = com.textArea(null, item.getItemProperty('OBSERVACOES').getValue());
				                                                   var instGravar = function run() {
				                                                   		var sqlAtualiza = 'UPDATE controle_despesas_combustiveis SET observacoes = ? ' + 
																						  ' WHERE CHAVE_DESPESA_COMBUSTIVEL = ? '; 	  
																	   	var params = new java.util.ArrayList();
																	   	params.add(textArea.getValue());
																	   	params.add(linha.getItemProperty('CHAVE_DESPESA_COMBUSTIVEL').getValue().longValue());
																	   	vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
																	   	engine.getField('tbCombustivel').refresh();
																        engine.getField('tbTotalCombustivel').refresh();
																        engine.getGlobalVariable('fncSubTotalCombustivel')();
																	   	window.close();
				                                                   };
				                                                   var gravar = com.button('Gravar',instGravar,null);
				                                                   subContent.addComponent(textArea);
				                                                   subContent.addComponent(gravar);
				                                                   var window = com.openWindow(item.getItemProperty('CLIENTE').getValue(), subContent,500,200);
				                                                   
				                                                   textArea.setSizeFull();
				                                                   textArea.addStyleName(com.theme().TEXTAREA_BORDERLESS);
				                                                   window.setModal(true);
				                                                });
				                                                btn.setDescription(item.getItemProperty('OBSERVACOES').getValue());
				                                                var container = com.horizontalLayout([btn]);
				                                                container.setSpacing(false);
				                                                return container;
				                                             }
				                                          }
				                                          var script = new Generator();
													</scriptColumnGenerator>
												</generated>
												<generated name="COMBUSTIVEL" caption="Combustível" cache="false" expand-ratio="0.15" >
													<scriptColumnGenerator language="JavaScript">
														<![CDATA[
															importClass(Packages.com.vaadin.ui.ComboBox);
															importClass(Packages.br.com.davinti.base.vaadin.components.data.container.ContainerUtils);
															importClass(Packages.com.vaadin.data.Property);
															
															var setUsuario = function(chave, cliente) {
																var sqlAtualiza = "UPDATE controle_despesas_combustiveis SET chave_combustivel = ? "+
																		  " WHERE CHAVE_DESPESA_COMBUSTIVEL = ? ";
																var sql = "Select codigo from combustivel where descricao = '" + cliente + "'";
													         	var db = libService.loadScript('db');
																var dbVitruvio = new db('vitruvio');
																var row = dbVitruvio.queryRow(sql);		  
																var params = new java.util.ArrayList();
																params.add(row.codigo);
																params.add(chave);
																vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
															};
															
															function generate(itemId, columnId, item, container) {
																
																var sql = "Select codigo, descricao from combustivel";
																
																var ds = vQueryService.executeQuery('vitruvio', sql);
																
																if(ds == null){
																	return null;
																}
																
																var map = new java.util.LinkedHashMap();
																
																while(ds.next()) {
																	map.put(ds.getString('DESCRICAO'), ds.getString('DESCRICAO'));
																}
																
																var combo = new ComboBox();
																combo.setWidth("100%");
																ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
																
																var linha = item;
																if(linha.getItemProperty('COMBUSTIVEL').getValue()) {
																	combo.setValue(linha.getItemProperty('COMBUSTIVEL').getValue());
																}
																
																
																combo.addValueChangeListener(new Property.ValueChangeListener() {
																		valueChange: function(event) {
																			setUsuario(linha.getItemProperty('CHAVE_DESPESA_COMBUSTIVEL').getValue().longValue(),
																		   	event.getProperty().getValue());
																		},
																		hashCode: function() {
																			return combo.hashCode();
																		}
																	});
																
																return combo;
															}
														]]>
													</scriptColumnGenerator>
												</generated>
												<column name="LITROS" caption="Litros" expand-ratio="0.05" commitOnValueChange="true" commitOnEnter="true" editable="true" align="RIGHT" decimalSeparator="," />
												<column name="VALOR_LITRO" caption="Vlr. litro" expand-ratio="0.05" commitOnValueChange="true" commitOnEnter="true" editable="true" align="RIGHT" decimalSeparator=","/>
												<column name="TOTAL_COMBUSTIVEL" format="###0.00" caption="Total" expand-ratio="0.05" align="RIGHT" decimalSeparator=","/>
												<column name="KM_INICIAL" format="#.##0,00" caption="Km inicial" expand-ratio="0.05" commitOnEnter="true" commitOnValueChange="true" editable="true" align="RIGHT" decimalSeparator=","/>
												<column name="KM_FINAL" format="#.##0,00" caption="Km final" expand-ratio="0.05" commitOnValueChange="true" commitOnEnter="true" editable="true" align="RIGHT" decimalSeparator=","/>
												<column name="KM_RODADO" format="###0.00" caption="Km Rodado" expand-ratio="0.05" align="RIGHT" decimalSeparator="," />
												<column name="MEDIA_CONSUMO" format="###0.00" caption="Média consumo" expand-ratio="0.05" align="RIGHT" decimalSeparator=","  />
											</columns>
											<events>
												<itemChange>
													<script language="JavaScript">
														<![CDATA[
															function onChange(event) {
																var db = libService.loadScript('db');
																var dbVitruvio = new db('vitruvio');
																dbVitruvio.transaction(function() {
																   //if (event.isChanged('DATA')) {
																	   var sqlAtualiza = "UPDATE controle_despesas_combustiveis SET data = :data, litros = :litros, valor_litro = :valor_litro, total_combustivel = :total_combustivel, km_inicial = :km_inicial, km_final = :km_final, km_rodado = :km_rodado, media_consumo = :media_consumo" + 
																			  " WHERE CHAVE_DESPESA_COMBUSTIVEL = :chave";
																   //}
																   this.update(sqlAtualiza, {
																		chave: Number(event.getItemId()),
																		data: event.getField('DATA').getValue(),
																		litros: event.getField('LITROS').getConvertedValue(),
																		valor_litro: event.getField('VALOR_LITRO').getConvertedValue(),
																		total_combustivel: event.getField('LITROS').getConvertedValue() * event.getField('VALOR_LITRO').getConvertedValue(),
																		km_inicial: event.getField('KM_INICIAL').getConvertedValue(),
																		km_final: event.getField('KM_FINAL').getConvertedValue(),
																		km_rodado: event.getField('KM_FINAL').getConvertedValue() - event.getField('KM_INICIAL').getConvertedValue(),
																		media_consumo: (event.getField('KM_FINAL').getConvertedValue() - event.getField('KM_INICIAL').getConvertedValue()) / event.getField('LITROS').getConvertedValue()
																   });
														        });
														        engine.getField('tbCombustivel').refresh();
																engine.getGlobalVariable('fncSubTotalCombustivel')();
																engine.getField('tbTotalCombustivel').refresh();
																event.commit();	
															}
														]]>
													</script>
												</itemChange>
											</events>
										</DBTable>
										<DBTable id="tbTotalCombustivel" type="string" width="100%" expandRatio="0.25" rows="10" selectable="false" exportXLS="true" editable="false" >
											<datasource>
												<sqlBuilderDataSource connection-key="vitruvio" language="JavaScript">
													<![CDATA[
														function buildSQL(params) {
															var sql = 	"Select c.descricao, " +
																		"sum(cdc.litros) litros, " +
																		"sum(cdc.total_combustivel) total " +
																		"from combustivel c inner join controle_despesas_combustiveis cdc on c.codigo = cdc.chave_combustivel " +
																		"where 1=2 " +
																		"group by c.descricao"; 
															if (engine) {
																sql = 	"Select c.descricao, " +
																		"sum(cdc.litros) litros, " +
																		"replace(replace(replace(to_char(sum(cdc.total_combustivel), '9999999999D99'),',','-' ),'.',','),'-','.') total " +
																		"from combustivel c inner join controle_despesas_combustiveis cdc on c.codigo = cdc.chave_combustivel " +
																		"where cdc.data between '" + engine.getField('dataInicioCombustivel') + "' and '" + engine.getField('dataFinalCombustivel') + "'";
																		if (engine.getField('ftPlacaCombustivel').getValue()) {
																			sql += " and cdc.chave_veiculo = " + engine.getField('ftPlacaCombustivel').getValue();
																		}
																		if (engine.getField('ftCombustivel').getValue()) {
																			sql += " and cdc.chave_combustivel = " + engine.getField('ftCombustivel').getValue();
																		}
																		if (engine.getField('ftClienteCombustivel').getValue()) {
																			sql += " and cdc.chave_cliente = " + engine.getField('ftClienteCombustivel').getValue();
																		}
																		sql += " group by c.descricao ";
																		sql += "union " +
																		"Select 'TOTAL' descricao, " +
																		"sum(cdc.litros) litros, " +
																		"replace(replace(replace(to_char(sum(cdc.total_combustivel), '9999999999D99'),',','-' ),'.',','),'-','.') total " +
																		"from combustivel c inner join controle_despesas_combustiveis cdc on c.codigo = cdc.chave_combustivel " +
																		"where cdc.data between '" + engine.getField('dataInicioCombustivel') + "' and '" + engine.getField('dataFinalCombustivel') + "'";
																		if (engine.getField('ftPlacaCombustivel').getValue()) {
																			sql += " and cdc.chave_veiculo = " + engine.getField('ftPlacaCombustivel').getValue();
																		}
																		if (engine.getField('ftCombustivel').getValue()) {
																			sql += " and cdc.chave_combustivel = " + engine.getField('ftCombustivel').getValue();
																		}
																		if (engine.getField('ftClienteCombustivel').getValue()) {
																			sql += " and cdc.chave_cliente = " + engine.getField('ftClienteCombustivel').getValue();
																		}
																		sql += " order by 1";
															}
															return sql;
														}
													]]>
												</sqlBuilderDataSource>
											</datasource>
											<key-field>DESCRICAO</key-field>
											<columns>
												<column name="DESCRICAO" caption="Combustível" expand-ratio="1"/>
												<column name="LITROS" caption="Litros" expand-ratio="0.2"/>
												<column name="TOTAL" caption="Total" expand-ratio="0.3" />
											</columns>
										</DBTable>
									</HorizontalLayout>
								</VerticalLayout>
							</Panel>
		         		</VerticalLayout>
		         	</Tab> 
	         	</TabLayout>
         	</VerticalLayout>
      	</components>

   	</form>
</panel-form>