FacturaController.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.avbravo.store.controller;
// <editor-fold defaultstate="collapsed" desc="imports">
import com.avbravo.avbravoutils.JsfUtil;
import com.avbravo.avbravoutils.printer.Printer;
import com.avbravo.ejbjmoordb.interfaces.IController;
import com.avbravo.ejbjmoordb.services.RevisionHistoryServices;
import com.avbravo.ejbjmoordb.services.UserInfoServices;
import com.avbravo.storeejb.producer.AutoincrementableStoreejbRepository;
import com.avbravo.storeejb.datamodel.FacturaDataModel;
import com.avbravo.storeejb.repository.FacturaRepository;
import com.avbravo.storeejb.producer.RevisionHistoryStoreejbRepository;
import com.avbravo.storeejb.entity.Factura;
import com.avbravo.storeejb.services.FacturaServices;
import com.avbravo.store.util.ResourcesFiles;
import com.avbravo.storeejb.datamodel.FacturadetalleDataModel;
import com.avbravo.storeejb.entity.Cliente;
import com.avbravo.storeejb.entity.Facturadetalle;
import com.avbravo.storeejb.entity.Proveedor;
import com.avbravo.storeejb.entity.Usuario;
import com.avbravo.storeejb.repository.ArticuloRepository;
import com.avbravo.storeejb.repository.InventarioRepository;
import com.avbravo.storeejb.repository.InventariodetalleRepository;
import com.avbravo.storeejb.repository.FacturadetalleRepository;
import com.avbravo.storeejb.services.AlmacenServices;
import com.avbravo.storeejb.services.ArticuloServices;
import com.avbravo.storeejb.producer.AutoincrementableStoreejbServices;
import com.avbravo.storeejb.services.InventarioServices;
import com.avbravo.store.util.LookupServices;
import com.avbravo.storeejb.entity.Estatusfactura;
import com.avbravo.storeejb.producer.ErrorInfoStoreejbServices;
import com.avbravo.storeejb.repository.EstatusfacturaRepository;
import com.avbravo.storeejb.services.OrdenServices;
import java.util.ArrayList;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.faces.context.FacesContext;
import org.bson.Document;
import org.primefaces.PrimeFaces;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.SelectEvent;
// </editor-fold>
/**
*
* @authoravbravo
*/
@Named
@ViewScoped
public class FacturaController implements Serializable, IController {
// <editor-fold defaultstate="collapsed" desc="fields">
private static final long serialVersionUID = 1L;
private static final Logger LOG = Logger.getLogger(FacturaController.class.getName());
// @Inject
//private transient ExternalContext externalContext;
private Boolean writable = false;
private Boolean isContado = false;
private Boolean showTable = false;
//DataModel
private FacturaDataModel facturaDataModel;
private FacturadetalleDataModel facturadetalleDataModel;
Integer page = 1;
Integer rowPage = 25;
List<Integer> pages = new ArrayList<>();
//
//Entity
Cliente cliente;
Cliente clienteSelected;
Factura factura;
Factura facturaSelected;
Facturadetalle facturadetalle;
Facturadetalle facturadetalleSelected;
Proveedor proveedorSelected;
Usuario vendedor = new Usuario();
Usuario capturador = new Usuario();
//List
List<Factura> facturaList = new ArrayList<>();
List<Factura> facturaFiltered = new ArrayList<>();
List<Facturadetalle> facturadetalleList = new ArrayList<>();
List<Facturadetalle> facturadetalleFiltered = new ArrayList<>();
List<Usuario> usuarioList = new ArrayList<>();
//Repository
@Inject
AutoincrementableStoreejbRepository autoincrementableRepository;
@Inject
ArticuloRepository articuloRepository;
@Inject
InventarioRepository inventarioRepository;
@Inject
InventariodetalleRepository inventariodetalleRepository;
@Inject
FacturaRepository facturaRepository;
@Inject
EstatusfacturaRepository estatusfacturaRepository;
@Inject
FacturadetalleRepository facturadetalleRepository;
@Inject
RevisionHistoryStoreejbRepository revisionHistoryStoreejbRepository;
//Services
ErrorInfoStoreejbServices errorServices;
@Inject
AlmacenServices almacenServices;
@Inject
OrdenServices ordenServices;
@Inject
AutoincrementableStoreejbServices autoincrementableStoreejbServices;
@Inject
ArticuloServices articuloServices;
@Inject
InventarioServices inventarioServices;
@Inject
LookupServices lookupServices;
@Inject
RevisionHistoryServices revisionHistoryServices;
@Inject
UserInfoServices userInfoServices;
@Inject
FacturaServices facturaServices;
@Inject
ResourcesFiles rf;
@Inject
Printer printer;
@Inject
LoginController loginController;
//List of Relations
//Repository of Relations
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter">
public List<Integer> getPages() {
return facturaRepository.listOfPage(rowPage);
}
public void setPages(List<Integer> pages) {
this.pages = pages;
}
public Boolean getShowTable() {
return showTable;
}
public void setShowTable(Boolean showTable) {
this.showTable = showTable;
}
public Usuario getVendedor() {
return vendedor;
}
public List<Usuario> getUsuarioList() {
return usuarioList;
}
public void setUsuarioList(List<Usuario> usuarioList) {
this.usuarioList = usuarioList;
}
public void setVendedor(Usuario vendedor) {
this.vendedor = vendedor;
}
public Usuario getCapturador() {
return capturador;
}
public void setCapturador(Usuario capturador) {
this.capturador = capturador;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public Cliente getClienteSelected() {
return clienteSelected;
}
public void setClienteSelected(Cliente clienteSelected) {
this.clienteSelected = clienteSelected;
}
public OrdenServices getOrdenServices() {
return ordenServices;
}
public void setOrdenServices(OrdenServices ordenServices) {
this.ordenServices = ordenServices;
}
public ArticuloServices getArticuloServices() {
return articuloServices;
}
public void setArticuloServices(ArticuloServices articuloServices) {
this.articuloServices = articuloServices;
}
public List<Facturadetalle> getFacturadetalleList() {
return facturadetalleList;
}
public void setFacturadetalleList(List<Facturadetalle> facturadetalleList) {
this.facturadetalleList = facturadetalleList;
}
public FacturadetalleDataModel getFacturadetalleDataModel() {
return facturadetalleDataModel;
}
public void setFacturadetalleDataModel(FacturadetalleDataModel facturadetalleDataModel) {
this.facturadetalleDataModel = facturadetalleDataModel;
}
public Facturadetalle getFacturadetalle() {
return facturadetalle;
}
public void setFacturadetalle(Facturadetalle facturadetalle) {
this.facturadetalle = facturadetalle;
}
public Facturadetalle getFacturadetalleSelected() {
return facturadetalleSelected;
}
public void setFacturadetalleSelected(Facturadetalle facturadetalleSelected) {
this.facturadetalleSelected = facturadetalleSelected;
}
public List<Facturadetalle> getFacturadetalleFiltered() {
return facturadetalleFiltered;
}
public void setFacturadetalleFiltered(List<Facturadetalle> facturadetalleFiltered) {
this.facturadetalleFiltered = facturadetalleFiltered;
}
public Proveedor getProveedorSelected() {
return proveedorSelected;
}
public void setProveedorSelected(Proveedor proveedorSelected) {
this.proveedorSelected = proveedorSelected;
}
public LookupServices getLookupServices() {
return lookupServices;
}
public void setLookupServices(LookupServices lookupServices) {
this.lookupServices = lookupServices;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getRowPage() {
return rowPage;
}
public void setRowPage(Integer rowPage) {
this.rowPage = rowPage;
}
public FacturaServices getFacturaServices() {
return facturaServices;
}
public void setFacturaServices(FacturaServices facturaServices) {
this.facturaServices = facturaServices;
}
public List<Factura> getFacturaList() {
return facturaList;
}
public void setFacturaList(List<Factura> facturaList) {
this.facturaList = facturaList;
}
public List<Factura> getFacturaFiltered() {
return facturaFiltered;
}
public void setFacturaFiltered(List<Factura> facturaFiltered) {
this.facturaFiltered = facturaFiltered;
}
public Factura getFactura() {
return factura;
}
public void setFactura(Factura factura) {
this.factura = factura;
}
public Factura getFacturaSelected() {
return facturaSelected;
}
public void setFacturaSelected(Factura facturaSelected) {
this.facturaSelected = facturaSelected;
}
public FacturaDataModel getFacturaDataModel() {
return facturaDataModel;
}
public void setFacturaDataModel(FacturaDataModel facturaDataModel) {
this.facturaDataModel = facturaDataModel;
}
public Boolean getWritable() {
return writable;
}
public void setWritable(Boolean writable) {
this.writable = writable;
}
public Boolean getIsContado() {
return isContado;
}
public void setIsContado(Boolean isContado) {
this.isContado = isContado;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="constructor">
public FacturaController() {
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="preRenderView()">
@Override
public String preRenderView(String action) {
//acciones al llamar el formulario despues del init
return "";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="init">
@PostConstruct
public void init() {
try {
String action = loginController.get("factura");
String id = loginController.get("idfactura");
String pageSession = loginController.get("pagefactura");
//Search
if (loginController.get("searchfactura") == null || loginController.get("searchfactura").equals("")) {
loginController.put("searchfactura", "_init");
}
writable = false;
showTable = false;
facturaList = new ArrayList<>();
facturaFiltered = new ArrayList<>();
facturadetalleList = new ArrayList<>();
facturadetalleFiltered = new ArrayList<>();
factura = new Factura();
facturadetalle = new Facturadetalle();
facturadetalleSelected = new Facturadetalle();
facturaDataModel = new FacturaDataModel(facturaList);
facturadetalleDataModel = new FacturadetalleDataModel(facturadetalleList);
cliente = new Cliente();
clienteSelected = new Cliente();
//
vendedor = new Usuario();
capturador = loginController.getUsuario();
if (pageSession != null) {
page = Integer.parseInt(pageSession);
}
Integer c = facturaRepository.sizeOfPage(rowPage);
page = page > c ? c : page;
if (action != null) {
switch (action) {
case "gonew":
writable = false;
inicializarFactura();
break;
case "view":
if (id != null) {
Optional<Factura> optional = facturaRepository.find("idfactura", id);
if (optional.isPresent()) {
factura = optional.get();
vendedor = factura.getUsuario().get(0);
capturador = factura.getUsuario().get(1);
facturaSelected = factura;
writable = true;
}
}
break;
case "golist":
move();
break;
}
} else {
move();
}
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="inicializarFactura()">
private void inicializarFactura() {
try {
List<Estatusfactura> estatusfacturaList = estatusfacturaRepository.findBy(new Document("descripcion", "NOFACTURADO"));
if (estatusfacturaList.isEmpty()) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.noexisteestatusfacturanofacturado"));
return;
}
showTable = false;
factura = new Factura();
factura.setFecha(JsfUtil.getFechaActual());
factura.setEntregado("no");
factura.setEntregado("no");
factura.setCondicion("credito");
factura.setEstatusfactura(estatusfacturaList.get(0));
factura.setImpreso("no");
factura.setSaldo(0.0);
factura.setSubtotal(0.0);
factura.setItbms(0.0);
factura.setDescuento(0.0);
factura.setTotal(0.0);
factura.setMontoacuenta(0.0);
factura.setMontoalrecibir(0.0);
factura.setVuelto(0.0);
factura.setSaldo(0.0);
factura.setFecha(JsfUtil.getFechaActual());
factura.setCantidadmeses(0);
factura.setFechaentrega(JsfUtil.getFechaActual());
factura.setObservacion("---");
factura.setCantidadmeses(13);
factura.setEfectivo(0.0);
factura.setHoraentrega("03:00pm");
factura.setFechavencimiento(JsfUtil.sumarMesaFechaActual(factura.getCantidadmeses()));
facturaSelected = factura;
proveedorSelected = new Proveedor();
facturadetalleList = new ArrayList<>();
facturadetalleFiltered = new ArrayList<>();
facturadetalleDataModel = new FacturadetalleDataModel(facturadetalleList);
facturaList = new ArrayList<>();
facturaFiltered = new ArrayList<>();
facturadetalleList = new ArrayList<>();
facturadetalle = new Facturadetalle();
facturadetalle.setCantidad(0);
facturadetalle.setDescuento(0.0);
facturadetalle.setPrecio(0.0);
facturadetalle.setTotal(0.0);
facturadetalle.setCantidademisor(0);
facturadetalle.setActivo("si");
facturadetalleList.add(facturadetalle);
facturadetalleFiltered = facturadetalleList;
facturadetalleFiltered = new ArrayList<>();
facturadetalle = new Facturadetalle();
facturadetalleSelected = new Facturadetalle();
facturaDataModel = new FacturaDataModel(facturaList);
facturadetalleDataModel = new FacturadetalleDataModel(facturadetalleList);
cliente = new Cliente();
clienteSelected = new Cliente();
//
vendedor = new Usuario();
capturador = loginController.getUsuario();
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
} // </editor-fold>
// <editor-fold defaultstate="collapsed" desc="reset">
@Override
public void reset() {
RequestContext.getCurrentInstance().reset(":form:content");
prepare("new", factura);
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="prepare(String action, Object... item)">
public String prepare(String action, Factura item) {
String url = "";
try {
loginController.put("pagefactura", page.toString());
loginController.put("factura", action);
switch (action) {
case "new":
inicializarFactura();
writable = false;
break;
case "view":
facturaSelected = item;
factura = facturaSelected;
loginController.put("idfactura", factura.getIdfactura().toString());
url = "/pages/factura/view.xhtml";
break;
case "golist":
url = "/pages/factura/list.xhtml";
break;
case "gonew":
url = "/pages/factura/new.xhtml";
break;
}
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return url;
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="showAll">
@Override
public String showAll() {
try {
facturaList = new ArrayList<>();
facturaFiltered = new ArrayList<>();
facturaList = facturaRepository.findAll();
facturaFiltered = facturaList;
facturaDataModel = new FacturaDataModel(facturaList);
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="isNew">
@Override
public String isNew() {
try {
writable = true;
if (JsfUtil.isVacio(factura.getIdfactura())) {
writable = false;
return "";
}
Optional<Factura> optional = facturaRepository.findById(factura);
if (optional.isPresent()) {
writable = false;
JsfUtil.warningMessage(rf.getAppMessage("warning.idexist"));
return "";
} else {
Integer id = factura.getIdfactura();
factura = new Factura();
factura.setIdfactura(id);
factura.setCantidadmeses(0);
factura.setFechavencimiento(JsfUtil.getFechaActual());
factura.setObservacion("---");
facturaSelected = new Factura();
}
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="save()">
@Override
public String save() {
return "";
} // </editor-fold>
// <editor-fold defaultstate="collapsed" desc="save(String tipofactura, String subtipofactura)">
public String save(String tipofactura, String subtipofactura) {
try {
factura.setSaldo(factura.getTotal() - factura.getMontoacuenta()- factura.getDescuento());
pagar();
if (!valid()) {
return "";
}
//Genera una factura para cada almacen
//-> puede ser una tienda
//--> o una ganga en base al usuario logeado.
Integer identity = autoincrementableStoreejbServices.getContador("factura");
factura.setIdfactura(identity);
String idfacturaalmacen = "factura_" + loginController.getAlmacen().getTipoalmacen().getIdtipoalmacen() + "_" + loginController.getAlmacen().getIdalmacen();
Integer numerofactura = autoincrementableStoreejbServices.getContador(idfacturaalmacen);
factura.setNumerofactura(numerofactura);
factura.setAlmacen(loginController.getAlmacen());
factura.setEntregado("no");
usuarioList = new ArrayList<>();
usuarioList.add(vendedor);
usuarioList.add(capturador);
factura.setUsuario(usuarioList);
//Carga los datos idemisorreceptor
factura.setUserInfo(userInfoServices.generateListUserinfo(loginController.getUsername(), "create"));
if (facturaRepository.save(factura)) {
revisionHistoryStoreejbRepository.save(revisionHistoryServices.getRevisionHistory(factura.getIdfactura().toString(), loginController.getUsername(),
"create", "factura", facturaRepository.toDocument(factura).toString()));
JsfUtil.successMessage(rf.getAppMessage("info.save"));
//---
//Guardar el detalle de la factura
for (Facturadetalle fd : facturadetalleList) {
Facturadetalle facturadetalle = new Facturadetalle();
Integer identitydetalle = autoincrementableStoreejbServices.getContador("facturadetalle");
facturadetalle.setIdfacturadetalle(identitydetalle);
facturadetalle.setFactura(factura);
facturadetalle.setActivo("si");
facturadetalle.setArticulo(fd.getArticulo());
facturadetalle.setCantidad(fd.getCantidad());
facturadetalle.setDescuento(fd.getDescuento());
facturadetalle.setCantidademisor(0);
facturadetalle.setPrecio(fd.getPrecio());
facturadetalle.setTotal(fd.getCantidad() * fd.getPrecio());
facturadetalle.setUserInfo(userInfoServices.generateListUserinfo(loginController.getUsername(), "create"));
if (facturadetalleRepository.save(facturadetalle)) {
revisionHistoryStoreejbRepository.save(revisionHistoryServices.getRevisionHistory(facturadetalle.getIdfacturadetalle().toString(), loginController.getUsername(),
"create", "facturadetalle", facturadetalleRepository.toDocument(facturadetalle).toString()));
}
//Actualiza el inventario
// inventarioServices.saveFromFactura(facturadetalle, subtipofactura, loginController.getUsername(), bodegaSelected, tiendaSelected, gangaSelected, internoSelected, proveedorSelected);
}
//Limpia los datos
inicializarFactura();
} else {
JsfUtil.successMessage("save() " + facturaRepository.getException().toString());
}
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="edit">
@Override
public String edit() {
try {
usuarioList = new ArrayList<>();
usuarioList.add(vendedor);
usuarioList.add(capturador);
factura.setUsuario(usuarioList);
factura.getUserInfo().add(userInfoServices.generateUserinfo(loginController.getUsername(), "update"));
//guarda el contenido anterior
//guarda el contenido actualizado
revisionHistoryStoreejbRepository.save(revisionHistoryServices.getRevisionHistory(factura.getIdfactura().toString(), loginController.getUsername(),
"update", "factura", facturaRepository.toDocument(factura).toString()));
facturaRepository.update(factura);
JsfUtil.successMessage(rf.getAppMessage("info.update"));
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="delete(Object item, Boolean deleteonviewpage)">
@Override
public String delete(Object item, Boolean deleteonviewpage) {
String path = "";
try {
factura = (Factura) item;
if (!facturaServices.isDeleted(factura)) {
JsfUtil.warningDialog("Delete", rf.getAppMessage("waring.integridadreferencialnopermitida"));
return "";
}
facturaSelected = factura;
if (facturaRepository.delete("idfactura", factura.getIdfactura())) {
revisionHistoryStoreejbRepository.save(revisionHistoryServices.getRevisionHistory(factura.getIdfactura().toString(), loginController.getUsername(), "delete", "factura", facturaRepository.toDocument(factura).toString()));
JsfUtil.successMessage(rf.getAppMessage("info.delete"));
if (!deleteonviewpage) {
facturaList.remove(factura);
facturaFiltered = facturaList;
facturaDataModel = new FacturaDataModel(facturaList);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("pagefactura", page.toString());
} else {
factura = new Factura();
facturaSelected = new Factura();
writable = false;
}
}
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
// path = deleteonviewpage ? "/pages/factura/list.xhtml" : "";
path = "";
return path;
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="deleteAll">
@Override
public String deleteAll() {
if (facturaRepository.deleteAll() != 0) {
JsfUtil.successMessage(rf.getAppMessage("info.delete"));
}
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="print">
@Override
public String print() {
try {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("pagefactura", page.toString());
List<Factura> list = new ArrayList<>();
list.add(factura);
String ruta = "/resources/reportes/factura/details.jasper";
HashMap parameters = new HashMap();
parameters.put("P_EMPRESA", loginController.getUsuario().getEmpresa().getDescripcion());
printer.imprimir(list, ruta, parameters);
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return null;
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="printAll">
@Override
public String printAll() {
try {
List<Factura> list = new ArrayList<>();
list = facturaRepository.findAll(new Document("idfactura", 1));
String ruta = "/resources/reportes/factura/all.jasper";
HashMap parameters = new HashMap();
parameters.put("P_EMPRESA", loginController.getUsuario().getEmpresa().getDescripcion());
printer.imprimir(list, ruta, parameters);
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return null;
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="handleSelect">
public void handleSelect(SelectEvent event) {
try {
showTable = true;
factura.setHoraentrega("03:00pm");
factura.setEfectivo(0.0);
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="handleSelect">
public void handleSelectCliente(SelectEvent event) {
try {
showTable = true;
factura.setHoraentrega("03:00pm");
factura.setEfectivo(0.0);
facturadetalle = new Facturadetalle();
// Facturadetalle facturadetalle2 = new Facturadetalle();
facturadetalle.setCantidad(0);
facturadetalle.setDescuento(0.0);
facturadetalle.setPrecio(0.0);
facturadetalle.setTotal(0.0);
facturadetalle.setCantidademisor(0);
facturadetalle.setActivo("si");
// facturadetalle2.setCantidad(0);
// facturadetalle2.setDescuento(0.0);
// facturadetalle2.setPrecio(0.0);
// facturadetalle2.setTotal(0.0);
// facturadetalle2.setCantidademisor(0);
// facturadetalle2.setActivo("si");
facturadetalleList.add(facturadetalle);
// facturadetalleList.add(facturadetalle2);
facturadetalleFiltered = new ArrayList<>();
facturadetalleFiltered = facturadetalleList;
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="handleAutocompleteOfListXhtml(SelectEvent event)">
public void handleAutocompleteOfListXhtml(SelectEvent event) {
try {
facturaList.removeAll(facturaList);
facturaList.add(facturaSelected);
facturaFiltered = facturaList;
facturaDataModel = new FacturaDataModel(facturaList);
lookupServices.setIdfactura(facturaSelected.getIdfactura());
loginController.put("searchfactura", "idfactura");
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="last">
@Override
public String last() {
try {
page = facturaRepository.sizeOfPage(rowPage);
move();
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="first">
@Override
public String first() {
try {
page = 1;
move();
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="next">
@Override
public String next() {
try {
if (page < (facturaRepository.sizeOfPage(rowPage))) {
page++;
}
move();
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="back">
@Override
public String back() {
try {
if (page > 1) {
page--;
}
move();
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="skip(Integer page)">
@Override
public String skip(Integer page) {
try {
this.page = page;
move();
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="move">
@Override
public void move() {
try {
//Filtra por el almacen
Document doc;
Document sort = new Document("idfactura", -1);
switch (loginController.get("searchfactura")) {
case "_init":
case "_autocomplete":
doc = new Document("almacen.idalmacen", loginController.getAlmacen().getIdalmacen());
facturaList = facturaRepository.findPagination(doc, page, rowPage, sort);
break;
case "idfactura":
if (lookupServices.getIdfactura() != null) {
doc = new Document("idfactura", lookupServices.getIdfactura()).append("almacen.idalmacen", loginController.getAlmacen().getIdalmacen());
facturaList = facturaRepository.findPagination(doc, page, rowPage, new Document("idfactura", -1));
} else {
doc = new Document("almacen.idalmacen", loginController.getAlmacen().getIdalmacen());
facturaList = facturaRepository.findPagination(doc, page, rowPage);
}
break;
default:
doc = new Document("almacen.idalmacen", loginController.getAlmacen().getIdalmacen());
facturaList = facturaRepository.findPagination(doc, page, rowPage, sort);
break;
}
facturaFiltered = facturaList;
facturaDataModel = new FacturaDataModel(facturaList);
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="clear">
@Override
public String clear() {
try {
loginController.put("searchfactura", "_init");
page = 1;
move();
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="searchBy(String string, Boolean... blns)">
@Override
public String searchBy(String string) {
try {
loginController.put("searchfactura", string);
writable = true;
move();
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="addFila()">
public String addFila() {
try {
facturadetalle = new Facturadetalle();
facturadetalle.setCantidad(0);
facturadetalle.setDescuento(0.0);
facturadetalle.setPrecio(0.0);
facturadetalle.setTotal(0.0);
facturadetalle.setCantidademisor(0);
facturadetalle.setActivo("si");
facturadetalleList.add(facturadetalle);
facturadetalleFiltered = facturadetalleList;
facturadetalleDataModel = new FacturadetalleDataModel(facturadetalleList);
showTotales();
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
LOG.info("addFila()" + e.getLocalizedMessage());
}
return "";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="onArticuloChange(int rowIndex, Facturadetalle facturadetalle, String subtipofactura)">
public String onArticuloChange(int rowIndex, Facturadetalle facturadetalle, String subtipofactura) {
try {
Integer count = 0;
if (!facturadetalleList.isEmpty()) {
for (Facturadetalle o : facturadetalleList) {
if (o.getArticulo() != null) {
if (facturadetalle.getArticulo().getIdarticulo().equals(o.getArticulo().getIdarticulo())) {
count++;
}
}
}
if (count > 1) {
JsfUtil.infoDialog(rf.getMessage("warning.view"), rf.getMessage("warning.articulorepetido"));
facturadetalleList.remove(rowIndex);
}
}
Integer cantidademisor = 0;
Integer cantidadreceptor = 0;
switch (subtipofactura) {
case "factura":
// cantidademisor = inventarioServices.cantidadInventarioOf(facturadetalle.getArticulo(), loginController.getUsuario().getIdalmacen(), loginController.getUsuario().getTipoalmacen());
break;
}
facturadetalleList.get(rowIndex).setCantidademisor(cantidademisor);
if (factura.getCondicion().equals("contado")) {
facturadetalleList.get(rowIndex).setPrecio(facturadetalle.getArticulo().getPrecioventapublico());
} else {
facturadetalleList.get(rowIndex).setPrecio(facturadetalle.getArticulo().getPrecioventacredito());
}
// facturadetalleList.get(rowIndex).setCantidad(1);
facturadetalleList.get(rowIndex).setCantidad(0);
facturadetalleList.get(rowIndex).setTotal(facturadetalleList.get(rowIndex).getCantidad() * facturadetalleList.get(rowIndex).getPrecio());
showTotales();
//update panel
// PrimeFaces.current().ajax().update("form:panel");
//scroll to panel
// PrimeFaces.current().scrollTo("form:efectivoDialog");
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
errorServices.errorDialog(nameOfClass(), nameOfMethod(), "error", e.getLocalizedMessage());
JsfUtil.errorDialog("error", e.getLocalizedMessage());
}
return "";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="calcularBalance">
public Integer calcularBalance(Integer cantidad, Integer anterior, Facturadetalle item, int rowIndex) {
Integer balance = 0;
try {
if (item.getArticulo() == null) {
facturadetalleList.get(rowIndex).setCantidad(0);
return balance;
}
if (cantidad > 0) {
balance = cantidad + anterior;
}
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return balance;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="calcularCosto( Facturadetalle item, int rowIndex)">
public Double calcularCosto(Facturadetalle item, int rowIndex) {
Double costo = 0.0;
try {
if (item.getArticulo() == null) {
facturadetalleList.get(rowIndex).setCantidad(0);
return 0.0;
}
costo = facturadetalleList.get(rowIndex).getCantidad() * facturadetalleList.get(rowIndex).getPrecio();
costo = JsfUtil.redondear(costo, 2);
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return costo;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="refresh()">
public String refresh() {
return "";
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="onCellEdit(CellEditEvent event) ">
public void onCellEdit(CellEditEvent event) {
try {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
Integer cantidad = facturadetalleList.get(event.getRowIndex()).getCantidad();
Integer cantidadanterioremisor = facturadetalleList.get(event.getRowIndex()).getCantidademisor();
if(cantidad < 0)
{
//
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.cantidadmenorquecero"));
facturadetalleList.get(event.getRowIndex()).setCantidad(1);
cantidad =1;
}
Integer nuevacantidad = cantidad;
if (facturadetalleList.get(event.getRowIndex()).getArticulo() == null) {
facturadetalleList.get(event.getRowIndex()).setCantidad(0);
return;
}
if (cantidad > cantidadanterioremisor) {
// JsfUtil.warningMessage(rf.getMessage("warning.cantidadmayordisponible"));
// JsfUtil.warningDialog("Advertencia",rf.getMessage("warning.cantidadmayordisponible"));
// facturadetalleList.get(event.getRowIndex()).setCantidad(0);
}
showTotales();
} catch (Exception e) {
//errorServices.errorMessage(nameOfClass(),nameOfMethod(), e.getLocalizedMessage());
JsfUtil.errorDialog("error", "onCellEdit() " + e.getLocalizedMessage());
}
} // </editor-fold>
// <editor-fold defaultstate="collapsed" desc="onRowDelete(int rowIndex)">
public void onRowDelete(int rowIndex) {
try {
facturadetalleList.remove(rowIndex);
facturadetalleFiltered = facturadetalleList;
facturadetalleDataModel = new FacturadetalleDataModel(facturadetalleList);
showTotales();
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="valid()">
private Boolean valid() {
try {
List<Estatusfactura> estatusfacturaList = estatusfacturaRepository.findBy(new Document("descripcion", "NOFACTURADO"));
if (estatusfacturaList.isEmpty()) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.noexisteestatusfacturanofacturado"));
return false;
}
if (facturadetalleList.isEmpty()) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.noseleccionoarticulosparafacturar"));
return false;
}
if (factura.getTotal() <= 0) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.totalmenoroigualcero"));
return false;
}
if (factura.getMontoacuenta()<= 0) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.montoacuentaoigualcero"));
return false;
}
if (factura.getMontoalrecibir()< 0) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.montoarecibirmenoroigualcero"));
return false;
}
if (factura.getMontoacuenta()> factura.getTotal()) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.montoacuentamayortotal"));
return false;
}
if (factura.getMontoalrecibir()> factura.getTotal()) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.montoalrecibirmayortotal"));
return false;
}
if ((factura.getMontoalrecibir()+ factura.getMontoacuenta())> factura.getTotal()) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.montoacuentamasmontoalrecibirmayortotal"));
return false;
}
if (factura.getEfectivo() < 0) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.efectivomenorquecero"));
return false;
}
if (factura.getEfectivo() < factura.getMontoacuenta()) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.efectivomenorpago"));
return false;
}
if (JsfUtil.isVacio(vendedor.getNombre())) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.seleccioneunvendedor"));
return false;
}
// if (!Objects.equals(factura.getEfectivo(), factura.getPago())) {
// JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.efectivodiferentedelpago"));
// return false;
// }
if (factura.getCondicion().equals("contado") && factura.getSaldo() != 0) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.saldodebesercerocontado"));
return false;
}
Boolean foundArticuloEmpty = false;
Boolean foundCantidadEmpty = false;
for (Facturadetalle o : facturadetalleList) {
if (o.getArticulo() == null) {
foundArticuloEmpty = true;
} else {
if (o.getCantidad() == 0) {
foundCantidadEmpty = true;
}
}
}
if (foundArticuloEmpty) {
JsfUtil.warningMessage(rf.getMessage("warning.hayarticulosvacios"));
return false;
}
if (foundCantidadEmpty) {
JsfUtil.warningMessage(rf.getMessage("warning.haycantidadescero"));
return false;
}
return true;
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return false;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="showTotales()">
private void showTotales() {
try {
Double itbms = loginController.getConfiguracion().getItbms();
factura.setSubtotal(0.0);
factura.setItbms(0.0);
factura.setDescuento(0.0);
factura.setTotal(0.0);
facturadetalleList.forEach((fd) -> {
factura.setSubtotal(factura.getSubtotal() + (fd.getPrecio() * fd.getCantidad()));
});
factura.setSubtotal(JsfUtil.redondear(factura.getSubtotal(), 2));
factura.setItbms(factura.getSubtotal() * itbms);
factura.setItbms(JsfUtil.redondear(factura.getItbms(), 2));
factura.setTotal((factura.getSubtotal() + factura.getItbms()) - factura.getDescuento());
//
// factura.setItbms(itbms);
factura.setTotal(JsfUtil.redondear(factura.getTotal(), 2));
factura.setSaldo(factura.getTotal());
factura.setVuelto(0.0);
factura.setSaldo(JsfUtil.redondear(factura.getSaldo(), 2));
factura.setEfectivo(0.0);
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
} // </editor-fold>
//
// public String onCondicionChange() {
// try {
// isContado = false;
// if (factura.getCondicion().equals("contado")) {
// isContado = true;
// }
// if (factura.getCantidadmeses() == 0) {
// factura.setCantidadmeses(13);
// }
// factura.setFechavencimiento(JsfUtil.sumarMesaFechaActual(factura.getCantidadmeses()));
//
// } catch (Exception e) {
// errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
// }
// return "";
// }
//
// <editor-fold defaultstate="collapsed" desc="onCondicionChange()">
public String onCondicionChange() {
try {
showTable = true;
if (isContado) {
factura.setCondicion("contado");
} else {
factura.setCondicion("credito");
}
if (factura.getCantidadmeses() == 0) {
factura.setCantidadmeses(13);
}
factura.setFechavencimiento(JsfUtil.sumarMesaFechaActual(factura.getCantidadmeses()));
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="pagar()">
public String pagar() {
try {
// factura.setPago(JsfUtil.redondear(pago,2));
if (!validarMayorCero()) {
//return "";
}
if ((factura.getDescuento() + factura.getMontoacuenta()) > factura.getTotal()) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.pagomayortotal"));
factura.setMontoacuenta(0.0);
factura.setMontoalrecibir(0.0);
factura.setEfectivo(0.0);
factura.setVuelto(0.0);
if (factura.getDescuento() > factura.getTotal()) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.descuentomayortotal"));
factura.setDescuento(0.0);
}
}
actualizarPagos();
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="descontar()">
public String descontar() {
try {
// factura.setDescuento(JsfUtil.redondear(descuento,2));
if (!validarMayorCero()) {
return "";
}
if ((factura.getDescuento() + factura.getMontoacuenta()) > factura.getTotal()) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.descuentomayortotal"));
factura.setDescuento(0.0);
if (factura.getMontoacuenta()> factura.getTotal()) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.pagomayortotal"));
factura.setMontoacuenta(0.0);
factura.setEfectivo(0.0);
factura.setVuelto(0.0);
}
}
actualizarPagos();
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return "";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="validarPago()">
private Boolean validarMayorCero() {
Boolean valid = true;
try {
if (factura.getDescuento() < 0.0) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.descuentomenorquecero"));
factura.setDescuento(0.0);
valid = false;
}
if (factura.getMontoacuenta()< 0.0) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.pagomenorquecero"));
factura.setMontoacuenta(0.0);
valid = false;
}
if (factura.getMontoalrecibir()< 0.0) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.montoalrecibirmenorcero"));
factura.setMontoalrecibir(0.0);
valid = false;
}
if (factura.getEfectivo() < 0.0) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.pagoefectivomenorquecero"));
factura.setEfectivo(0.0);
valid = false;
}
if ((factura.getEfectivo() > 0.0)) {
if ((factura.getEfectivo() < factura.getMontoacuenta())) {
JsfUtil.warningDialog(rf.getAppMessage("warning.view"), rf.getMessage("warning.efectivomenorpago"));
factura.setEfectivo(0.0);
factura.setVuelto(0.0);
valid = false;
}
}
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
return valid;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="actualizarPagos()">
private void actualizarPagos() {
try {
if (factura.getEfectivo() <= 0) {
factura.setEfectivo(0.0);
factura.setVuelto(0.0);
} else {
factura.setVuelto(factura.getEfectivo() - factura.getMontoacuenta());
}
factura.setSaldo(factura.getTotal() - (factura.getMontoacuenta()+ factura.getDescuento()));
factura.setVuelto(JsfUtil.redondear(factura.getVuelto(), 2));
factura.setSaldo(JsfUtil.redondear(factura.getSaldo(), 2));
} catch (Exception e) {
errorServices.errorMessage(nameOfClass(), nameOfMethod(), e.getLocalizedMessage());
}
}
// </editor-fold>
}
Last updated
Was this helpful?