@RoinujNosde
este código está nas linhas 303/304
package br.com.fjsistemas.cadastros.view;
import java.text.NumberFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.textfieldformatter.CustomStringBlockFormatter;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.tabs.Tab;
import com.vaadin.flow.component.tabs.Tabs;
import com.vaadin.flow.component.textfield.NumberField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.binder.PropertyId;
import com.vaadin.flow.data.renderer.LocalDateRenderer;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import br.com.fjsistemas.backend.Cliente;
import br.com.fjsistemas.backend.Produto;
import br.com.fjsistemas.backend.Venda;
import br.com.fjsistemas.main.MainView;
import br.com.fjsistemas.repository.ClienteRepository;
import br.com.fjsistemas.repository.ProdutoRepository;
import br.com.fjsistemas.service.VendaService;
@Route(value = "venda-view", layout = MainView.class)
@PageTitle("Lançamento de Vendas")
public class VendaView extends VerticalLayout {
private static final long serialVersionUID = 1L;
private HorizontalLayout hltVenda = new HorizontalLayout();
Grid<Venda> grdVenda = new Grid<>(Venda.class, false);
private HorizontalLayout hltBarraBotoes = new HorizontalLayout();
Button btnNovo = new Button("Novo");
Button btnAlterar = new Button("Alterar");
Button btnExcluir = new Button("Excluir");
private Dialog dlgJanela = new Dialog();
private FormLayout fltCamposVenda = new FormLayout();
HorizontalLayout segundaLinhaGuiaVenda = new HorizontalLayout();
HorizontalLayout terceiraLinhaGuiaVenda = new HorizontalLayout();
HorizontalLayout primeiraLinhaEntrega = new HorizontalLayout();
HorizontalLayout segundaLinhaEntrega = new HorizontalLayout();
HorizontalLayout terceiraLinhaEntrega = new HorizontalLayout();
Tab vender = new Tab("Vendas");
Div venderDiv = new Div();
Tab entrega = new Tab("Entregas");
Div entregaDiv = new Div();
Tab financeiro = new Tab("Financeiro");
Div financeiroDiv = new Div();
double somaValores;
@PropertyId("dataVenda")
private DatePicker txtDataVenda = new DatePicker("Data Venda");
@PropertyId("cliente")
private ComboBox<Cliente> txtNomeCliente = new ComboBox<>();
@PropertyId("telefone")
private TextField txtTelefone = new TextField("Telefone");
@PropertyId("celular")
private TextField txtCelular = new TextField("Celular");
@PropertyId("valorTotalVenda")
private TextField campoSomaValores = new TextField();
@PropertyId("enderecoEntrega")
private TextField enderecoEntrega = new TextField("Endereço");
@PropertyId("numeroEntrega")
private TextField numeroEntrega = new TextField("Nº");
@PropertyId("bairroEntrega")
private TextField bairroEntrega = new TextField("Bairro");
@PropertyId("cidadeEntrega")
private TextField cidadeEntrega = new TextField("Cidade");
@PropertyId("estadoEntrega")
private ComboBox<String> estadoEntrega = new ComboBox<>("Estado");
private HorizontalLayout htlDlgBarraBotoes = new HorizontalLayout();
private Button btnSalvar = new Button("Salvar");
private Button btnFechar = new Button("Fechar");
private Button btnAdicionarItem = new Button("+ Item");
@Autowired
VendaService vendaService;
@Autowired
ClienteRepository clienteRepository;
@Autowired
ProdutoRepository produtoRepository;
private List<Venda> listaVendas;
private List<TextField> valores = new ArrayList<>();
private Venda venda;
Binder<Venda> binderVenda = new Binder<>(Venda.class);
public VendaView() {
}
@PostConstruct
public void init() {
configuraTela();
}
private void configuraTela() {
setMargin(false);
setPadding(false);
configuraHltVenda();
configuraFltBarraBotoes();
configuraDlgJanela();
populaGrdVenda();
configuraBinder();
add(hltVenda, hltBarraBotoes);
}
private void configuraFltBarraBotoes() {
btnNovo.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
btnNovo.addClickListener(e -> {
novoClick();
});
btnAlterar.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
btnAlterar.addClickListener(e -> {
alterarClick();
});
btnExcluir.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
btnExcluir.addClickListener(e -> {
excluirClick();
});
hltBarraBotoes.add(btnNovo, btnAlterar, btnExcluir);
}
private void excluirClick() {
if (venda != null) {
listaVendas.remove(venda);
vendaService.delete(venda);
atualizaGrdVenda();
}
}
private void configuraHltVenda() {
hltVenda.setWidthFull();
configuraGrdVenda();
hltVenda.add(grdVenda);
}
private void configuraGrdVenda() {
grdVenda.setHeight("820px");
grdVenda.setWidthFull();
grdVenda.addColumn(Venda::getId).setHeader("ID:").setAutoWidth(true);
grdVenda.addColumn(new LocalDateRenderer<>(Venda::getDataVenda, DateTimeFormatter.ofPattern("dd/MM/yyy")))
.setHeader("Data Venda").setAutoWidth(true);
grdVenda.addColumn(venda -> venda.getCliente().getNome()).setHeader("Nome:").setAutoWidth(true)
.setKey("cliente.nome");
grdVenda.addColumn(Venda::getValorTotalVenda).setHeader("Valor Total:").setAutoWidth(true)
.setKey("valorTotalVenda");
grdVenda.addThemeVariants(GridVariant.LUMO_COMPACT, GridVariant.LUMO_COLUMN_BORDERS);
grdVenda.getColumns().forEach(col -> col.setAutoWidth(true).setSortable(true));
grdVenda.addItemClickListener(e -> {
venda = e.getItem();
});
}
private void configuraDlgJanela() {
dlgJanela.setHeight("755px");
dlgJanela.setWidth("860px");
dlgJanela.setCloseOnEsc(false);
dlgJanela.setCloseOnOutsideClick(false);
//=====================================================================================================================
txtNomeCliente.setWidth("350px");
txtNomeCliente.setLabel("Nome Cliente");
txtNomeCliente.setItemLabelGenerator(cliente -> {
if (cliente == null || cliente.getNome() == null) {
return " ";
} else {
return cliente.getNome();
}
});
List<Cliente> listaDeClientes = clienteRepository.findAll();
txtNomeCliente.setItems(listaDeClientes);
txtNomeCliente.addValueChangeListener(event -> {
if (event.getValue() == null || event.getValue().getFone() == null) {
txtTelefone.setValue(" ");
} else {
txtTelefone.setValue(event.getValue().getFone());
}
if (event.getValue() == null || event.getValue().getCelular() == null) {
txtCelular.setValue(" ");
} else {
txtCelular.setValue(event.getValue().getCelular());
}
});
new CustomStringBlockFormatter.Builder().blocks(0, 2, 4, 4).delimiters("(", ")", "-").numeric().build()
.extend(txtTelefone);
new CustomStringBlockFormatter.Builder().blocks(0, 2, 5, 4).delimiters("(", ")", "-").numeric().build()
.extend(txtCelular);
//=====================================================================================================================
Label text = new Label("Valor Total da Compra");
text.getElement().getStyle().set("fontWeight", "bold");
text.getStyle().set("margin-top", "2em");
text.getStyle().set("margin-left", "2em");
text.getStyle().set("text-align", "center");
campoSomaValores.getStyle().set("margin-top", "2em");
campoSomaValores.getStyle().set("margin-right", "1em");
campoSomaValores.setWidth("30em");
//==========================================================================================================================
segundaLinhaGuiaVenda.add(txtNomeCliente, txtTelefone, txtCelular);
fltCamposVenda.add(venderDiv, entregaDiv, financeiroDiv);
venderDiv.add(txtDataVenda, segundaLinhaGuiaVenda);
venderDiv.getStyle().set("height", "600px");
venderDiv.getStyle().set("width", "800px");
venderDiv.getStyle().set("overflow-y", "scroll");
vender.add(venderDiv);
estadoEntrega.setPlaceholder("Escolha uma Opção");
estadoEntrega.setItems("Acre(AC)", "Alagoas(AL)", "Amapá(AP)", "Amazonas(AM)", "Bahia(BA)", "Ceará(CE)",
"Distrito Federal(DF)", "Espírito Santo(ES", "Goias(GO)", "Maranhão(MA)", "Mato Grosso(MT)",
"Mato Grosso do Sul(MS)", "Minas Gerais(MG)", "Pará(PA)", "Paraíba(PB)", "Paraná(PR)", "Pernanbuco(PE)",
"Piauí(PI)", "Rio de Janeiro(RJ)", "Rio Grande do Norte(RN)", "Rio Grande do Sul(RS)", "Rondônia(RO)",
"Roraima(RR)", "Santa Catarina(SC)", "São Paulo(SP)", "Sergipe(SE)", "Tocantins(TO)");
Checkbox checkbox = new Checkbox();
checkbox.setLabel("Mesmo Endereço do Cadastro");
checkbox.setValue(true);
primeiraLinhaEntrega.add(enderecoEntrega, numeroEntrega, bairroEntrega);
segundaLinhaEntrega.add(cidadeEntrega, estadoEntrega);
terceiraLinhaEntrega.add(checkbox);
entregaDiv.add(primeiraLinhaEntrega, segundaLinhaEntrega, terceiraLinhaEntrega);
entrega.add(entregaDiv);
LocalDate now = LocalDate.now();
txtDataVenda.setValue(now);
Map<Tab, Component> tabsToPages = new HashMap<>();
tabsToPages.put(vender, venderDiv);
tabsToPages.put(entrega, entregaDiv);
tabsToPages.put(financeiro, financeiroDiv);
Tabs tabs = new Tabs(vender, entrega, financeiro);
Div pages = new Div(venderDiv, entregaDiv, financeiroDiv);
tabs.addSelectedChangeListener(event -> {
tabsToPages.values().forEach(page -> page.setVisible(false));
Component selectedPage = tabsToPages.get(tabs.getSelectedTab());
selectedPage.setVisible(true);
});
dlgJanela.add(tabs, pages);
btnSalvar.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
btnSalvar.getStyle().set("margin-top", "2em");
btnSalvar.getStyle().set("margin-left", "1em");
btnSalvar.addClickListener(e -> {
salvarClick();
});
btnFechar.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
btnFechar.getStyle().set("margin-top", "2em");
btnFechar.addClickListener(e -> {
dlgJanela.close();
});
btnAdicionarItem.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
btnAdicionarItem.getStyle().set("margin-top", "2em");
btnAdicionarItem.addClickListener(e -> {
adicionaProduto();
});
dlgJanela.add(fltCamposVenda, htlDlgBarraBotoes);
}
private void salvarClick() {
venda = binderVenda.getBean();
boolean adicionarLista = venda.getId() == null ? true : false;
vendaService.create(venda);
if (adicionarLista) {
listaVendas.add(venda);
}
atualizaGrdVenda();
novaVenda();
txtNomeCliente.focus();
binderVenda.setBean(venda);
if (adicionarLista) {
dlgJanela.close();
}
}
private void populaGrdVenda() {
listaVendas = vendaService.read();
atualizaGrdVenda();
}
private void atualizaGrdVenda() {
grdVenda.setItems(listaVendas);
}
private void configuraBinder() {
binderVenda.bindInstanceFields(this);
}
private void novoClick() {
novaVenda();
binderVenda.setBean(venda);
dlgJanela.open();
txtNomeCliente.focus();
}
private void alterarClick() {
if (venda != null) {
binderVenda.setBean(venda);
dlgJanela.open();
}
}
private void adicionaProduto() {
ComboBox<Produto> txtProdutos = new ComboBox<>();
NumberField txtQuantidade = new NumberField("Quantidade");
TextField txtValorUnitario = new TextField("Valor Unitário");
TextField txtValorTotalItem = new TextField("Valor Total Item");
txtProdutos.setWidth("370px");
txtProdutos.setLabel("Produtos");
List<Produto> listaDeProdutos = produtoRepository.findAll();
txtProdutos.setItemLabelGenerator(Produto::getNome);
txtProdutos.setItems(listaDeProdutos);
txtProdutos.addValueChangeListener(event -> {
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
try {
txtValorUnitario.setValue(formatter.format(event.getValue().getValor()));
} catch (Exception e) {
e.printStackTrace();
}
});
//==========================================================================================================================
txtQuantidade.setHasControls(true);
txtQuantidade.setValue(null);
txtQuantidade.setMin(1);
txtQuantidade.addValueChangeListener(event -> {
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
double valorTotal = 0;
try {
valorTotal = formatter.parse(txtValorUnitario.getValue()).doubleValue() * txtQuantidade.getValue();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
txtValorTotalItem.setValue(formatter.format(valorTotal));
double soma = 0;
for (TextField tf : valores) {
try {
soma += formatter.parse(tf.getValue()).doubleValue();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
campoSomaValores.setValue(formatter.format(soma));
});
HorizontalLayout linhaNova = new HorizontalLayout();
linhaNova.add(txtProdutos, txtQuantidade, txtValorUnitario, txtValorTotalItem);
venderDiv.add(linhaNova);
valores.add(txtValorTotalItem);
}
private void novaVenda() {
venda = new Venda();
venda.setCliente(null);
dlgJanela.close();
}
}