<?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>Créditos</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('placa')["setValue(java.lang.Object)"](null);
   				engine.getField('funcionario')["setValue(java.lang.Object)"](null);
   				engine.getField('valorFrete')['setValue(java.lang.String)'](null);
   				engine.getField('valorImposto')['setValue(java.lang.String)'](null);
   				engine.getField('valorLiquido')['setValue(java.lang.String)'](null);
   				engine.getField('tipoFrete')["setValue(java.lang.Object)"](null);
   				engine.getField('cte')['setValue(java.lang.String)'](null);
   				/*engine.getField('ufOrigem')["setValue(java.lang.Object)"](null);*/
   				engine.getField('ufDestino')["setValue(java.lang.Object)"](null);
   				engine.getField('placaCarreta')["setValue(java.lang.Object)"](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(ccf.valor_frete), '9999999999D99'),',','-' ),'.',','),'-','.') total_frete, " +
			    			"replace(replace(replace(to_char(sum(ccf.valor_imposto), '9999999999D99'),',','-' ),'.',','),'-','.') total_imposto, " +
			    			"replace(replace(replace(to_char(sum(ccf.valor_liquido), '9999999999D99'),',','-' ),'.',','),'-','.') total_liquido " +
			    			"from controle_receitas_fretes ccf where ccf.data between '" + engine.getField('dataInicio') + "' and '" + engine.getField('dataFinal') + "'";
			    			if (engine.getField('ftFuncionario').getValue()) {
								sql +=  " and ccf.chave_funcionario = " + engine.getField('ftFuncionario').getValue();
							}
							if (engine.getField('ftPlaca').getValue()) {
								sql +=  " and ccf.chave_veiculo = " + engine.getField('ftPlaca').getValue();
							}
                     if (engine.getField('ftPlacaCarreta').getCaptionValue()) {
                        sql +=  " and ccf.placa_carreta = '" + engine.getField('ftPlacaCarreta').getCaptionValue() + "'";
                     }
                     if (engine.getField('ftClientes').getValue() && engine.getField('ftClientes').getValue() != '[]') {
                        sql +=  " and ccf.chave_cliente in (" + engine.getField('ftClientes').getValue().toString().replace('[','').replace(']','') + ")";
                     }
							/*if (engine.getField('ftCliente').getValue()) {
								sql +=  " and ccf.chave_cliente = " + engine.getField('ftCliente').getValue();
							}*/
							if (engine.getField('ftFrotaTerceiro').getValue() == 'F') {
								sql +=  " and ccf.frota_terceiro = 'F'";
							}
							if (engine.getField('ftFrotaTerceiro').getValue() == 'T') {
								sql +=  " and ccf.frota_terceiro = 'T'";
							}
                     
                     if (engine.getField('ftCaminhaoCarreta').getValue() == 'C') {
                        sql +=  " and ccf.caminhao_carreta = 'C'";
                     }
                     if (engine.getField('ftCaminhaoCarreta').getValue() == 'T') {
                        sql +=  " and ccf.caminhao_carreta = 'T'";
                     }
                     if (engine.getField('ftUfOrigem').getValue()) {
                        sql +=  " and ccf.uf_origem = '" + engine.getField('ftUfOrigem').getValue() + "'";
                     }
							if (engine.getField('ftUfDestino').getValue()) {
								sql +=  " and ccf.uf_destino = '" + engine.getField('ftUfDestino').getValue() + "'";
							}
			    vitruvio.query(sql).each(function (r) {
		            if (r.total_frete) {
		            	engine.getLabel('sub').setValue('<b><font color="blue">Subtotal Frete R$ ' + r.total_frete + '</font></b>');
		            } else {
		            	engine.getLabel('sub').setValue('<b><font color="blue">Subtotal Frete R$ 0,00</font></b>');
		            }
		            if (r.total_imposto) {
		            	engine.getLabel('subImposto').setValue('<b><font color="red">Subtotal Impostos R$ ' + r.total_imposto + '</font></b>');
		            } else {
		            	engine.getLabel('subImposto').setValue('<b><font color="red">Subtotal Impostos R$ 0,00</font></b>');
		            }
		            if (r.total_liquido) {
		            	engine.getLabel('subLiquido').setValue('<b><font color="green">Subtotal (Frete - Impostos) R$ ' + r.total_liquido + '</font></b>');
		            } else {
		            	engine.getLabel('subLiquido').setValue('<b><font color="green">Subtotal (Frete - Impostos) R$ 0,00</font></b>');
		            }
		         }); 
			}
         
         function fncLancFrete(){
            var funcionario = engine.getField('funcionario').getValue();
            var sql = "Select coalesce(nao_carregar_frete,false) as nao_carregar_frete from funcionario where codigo = :ParFuncionario";   
            var db = libService.loadScript('db');
            var dbVitruvio = new db('vitruvio');
            var row = dbVitruvio.queryRow(sql, {ParFuncionario: funcionario});
            
            if (row) {
               //Enable/disable componente frete
               if (row.nao_carregar_frete == false) {
                  engine.getField('valorFrete').setEnabled(false);
                  engine.getField('origemFrete').setRequired(true);
                  engine.getField('origemFrete').setVisible(true);
               } else {
                  engine.getField('valorFrete').setEnabled(true);
                  engine.getField('origemFrete').setRequired(false);
                  engine.getField('origemFrete').setVisible(false);
               }
            }
         }
			
			function run() {
				engine.getField('valorImposto').setEnabled(false);
				engine.getField('valorLiquido').setEnabled(false);
				engine.setGlobalVariable('abertura',1);
				engine.getField('frotaTerceiro').setValue('F');
				engine.getField('ftFrotaTerceiro').setValue('A');
            engine.getField('caminhaoCarreta').setValue('C');
            engine.getField('ftCaminhaoCarreta').setValue('A');
				
				var d = new java.util.Date();
				engine.setGlobalVariable('fncLimpaCampos', fncLimpaCampos);
				engine.setGlobalVariable('fncSubTotal', fncSubTotal);
				engine.getField('dataInicio').setValue(d);
				engine.getField('dataFinal').setValue(d);
				engine.getField('tbLancamentos').refresh();
				engine.getGlobalVariable('fncSubTotal')();
            engine.setGlobalVariable('fncLancFrete', fncLancFrete);
				
				// 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));
			}
		]]>
	  	</initScript>

      	<components>
      		<VerticalLayout margin="true" width="100%" height="100%" >
	      		<TabLayout align="BOTTOM_LEFT" id="credito" compact="true" width="100%" height="100%" >
	      			<Tab caption="Fretes">
						<VerticalLayout spacing="true" width="100%" height="100%">
						   <Panel caption=" " width="100%" expandRatio="0.5" align="TOP_LEFT" height="100%">
								<VerticalLayout width="100%" spacing="true">
									<HorizontalLayout width="100%" spacing="true" height="100%" margin="true">
								      <ImageWidget id="img1" height="46" width="68" align="TOP_LEFT">
							      		<image>
							      			<base64 extension="jpg">
							      				<![CDATA[
							      					,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA8AAD/4QMraHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjMtYzAxMSA2Ni4xNDU2NjEsIDIwMTIvMDIvMDYtMTQ6NTY6MjcgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzYgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkVFQTIxQTExOTRFODExRThCQTY5OUIwNzFEMDlCNzIxIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkVFQTIxQTEyOTRFODExRThCQTY5OUIwNzFEMDlCNzIxIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6RUVBMjFBMEY5NEU4MTFFOEJBNjk5QjA3MUQwOUI3MjEiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6RUVBMjFBMTA5NEU4MTFFOEJBNjk5QjA3MUQwOUI3MjEiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7/7gAOQWRvYmUAZMAAAAAB/9sAhAAGBAQEBQQGBQUGCQYFBgkLCAYGCAsMCgoLCgoMEAwMDAwMDBAMDg8QDw4MExMUFBMTHBsbGxwfHx8fHx8fHx8fAQcHBw0MDRgQEBgaFREVGh8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx//wAARCAA5AE0DAREAAhEBAxEB/8QAowAAAgIDAQEAAAAAAAAAAAAAAAYBCAQFBwMCAQACAwEBAQAAAAAAAAAAAAAABQEEBgMCBxAAAgECBAMCCQkJAAAAAAAAAQIDAAQREgUGITEHUhNBUWGRoSIyQhRxgbFyk+M0VReSorLC0jNTlCYRAAIBAwEEBgYLAQAAAAAAAAABAhEDBAUhMVESQWFxgaEVkdHhIkITscEyUmJykjNjBhbw/9oADAMBAAIRAxEAPwC1NAEZ07Q89FCKhnTtDz1NAqGdO0PPRQKhnTtDz0UCoZ07Q89FAqTUEhQAUAFABQBVm+mlN5MS5JLsSSePOt3FKiPlk23J9p495J2jUnmpttB29qusi6a2jmaO2heTPHG0gaRACsWI95seFcL+RG3StNr/AOZbxcS5eryp7E+iu3gapmmVir5ldSQyngQRwIIrvsKrqiBLJj7RqSKljNhTSSbN0mSaQu5gALucScCQOJ8grG5ypelTifRtLk3jQb4G/wA6doeeqlC9UmgkKACgCq95+Lm+ufprdx3I+Vz3vtPCvR5Ou7Tvk1Pbdra6PrKade2NlJBJp74RZrliuFyXBxZR8h51nsqHJcbnDmjKVa9XA12DdV2yo258koxa5d3vfeEPfVvuOPcEsmvwpFeTKCrRKBE6L6uZCOflx401wpW3bpbexCHU43lebvKknw3C+KuC8cd33Vwu1trW6yMIfhGkKAnAtnIxw5cqX4kV824+nmHGoTfybKrs5X9IoLNKpBDEEcqv0FFWWE6dbmGu7chaR819aYQXWJxYkD1HOJY+svMnm2NZHUcb5Vx0+y9qPoOkZvz7Kr9qOx+vvGiqI0CgCq95+Lm+ufprdx3I+Vz3vtPCvR5Ogbd1DY97bTd/Y3Njfw6ZNDefBlDFJCuUM694S3eHy/PjSjIt34tUalFzVK76+o0GJdxZxdYyjNW2ny7muO3pNFvXc1prlzZLZQyRWWnwfD25nbNK44Es/E8eHjq3h4ztJ8z96Trs3FHUcyN+UeVNRgqKu/vF0VcFo37xH/L7Ubx2kg80lL8P9y7+ZDfUf2bP5X9In0wFI0dPd0PoG4IZHbCyuSIbtSeARj7fI+wePo8NUs/G+bba+JbUMtKzXYvJ/DLY/X3Fh8Rhj4Kx59DCgDhGodJ95C8m7u3jmjLErKsqBSD9cqfRWqhqtmi2tdxg7mhZKk6JNdpjL0q3qwBWzRgeRE0R/mr35pY4+DPC0PK+6vSj4fphvBGyvbRo3iM8IP8AFUrUrL6X6GQ9FyV0L9SI/TPdn+CH/Yh/qo8ys8X6GR5NkcF+pAvTLdhYAwwgEjE/EQ8P3qPMrPF+hh5NkcF+pDtuLptqOo7e0e00+7gnudKiaKVScqsXOY5WGbkeHGluPqMYXJuSaU2OszR53LVuMJJu2qClL0j3kiFlhhlYe4kyZj+1lHpq+tVsvpfoFMtByUtyfeK1xYXlhqLWd5E0NzC+WSNuYNX4zU480XVMVztStz5ZKkky0fufNWGPqHQTUEnGesut6m2sppZzxWEKLIi8llZhiX5ccPZ+Y1pdHsxVvn+J+BjP7FkTd1W9qglXt6/qNP0t1S+tt3WlvFKRDdExzx4nKwwJHDxirGpWoysttbUU9FvzhkxSeyWxj1rnSa41jVLjULnWW7ydiwTucQq+BRjJyA4Urs6qrcFFQ3dfsHmToLvXHOVza+r2mB+hq/nJ+w+8rp53+Dx9hw/zP8nh7Q/Q1fzk/YfeUed/g8fYH+Z/k8PabDXdIl2Z06u4NOuXN08i99dgBGPeMFOGGJUZeHPGuVi8snJTktnDsLGVjvCwpKD96u/tZxq3vLqCeOeGVkmjYMjqSGDA4ggitG4pqjWwxsZyi6p0aOra1tTW956Zt/WIoo4L1oSl88xKMwB9STALyOBbgPepDZyoY05wbrGuw1eTg3cy3auJJSp71fB/X3nUcPVw8mFIjUk0AaHdOy9F3JHEL5XSaH+3cRELIF7JJDAjHjyq3i5s7NeXc+goZ2m2slLn3rpW8xNr9OtA29dG8tjLPdZcqyzMDlB55VUKOPlrpk6jcvLldEuo44WkWceXNGrl1jTVAahQAUAYup6ZY6nYy2N7EJraYYOh9BB8BHgNdLVyUJKUdjRyvWY3YOElWLEm26L7bhvVme4uJrdSCLdygxIOJDMqg4HyYfLTOWs3XGlEnxEkP65YUqtya4D9FFHFGkUShI41CoijBVUDAAAcgKUtturH8YpKi3H1UEhQAUAFABQAUAFABQAUAFABQB//2Q==
							      				]]>
							      			</base64>
							      		</image>
							      	</ImageWidget>
							      	<DateField type="date" id="dataLancamento" align="TOP_LEFT" caption="Data" width="100%" expandRatio="0.8" required="true" resolution="DAY" description="Informe a data do lançamento" format="dd/MM/yyyy" >
							      	</DateField>
                              
                              <OptionGroup type="string" id="frotaTerceiro" disposition="vertical" required="true" width="100%" expandRatio="0.5" >
                                 <entry value="Frota" key="F"/>
                                 <entry value="Terceiro" key="T"/>
                              </OptionGroup>
                              
                              <OptionGroup type="string" id="caminhaoCarreta" disposition="vertical" required="true" width="75%" expandRatio="0.5">
                                 <entry value="Caminhão" key="C"/>
                                 <entry value="Carreta" key="T"/>
                                 <events>
                                    <valueChange>
                                       <script language="JavaScript">
                                          <![CDATA[
                                             function run() {
                                                var keyValue = engine.getField('caminhaoCarreta').getValue();
                                                if (keyValue=="T") {                                          
                                                   engine.getField('placaCarreta').setVisible(true); 
                                                   engine.getField('placaCarreta').setRequired(true);                                                                                                                                                               
                                                } else {
                                                   engine.getField('placaCarreta').setVisible(false);  
                                                   engine.getField('placaCarreta').setRequired(false); 
                                                   engine.getField('placaCarreta').setValue(null);
                                                } 
                                             }                                    
                                          ]]>
                                       </script>
                                    </valueChange>
                                 </events>
                              </OptionGroup>
                              
							      	<DBComboBox type="string" id="placa" width="100%" required="true" expandRatio="1" align="TOP_LEFT" caption="Placa">
							      		<datasource>
							      			<freeQuery connection-key="vitruvio">
							      				<![CDATA[
							      					Select * from veiculo where inativo is false order by PLACA 
							      				]]>
							      			</freeQuery>
							      		</datasource>
							      		<key-field>CODIGO</key-field>
							      		<caption-field>PLACA</caption-field>
							      		<events>
							      			<valueChange>
							      				<script language="JavaScript">
							      					<![CDATA[
							      						function run() {
															   var sql = "Select placa_carreta from veiculo where codigo = " + engine.getField('placa').getValue();
												         	var db = libService.loadScript('db');
   															var dbVitruvio = new db('vitruvio');
   															var row = dbVitruvio.queryRow(sql);
   															if (row && row.placa_carreta) {		  
   																engine.getField('placaCarreta').setValue(row.placa_carreta);
   															}
							      						}
							      					]]>
							      				</script>
							      			</valueChange>
							      		</events>
							      	</DBComboBox>
                              
                              <DBComboBox type="string" id="placaCarreta" width="100%" expandRatio="1" align="TOP_LEFT" caption="Placa carreta" required="true">
                                 <datasource>
                                    <freeQuery connection-key="vitruvio">
                                       <![CDATA[
                                          Select * from veiculo where placa_carreta is not null order by placa_carreta
                                       ]]>
                                    </freeQuery>
                                 </datasource>
                                 <key-field>PLACA_CARRETA</key-field>
                                 <caption-field>PLACA_CARRETA</caption-field>
                              </DBComboBox>
							      	
							      	<DBComboBox type="string" id="funcionario" required="true" width="100%" expandRatio="1" align="TOP_LEFT" caption="Funcionário">
							      		<datasource>
							      			<freeQuery connection-key="vitruvio">
							      				<![CDATA[
							      					Select * from funcionario where inativo is false order by nome
							      				]]>
							      			</freeQuery>
							      		</datasource>
							      		<key-field>CODIGO</key-field>
							      		<caption-field>NOME</caption-field>
                                 <events>
                                    <valueChange>
                                       <script language="JavaScript">
                                          <![CDATA[
                                             function run() {
                                                var fncLancFrete = engine.getGlobalVariable('fncLancFrete');
                                                
                                                if(fncLancFrete){
                                                   engine.getGlobalVariable('fncLancFrete')();
                                                }
                                             }
                                          ]]>
                                       </script>
                                    </valueChange>
                                 </events>
							      	</DBComboBox>
                              
							      	<DBComboBox type="string" id="cliente" required="true" width="100%" expandRatio="1" align="TOP_LEFT" caption="Cliente">
							      		<datasource>
							      			<freeQuery connection-key="vitruvio">
							      				<![CDATA[
							      					Select * from clientes where inativo is false order by nome
							      				]]>
							      			</freeQuery>
							      		</datasource>
							      		<key-field>CODIGO</key-field>
							      		<caption-field>NOME</caption-field>
                                 <events>
                                    <valueChange>
                                       <script language="JavaScript">
                                          <![CDATA[
                                             function run(){
                                                var cliente = engine.getField('cliente').getValue();
                                                var sql = "Select count(*) as contador from clientes_frete where chave_cliente = :ParCliente";   
                                                var db = libService.loadScript('db');
                                                var dbVitruvio = new db('vitruvio');
                                                var row = dbVitruvio.queryRow(sql, {ParCliente: cliente});
                                                
                                                if (row) {
                                                   if (row.contador == 0) {
                                                      engine.getField('valorFrete').setEnabled(true);
                                                      engine.getField('origemFrete').setRequired(false);
                                                      engine.getField('origemFrete').setVisible(false);
                                                   }else{
                                                      var fncLancFrete = engine.getGlobalVariable('fncLancFrete');
                                                      if(fncLancFrete){
                                                         engine.getGlobalVariable('fncLancFrete')();
                                                      }
                                                   }
                                                }
                                             }
                                          ]]>
                                       </script>
                                    </valueChange>
                                 </events>
							      	</DBComboBox>
							      </HorizontalLayout>
                              
								   <HorizontalLayout width="100%" spacing="true" margin="true">
                              <NumericField type="number" id="cte" caption="CTE" />
                              
                              <DBComboBox type="string" id="tipoFrete" required="true" width="100%" expandRatio="0.5" align="TOP_LEFT" caption="Tipo de frete">
                                 <datasource>
                                    <freeQuery connection-key="vitruvio">
                                       <![CDATA[
                                          Select * from tipo_frete
                                       ]]>
                                    </freeQuery>
                                 </datasource>
                                 <key-field>CODIGO</key-field>
                                 <caption-field>DESCRICAO</caption-field>
                              </DBComboBox>
                              
                              <DBComboBox type="number" id="origemFrete" width="100%" expandRatio="0.5" align="TOP_LEFT" caption="Lanc. Frete" required="false">
                                 <datasource>
                                    <freeQuery connection-key="vitruvio">
                                       <![CDATA[
                                          select chave_frete, descricao||' - R$ '||valor_frete as descricao 
                                            from clientes_frete
                                           where chave_cliente = ${ParCodigo}
                                           order by descricao
                                       ]]>
                                    </freeQuery>
                                 </datasource>
                                 <key-field>CHAVE_FRETE</key-field>
                                 <caption-field>DESCRICAO</caption-field>
                                 <bind>
                                    <parameter value-type="number" defaultValue="-1" parameterName="ParCodigo" field-ref="cliente"/>
                                 </bind>
                                 <events>
                                    <valueChange>
                                       <script language="JavaScript">
                                          <![CDATA[
                                             function run() {
                                                var db = libService.loadScript('db');
                                                var dbVitruvio = new db('vitruvio');
                                                
                                                var sql = "Select valor_frete from clientes_frete ";
                                                sql +=    "where chave_frete = " + engine.getField('origemFrete').getValue();   
                                                
                                                var row = dbVitruvio.queryRow(sql);
                                                
                                                if (row) {
                                                   //Atribui o valor do frete no componente
                                                   if (row.valor_frete > 0) {
                                                      engine.getField('valorFrete').setValue(row.valor_frete);
                                                   } else {
                                                      engine.getField('valorFrete').setValue(0);
                                                   }
                                                }
                                             }
                                          ]]>
                                       </script>
                                    </valueChange>
                                 </events>
                              </DBComboBox>
                              
										<DBComboBox type="string" id="ufDestino" caption="UF Origem-Destino" width="100%" expandRatio=".6" >
											<datasource>
												<freeQuery connection-key="vitruvio">
													<![CDATA[
														Select cp.chave_praca, ori.nome ||' - '|| dest.nome as percurso
                                          from clientes_praca cp, estados ori, estados dest  
                                          where cp.chave_estado_origem = ori.chave_estado
                                            and cp.chave_estado = dest.chave_estado
                                            and cp.chave_cliente = ${ParCodigo}
                                           order by 2
													]]>
												</freeQuery>
											</datasource>
											<key-field>CHAVE_PRACA</key-field>
											<caption-field>PERCURSO</caption-field>
											<bind>
												<parameter value-type="number" defaultValue="-1" parameterName="ParCodigo" field-ref="cliente"/>
											</bind>
											<events>
												<valueChange>
													<script language="JavaScript">
														<![CDATA[
															function run() {
                                                var db = libService.loadScript('db');
                                                var dbVitruvio = new db('vitruvio');
																
                                                var pImpostos;
                                                
																var sql = "Select percentual_impostos, chave_estado, chave_estado_origem from clientes_praca ";
                                                sql +=    "where chave_praca = " + engine.getField('ufDestino').getValue();
																
                                                var row = dbVitruvio.queryRow(sql);
                                                
                                                if (row) {
                                                   engine.setGlobalVariable('praca',row.chave_estado);
                                                   engine.setGlobalVariable('pracaOrigem',row.chave_estado_origem);
                                                   
                                                   //Atribui o % do imposto
   																if (row.percentual_impostos > 0) {
   																	pImpostos = row.percentual_impostos/100;
   																} else {
   																	pImpostos = 0;
   																}
                                                }
                                                
																var impostos = engine.getField('valorFrete').getConvertedValue() * pImpostos;
																var liquido = engine.getField('valorFrete').getConvertedValue() - impostos;
																engine.getField('valorImposto').setValue(impostos);
																engine.getField('valorLiquido').setValue(liquido);
															}
														]]>
													</script>
												</valueChange>
											</events>
										</DBComboBox>
                              
                              <DecimalField type="decimal" id="valorFrete" required="true" immediate="true" caption="Valor frete (R$)" format="#,##0.00" description="Valor frete" width="100%" expandRatio=".6" >
                                <events>
                                   <valueChange>
                                      <script language="JavaScript">
                                         <![CDATA[
                                            function run() {
                                               var pImpostos;
                                               var sql = "Select percentual_impostos from clientes_praca where chave_praca = " + engine.getField('ufDestino').getValue();
                                               var db = libService.loadScript('db');
                                               var dbVitruvio = new db('vitruvio');
                                               var row = dbVitruvio.queryRow(sql);
                                               if (row && row.percentual_impostos) {        
                                               pImpostos = row.percentual_impostos/100;
                                               } else {
                                                 pImpostos = 0;
                                               }
                                               var impostos = engine.getField('valorFrete').getConvertedValue() * pImpostos;
                                               var liquido = engine.getField('valorFrete').getConvertedValue() - impostos;
                                               engine.getField('valorImposto').setValue(impostos);
                                               engine.getField('valorLiquido').setValue(liquido);
                                            }
                                          ]]>
                                       </script>
                                    </valueChange>
                                 </events>
                              </DecimalField>
                              
										<DecimalField type="decimal" id="valorImposto" caption="Valor impostos (R$)" format="#,##0.00" description="Valor impostos" width="100%" expandRatio=".6" />
										<DecimalField type="decimal" id="valorLiquido" caption="Valor Líquido (Frete - Impostos) (R$)" format="#,##0.00" description="Valor frete menos o valor dos impostos" width="100%" expandRatio=".6" align="BOTTOM_LEFT"/>
										<ButtonWidget id="btnGravar" caption="Gravar" description="Grava o lançamento" width="100" expandRatio=".3" >
											<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_receitas_fretes (chave_receita_frete,data,chave_cliente,chave_veiculo,chave_funcionario,valor_frete,valor_imposto,valor_liquido,chave_tipo_frete,cte,frota_terceiro,caminhao_carreta,uf_origem,uf_destino,chave_forma_pagamento,placa_carreta,usuario) " +
																		" values (" + dbVitruvio.getSequenceNextValSql('controle_rec_fr_seq') + ",:data,:chave_cliente,:chave_veiculo,:chave_funcionario,:valor_frete,:valor_imposto,:valor_liquido,:tipo_frete,:cte,:frota_terceiro,:caminhao_carreta,:uf_origem,:uf_destino,0,:placa_carreta,:usuario)";
															   	this.update(sql, {
																	data: engine.getField('dataLancamento').getValue(),
																	chave_cliente: Number(engine.getField('cliente').getValue()),
																	chave_veiculo: Number(engine.getField('placa').getValue()),
																	chave_funcionario: Number(engine.getField('funcionario').getValue()),
																	valor_frete: engine.getField('valorFrete').getConvertedValue(),
																	valor_imposto: engine.getField('valorImposto').getConvertedValue(),
																	valor_liquido: engine.getField('valorLiquido').getConvertedValue(),
																	tipo_frete: engine.getField('tipoFrete').getValue(),
																	cte: Number(engine.getField('cte').getValue()),
																	frota_terceiro: String(engine.getField('frotaTerceiro').getValue()),
                                                   caminhao_carreta: String(engine.getField('caminhaoCarreta').getValue()),
                                                   uf_origem: Number(engine.getGlobalVariable('pracaOrigem')),
																	uf_destino: Number(engine.getGlobalVariable('praca')),
																	placa_carreta: engine.getField('placaCarreta').getValue(),
                                                   usuario: engine.getLoggedUser().getLogin()
															   });
													        });
													        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" height="100%" expandRatio="1" >
								<VerticalLayout width="100%" spacing="true" align="TOP_LEFT" height="100%" >
                           <HorizontalLayout width="100%" spacing="true" height="100%" expandRatio="0.6">
                              <DBTwinColSelect type="string" id="ftClientes" allowNullSelection="true" multivalue="true" caption="Clientes" rows="5" width="100%" expandRatio="0.5" align="TOP_LEFT">
                                    <datasource>
                                       <freeQuery connection-key="vitruvio">
                                          <![CDATA[
                                             Select codigo, substr(nome,1,15)::varchar as nome from clientes order by nome
                                          ]]>
                                       </freeQuery>
                                    </datasource>
                                    <key-field>CODIGO</key-field>
                                    <caption-field>NOME</caption-field>
                                 </DBTwinColSelect>
                              <VerticalLayout width="100%" spacing="true" expandRatio="1" 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="1" description="Data iniacial da exibição" format="dd/MM/yyyy" />
   										<DateField type="date" id="dataFinal" caption="Data final" align="TOP_LEFT" width="100%" expandRatio="1" description="Data final da exibição" format="dd/MM/yyyy" />
   										<DBComboBox type="string" id="ftPlaca" width="100%" expandRatio="1" align="TOP_LEFT" caption="Placa" allowNullSelection="true">
                                    <datasource>
                                       <freeQuery connection-key="vitruvio">
                                          <![CDATA[
                                             Select * from veiculo order by placa
                                          ]]>
                                       </freeQuery>
                                    </datasource>
                                    <key-field>CODIGO</key-field>
                                    <caption-field>PLACA</caption-field>
                                 </DBComboBox>
                                 
                                 <DBComboBox type="string" id="ftPlacaCarreta" width="100%" expandRatio="1" align="TOP_LEFT" caption="Placa Carreta" allowNullSelection="true">
                                    <datasource>
                                       <freeQuery connection-key="vitruvio">
                                          <![CDATA[
                                             select distinct placa_carreta from veiculo where placa_carreta is not null order by placa_carreta
                                          ]]>
                                       </freeQuery>
                                    </datasource>
                                    <key-field>PLACA_CARRETA</key-field>
                                    <caption-field>PLACA_CARRETA</caption-field>
                                 </DBComboBox>
                             </HorizontalLayout>
                             
                             <HorizontalLayout width="100%" margin="false" spacing="true">
								      	<DBComboBox type="string" id="ftFuncionario" width="100%" expandRatio="0.2" align="TOP_LEFT" caption="Funcionário" allowNullSelection="true">
                                    <datasource>
                                       <freeQuery connection-key="vitruvio">
                                          <![CDATA[
                                             Select * from funcionario order by nome
                                          ]]>
                                       </freeQuery>
                                    </datasource>
                                    <key-field>CODIGO</key-field>
                                    <caption-field>NOME</caption-field>
                                 </DBComboBox>
                                 
                                 <DBComboBox type="number" id="ftUfOrigem" caption="UF origem" width="100%" expandRatio="0.1" allowNullSelection="true" align="TOP_LEFT" >
                                    <datasource>
                                       <freeQuery connection-key="vitruvio">
                                          <![CDATA[
                                             Select * from estados order by sigla
                                          ]]>
                                       </freeQuery>
                                    </datasource>
                                    <key-field>CHAVE_ESTADO</key-field>
                                    <caption-field>SIGLA</caption-field>
                                 </DBComboBox>
                                 
                                 <DBComboBox type="number" id="ftUfDestino" caption="UF destino" width="100%" expandRatio="0.1" allowNullSelection="true" align="TOP_LEFT" >
                                    <datasource>
                                       <freeQuery connection-key="vitruvio">
                                          <![CDATA[
                                             Select * from estados order by sigla
                                          ]]>
                                       </freeQuery>
                                    </datasource>
                                    <key-field>CHAVE_ESTADO</key-field>
                                    <caption-field>SIGLA</caption-field>
                                 </DBComboBox>
                                 
                                 <OptionGroup type="string" id="ftFrotaTerceiro" disposition="horizontal" width="100%" expandRatio="0.3" align="MIDDLE_CENTER" caption="Frota">
   											<entry value="Ambos" key="A"/>
   											<entry value="Frota" key="F"/>
   											<entry value="Terceiro" key="T"/>
										   </OptionGroup>
                                 
                                 <OptionGroup type="string" id="ftCaminhaoCarreta" disposition="horizontal" width="100%" expandRatio="0.3" align="MIDDLE_LEFT" caption="Caminhão/Carreta">
                                    <entry value="Ambos" key="A"/>
                                    <entry value="Caminhão" key="C"/>
                                    <entry value="Carreta" key="T"/>
                                 </OptionGroup>
                                 
   										<ButtonWidget id="btnFiltrar" caption="Filtrar" align="BOTTOM_RIGHT" description="Aplica filtro" width="100" >
   											<onClickScript language="JavaScript">
   												<![CDATA[
   													function run() {
   														engine.getField('tbLancamentos').refresh();
   														engine.getGlobalVariable('fncSubTotal')();
   													}
   												]]>
   											</onClickScript>
   										</ButtonWidget>
                                 
   										<ButtonWidget id="btnLimparFiltro" caption="Limpar" align="BOTTOM_RIGHT" 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('ftPlacaCarreta')["setValue(java.lang.Object)"](null);
   														engine.getField('ftClientes')["setValue(java.lang.Object)"](null);
   														engine.getField('ftFrotaTerceiro').setValue('A');
                                             engine.getField('ftCaminhaoCarreta').setValue('2');
                                             engine.getField('ftUfOrigem')["setValue(java.lang.Object)"](null);
   														engine.getField('ftUfDestino')["setValue(java.lang.Object)"](null);
   														engine.getField('tbLancamentos').refresh();
   														engine.getGlobalVariable('fncSubTotal')();
   													}
   												]]>
   											</onClickScript>
   										</ButtonWidget>
									</HorizontalLayout>
                           </VerticalLayout>
                        </HorizontalLayout>
									<HorizontalLayout width="70%" spacing="true" align="TOP_LEFT" height="100%" expandRatio="0.1">
										<Label id="sub" align="BOTTOM_RIGHT" width="100%" expandRatio="1" contentMode="HTML">
											<value>
												
											</value>
										</Label>
										<Label id="subImposto" align="BOTTOM_RIGHT" width="100%" expandRatio="1" contentMode="HTML">
											<value>
												
											</value>
										</Label>
										<Label id="subLiquido" align="BOTTOM_RIGHT" width="100%" expandRatio="1" contentMode="HTML">
											<value>
												
											</value>
										</Label>
									</HorizontalLayout>
									<DBTable id="tbLancamentos" type="number" showRowCount="true" width="100%" rows="6" selectable="false" exportXLS="true" editable="true" height="100%" expandRatio="1">
										<datasource>
											<sqlBuilderDataSource connection-key="vitruvio" language="JavaScript">
												<![CDATA[
													function buildSQL(params) {
														var sql = 	"Select ccf.chave_receita_frete, ccf.data, " +
																	" (select co.nome from clientes co where co.codigo = ccf.chave_cliente) cliente," +
																	" (select cv.placa from veiculo cv where cv.codigo = ccf.chave_veiculo) veiculo," +
																	" (select cf.nome from funcionario cf where cf.codigo = ccf.chave_funcionario) funcionario," +
																	" ccf.cte," +
																	" (select descricao from tipo_frete where codigo = ccf.chave_tipo_frete) tipo_frete," +
																	" ccf.frota_terceiro," +
                                                   " ccf.caminhao_carreta," +
																	" (select e.sigla from estados e where e.chave_estado = ccf.uf_origem) uf_origem," +
																	" (Select e.sigla from estados e where e.chave_estado = ccf.uf_destino) uf_destino," +
																	" replace(replace(replace(to_char(ccf.valor_frete, '9999999999D99'),',','-' ),'.',','),'-','.') valor_frete, " +
																	" replace(replace(replace(to_char(ccf.valor_imposto, '9999999999D99'),',','-' ),'.',','),'-','.') valor_imposto, " +
																	" replace(replace(replace(to_char(ccf.valor_liquido, '9999999999D99'),',','-' ),'.',','),'-','.') valor_liquido, " +
																	" ccf.placa_carreta placa_carreta " +
																	" from controle_receitas_fretes ccf" +
																	" where 1 = 2";
														if (engine) {
															var datainicio = engine.getField('dataInicio').getValue();
															var datafinal = engine.getField('dataFinal').getValue();
															sql = 	"Select ccf.chave_receita_frete, ccf.data, " +
																	" (select co.nome from clientes co where co.codigo = ccf.chave_cliente) cliente," +
																	" (select cv.placa from veiculo cv where cv.codigo = ccf.chave_veiculo) veiculo," +
																	" (select cf.nome from funcionario cf where cf.codigo = ccf.chave_funcionario) funcionario," +
																	" ccf.cte," +
																	" (select descricao from tipo_frete where codigo = ccf.chave_tipo_frete) tipo_frete," +
																	" ccf.frota_terceiro," +
                                                   " ccf.caminhao_carreta," +
																	" (select e.sigla from estados e where e.chave_estado = ccf.uf_origem) uf_origem," +
																	" (Select e.sigla from estados e where e.chave_estado = ccf.uf_destino) uf_destino," +
																	" ccf.valor_frete valor_frete, " +
																	" ccf.valor_imposto valor_imposto, " +
																	" ccf.valor_liquido valor_liquido, " +
																	" ccf.placa_carreta placa_carreta " +
																	" from controle_receitas_fretes ccf where 1 = 1 ";
															if (datainicio && datafinal) {
																	sql += " and ccf.data between '" + engine.getField('dataInicio') + "' and '" + engine.getField('dataFinal') + "'";
															}
															if (engine.getField('ftFuncionario').getValue()) {
																sql +=  " and ccf.chave_funcionario = " + engine.getField('ftFuncionario').getValue();
															}
															if (engine.getField('ftPlaca').getValue()) {
																sql +=  " and ccf.chave_veiculo = " + engine.getField('ftPlaca').getValue();
															}
                                             if (engine.getField('ftPlacaCarreta').getCaptionValue()) {
                                                sql +=  " and ccf.placa_carreta = '" + engine.getField('ftPlacaCarreta').getCaptionValue() +"'";
                                             }
															if (engine.getField('ftClientes').getValue() && engine.getField('ftClientes').getValue() != '[]') {
																sql +=  " and ccf.chave_cliente in (" + engine.getField('ftClientes').getValue().toString().replace('[','').replace(']','') + ")";
															}
															if (engine.getField('ftFrotaTerceiro').getValue() && engine.getField('ftFrotaTerceiro').getValue() == 'F') {
																sql +=  " and ccf.frota_terceiro = 'F'";
															}
															if (engine.getField('ftFrotaTerceiro').getValue() && engine.getField('ftFrotaTerceiro').getValue() == 'T') {
																sql +=  " and ccf.frota_terceiro = 'T'";
															}
                                             if (engine.getField('ftCaminhaoCarreta').getValue() && engine.getField('ftCaminhaoCarreta').getValue() == 'C') {
                                                sql +=  " and ccf.caminhao_carreta = 'C'";
                                             }
                                             if (engine.getField('ftCaminhaoCarreta').getValue() && engine.getField('ftCaminhaoCarreta').getValue() == 'T') {
                                                sql +=  " and ccf.caminhao_carreta = 'T'";
                                             }
                                             if (engine.getField('ftUfOrigem').getValue()) {
                                                sql +=  " and ccf.uf_origem = '" + engine.getField('ftUfOrigem').getValue() + "'";
                                             }
															if (engine.getField('ftUfDestino').getValue()) {
																sql +=  " and ccf.uf_destino = '" + engine.getField('ftUfDestino').getValue() + "'";
															}
															sql += " order by data desc";
														}
														return sql;
													}
												]]>
											</sqlBuilderDataSource>
										</datasource>
										<key-field>chave_receita_frete</key-field>
										<columns>
											<generated name="EXCLUIR" caption="">
												<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 sqlAtualiza = "UPDATE controle_receitas_fretes SET usuario = ?, blindar = ? "+
                                                                                    " WHERE CHAVE_RECEITA_FRETE = ? ";
                                                                 var params = new java.util.ArrayList();
                                                                 params.add(engine.getLoggedUser().getLogin());
                                                                 params.add(1);
                                                                 params.add(idRegistro);
                                                                 vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
                                                            
         																        var sql = 'delete from controle_receitas_fretes where chave_receita_frete = :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" format="dd/MM/yyyy" commitOnValueChange="true" editable="true" expand-ratio="0.15" />
											<generated name="VEICULO" caption="Veículo" 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) {
															if (cliente) {
																var sqlAtualiza = "UPDATE controle_receitas_fretes SET chave_veiculo = ? "+
																		  " WHERE CHAVE_RECEITA_FRETE = ? ";
																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());
															} else {
																MessageBox.show(MessageBox.BoxType.INFO, 'Atenção', 'Tipo de frete não pode ser vazio.');
															}
														};
														
														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_RECEITA_FRETE').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<generated name="PLACA_CARRETA" caption="Placa carreta" 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) {
															if (cliente) {
																var sqlAtualiza = "UPDATE controle_receitas_fretes SET placa_carreta = ? "+
																		  " WHERE CHAVE_RECEITA_FRETE = ? ";
																var params = new java.util.ArrayList();
																params.add(cliente);
																params.add(chave);
																vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
															} else {
																var sqlAtualiza = "UPDATE controle_receitas_fretes SET placa_carreta = null "+
																		  " WHERE CHAVE_RECEITA_FRETE = ? ";
																var params = new java.util.ArrayList();
																params.add(chave);
																vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
															}
														};
														
														function generate(itemId, columnId, item, container) {
															
															var sql = "Select placa_carreta from veiculo where placa_carreta is not null";
															
															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_CARRETA'), ds.getString('PLACA_CARRETA'));
															}
															
															var combo = new ComboBox();
															combo.setWidth("100%");
															ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
															
															var linha = item;
															if(linha.getItemProperty('PLACA_CARRETA').getValue()) {
																combo.setValue(linha.getItemProperty('PLACA_CARRETA').getValue());
															}
															
															
															combo.addValueChangeListener(new Property.ValueChangeListener() {
																	valueChange: function(event) {
																		setUsuario(linha.getItemProperty('CHAVE_RECEITA_FRETE').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.2">
												<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) {
															if (cliente) {
																var sqlAtualiza = "UPDATE controle_receitas_fretes SET chave_funcionario = ? "+
																		  " WHERE CHAVE_RECEITA_FRETE = ? ";
																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());
															} else {
																MessageBox.show(MessageBox.BoxType.INFO, 'Atenção', 'Tipo de frete não pode ser vazio.');
															}
														};
														
														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_RECEITA_FRETE').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<column name="CTE" caption="CTE" editable="true" commitOnValueChange="true" expand-ratio="0.1"/>
											<generated name="CLIENTE" caption="Cliente" cache="false" expand-ratio="0.2">
												<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) {
															if (cliente) {
																var sqlAtualiza = "UPDATE controle_receitas_fretes SET chave_cliente = ? "+
																		  " WHERE CHAVE_RECEITA_FRETE = ? ";
																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());
															} else {
																MessageBox.show(MessageBox.BoxType.INFO, 'Atenção', 'Cliente não pode ser vazio.');
															}
														};
														
														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_RECEITA_FRETE').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<generated name="TIPO_FRETE" caption="Tipo frete" 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);
														importClass(Packages.br.com.davinti.base.vaadin.components.layout.MessageBox);
														
														var setUsuario = function(chave, cliente) {
															if (cliente) {
																var sqlAtualiza = "UPDATE controle_receitas_fretes SET chave_tipo_frete = ? "+
																		  " WHERE CHAVE_RECEITA_FRETE = ? ";
																var sql = "Select codigo from tipo_frete 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());
															} else {
																MessageBox.show(MessageBox.BoxType.INFO, 'Atenção', 'Tipo de frete não pode ser vazio.');
															}
														};
														
														function generate(itemId, columnId, item, container) {
															
															var sql = "Select codigo, descricao from tipo_frete";
															
															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('TIPO_FRETE').getValue()) {
																combo.setValue(linha.getItemProperty('TIPO_FRETE').getValue());
															}
															
															
															combo.addValueChangeListener(new Property.ValueChangeListener() {
																	valueChange: function(event) {
																		setUsuario(linha.getItemProperty('CHAVE_RECEITA_FRETE').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<generated name="FROTA_TERCEIRO" caption="Frota" 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);
														importClass(Packages.br.com.davinti.base.vaadin.components.layout.MessageBox);
														
														var setUsuario = function(chave, cliente) {
															if (cliente) {
																var sqlAtualiza = "UPDATE controle_receitas_fretes SET frota_terceiro = ? "+
																		  " WHERE CHAVE_RECEITA_FRETE = ? ";
																var params = new java.util.ArrayList();
																params.add(String(cliente));
																params.add(chave);
																vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
															} else {
																MessageBox.show(MessageBox.BoxType.INFO, 'Atenção', 'Frota / Terceiro não pode ser vazio.');
															}
														};
														
														function generate(itemId, columnId, item, container) {
															
															var map = new java.util.LinkedHashMap();
															
															map.put('F', 'Frota');
															map.put('T', 'Terceiro');
															
															var combo = new ComboBox();
															combo.setWidth("100%");
															ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
															
															var linha = item;
															if(linha.getItemProperty('FROTA_TERCEIRO').getValue()) {
																combo.setValue(linha.getItemProperty('FROTA_TERCEIRO').getValue());
															}
															
															
															combo.addValueChangeListener(new Property.ValueChangeListener() {
																	valueChange: function(event) {
																		setUsuario(linha.getItemProperty('CHAVE_RECEITA_FRETE').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
                                 
                                 <generated name="CAMINHAO_CARRETA" caption="Caminhão/Carreta" 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);
                                          importClass(Packages.br.com.davinti.base.vaadin.components.layout.MessageBox);
                                          
                                          var setUsuario = function(chave, cliente) {
                                             if (cliente) {
                                                var sqlAtualiza = "UPDATE controle_receitas_fretes SET caminhao_carreta = ? "+
                                                        " WHERE CHAVE_RECEITA_FRETE = ? ";
                                                var params = new java.util.ArrayList();
                                                params.add(String(cliente));
                                                params.add(chave);
                                                vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
                                             } else {
                                                MessageBox.show(MessageBox.BoxType.INFO, 'Atenção', 'Caminhão / Carreta não pode ser vazio.');
                                             }
                                          };
                                          
                                          function generate(itemId, columnId, item, container) {
                                             
                                             var map = new java.util.LinkedHashMap();
                                             
                                             map.put('C', 'Caminhão');
                                             map.put('T', 'Carreta');
                                             
                                             var combo = new ComboBox();
                                             combo.setWidth("100%");
                                             ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
                                             
                                             var linha = item;
                                             if(linha.getItemProperty('CAMINHAO_CARRETA').getValue()) {
                                                combo.setValue(linha.getItemProperty('CAMINHAO_CARRETA').getValue());
                                             }
                                             
                                             combo.addValueChangeListener(new Property.ValueChangeListener() {
                                                   valueChange: function(event) {
                                                      setUsuario(linha.getItemProperty('CHAVE_RECEITA_FRETE').getValue().longValue(),
                                                         event.getProperty().getValue());
                                                   },
                                                   hashCode: function() {
                                                      return combo.hashCode();
                                                   }
                                                });
                                             
                                             return combo;
                                          }
                                       ]]>
                                    </scriptColumnGenerator>
                                 </generated>
                                 
											<column name="VALOR_FRETE" caption="Valor frete" align="RIGHT" format="#.##0,00" commitOnValueChange="true" editable="true" decimalSeparator="," expand-ratio="0.1" />
											<generated name="UF_ORIGEM" caption="Uf Origem" 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);
														importClass(Packages.br.com.davinti.base.vaadin.components.layout.MessageBox);
														
														var setUsuario = function(chave, cliente) {
															var sqlAtualiza = "UPDATE controle_receitas_fretes SET uf_origem = ? "+
																	  " WHERE CHAVE_RECEITA_FRETE = ? ";
															var sql = "Select chave_estado from estados where sigla = '" + 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.chave_estado);
															params.add(chave);
															vQueryService.executePSUpdateQuery('vitruvio', sqlAtualiza, params.toArray());
														};
														
														function generate(itemId, columnId, item, container) {
															
															var sql = "Select chave_estado, sigla from estados";
															
															var ds = vQueryService.executeQuery('vitruvio', sql);
															
															if(ds == null){
																return null;
															}
															
															var map = new java.util.LinkedHashMap();
															
															while(ds.next()) {
																map.put(ds.getString('SIGLA'), ds.getString('SIGLA'));
															}
															
															var combo = new ComboBox();
															combo.setWidth("100%");
															ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
															
															var linha = item;
															if(linha.getItemProperty('UF_ORIGEM').getValue()) {
																combo.setValue(linha.getItemProperty('UF_ORIGEM').getValue());
															}
															
															combo.addValueChangeListener(new Property.ValueChangeListener() {
																	valueChange: function(event) {
																		setUsuario(linha.getItemProperty('CHAVE_RECEITA_FRETE').getValue().longValue(),
																	   	event.getProperty().getValue());
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<generated name="UF_DESTINO" caption="Uf Destino" 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);
														importClass(Packages.br.com.davinti.base.vaadin.components.layout.MessageBox);
														
														var setUsuario = function(chave, cliente) {
															
															var params = new java.util.ArrayList();
															var sqlEstado = "Select chave_estado from estados where sigla = '" + cliente + "'";
												         	var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															var rowEstado = dbVitruvio.queryRow(sqlEstado);	
															var estado = rowEstado.chave_estado;
															var sql = "Select (crf.valor_frete * (cp.percentual_impostos/100)) impostos, crf.valor_frete - (crf.valor_frete * (cp.percentual_impostos/100)) liquido from controle_receitas_fretes crf inner join clientes_praca cp on cp.chave_cliente = crf.chave_cliente and cp.chave_estado = " + estado + " where crf.chave_receita_frete = " + chave;
															var row = dbVitruvio.queryRow(sql);	
															var impostos = row.impostos;
															var liquido = row.liquido;
															dbVitruvio.transaction(function() {
															   var sqlAtualiza = "UPDATE controle_receitas_fretes SET uf_destino = :chave_estado, valor_imposto = :impostos, valor_liquido = :liquido "+
																	  " WHERE CHAVE_RECEITA_FRETE = :chave";
															   this.update(sqlAtualiza, {
																	chave: Number(chave),
																	chave_estado: Number(estado),
																	impostos: impostos,
																	liquido: liquido
															   });
													        });
														};
														
														function generate(itemId, columnId, item, container) {
															
															var sql = "Select e.sigla from clientes_praca cp inner join clientes c on c.codigo = cp.chave_cliente inner join estados e on e.chave_estado = cp.chave_estado where c.nome = '" + item.getItemProperty('CLIENTE').getValue() + "'";
															
															var ds = vQueryService.executeQuery('vitruvio', sql);
															
															if(ds == null){
																return null;
															}
															
															var map = new java.util.LinkedHashMap();
															
															while(ds.next()) {
																map.put(ds.getString('sigla'), ds.getString('sigla'));
															}
															
															var combo = new ComboBox();
															combo.setWidth("100%");
															ContainerUtils.createAndConfigureContainerFromCaptionMap(map, combo);
															
															var linha = item;
															if(linha.getItemProperty('UF_DESTINO').getValue()) {
																combo.setValue(linha.getItemProperty('UF_DESTINO').getValue());
															}
															
															
															combo.addValueChangeListener(new Property.ValueChangeListener() {
																	valueChange: function(event) {
																		setUsuario(linha.getItemProperty('CHAVE_RECEITA_FRETE').getValue().longValue(),
																	   	event.getProperty().getValue());
																	   	engine.getField('tbLancamentos').refresh();
																	},
																	hashCode: function() {
																		return combo.hashCode();
																	}
																});
																
															
															
															return combo;
														}
													]]>
												</scriptColumnGenerator>
											</generated>
											<column name="VALOR_IMPOSTO" caption="Valor impostos" format="###0.00" decimalSeparator="," expand-ratio="0.1" />
											<column name="VALOR_LIQUIDO" caption="Lucro (Frete - Impostos)" format="###0.00" decimalSeparator="," expand-ratio="0.1" />
										</columns>
										<events>
											<itemChange>
												<script language="JavaScript">
													<![CDATA[
														function onChange(event) {
															var db = libService.loadScript('db');
															var dbVitruvio = new db('vitruvio');
															var sql = "Select (" + event.getField('VALOR_FRETE').getConvertedValue() + " * (cp.percentual_impostos/100)) impostos, " + event.getField('VALOR_FRETE').getConvertedValue() + " - (" + event.getField('VALOR_FRETE').getConvertedValue() + " * (cp.percentual_impostos/100)) liquido from controle_receitas_fretes crf inner join clientes_praca cp on cp.chave_cliente = crf.chave_cliente and cp.chave_estado = crf.uf_destino where crf.chave_receita_frete = " + event.getItemId();
															var row = dbVitruvio.queryRow(sql);	
															var impostos = row.impostos;
															var liquido = row.liquido;
															dbVitruvio.transaction(function() {
															   var sqlAtualiza = "UPDATE controle_receitas_fretes SET data = :data, cte = :cte, valor_frete = :valor_frete, valor_imposto = :valor_imposto, valor_liquido = :valor_liquido, usuario = :usuario " + 
																	  " WHERE CHAVE_RECEITA_FRETE = :chave";
															   this.update(sqlAtualiza, {
																	chave: Number(event.getItemId()),
																	data: event.getField('DATA').getValue(),
																	cte: event.getField('CTE').getConvertedValue(),
																	valor_frete: event.getField('VALOR_FRETE').getConvertedValue(),
																	valor_imposto: impostos,
																	valor_liquido: liquido,
                                                   usuario: engine.getLoggedUser().getLogin()
															   });
													        });
													        engine.getField('tbLancamentos').refresh();
															engine.getGlobalVariable('fncSubTotal')();
															event.commit();	
														}
													]]>
												</script>
											</itemChange>
										</events>
									</DBTable>
								</VerticalLayout>
							</Panel>	
			         	</VerticalLayout>
		         	</Tab> 
	         	</TabLayout>
         	</VerticalLayout>
      	</components>

   	</form>
</panel-form>