trucosjakartaee
  • Introduction
  • Creditos
  • Jar to Exe
  • Primefaces security
  • Primefaces Responsive
  • Leer archivos en una linea de codigo
  • Logger Crear archivo JSOn
  • Cifrar Archivos y Licencias
    • Cifrar Archivos y Encriptar Textos
    • Licencias
  • JSON-P Leer arhivos
  • Apache Derby
  • Migrar a Java 11
  • jmoordbjsf
    • 1. Controller
      • 1.1 Definicion
      • 1.2 before/after()
      • 1.3 Parametros internos
      • 1.2 init()
        • 1.2.1 Obtener el action en el init()
        • 1.2.3 Asignar el search en el init()
      • 1.3 searchBy()
      • 1.4 <jmoordbjsf:search>
      • 1.5<jmoordbjsf:searchBetweenDate> Busquedas entre fechas.
        • 1.5.1 <jmoordbjsf:searchBetweenDates con <jmoordbjsf:autocomplete>
      • 1.6 handleSelect de autocomplete en list.xhtml
      • 1.7 <p:selectOneMenu> eventos en list.xhtml
      • 1.8 move()
    • 2. Componentes
      • 2.1 <jmoordbjsf:ccstimeline>
      • 2.2 <jmoordbjsf:paginator>
        • 2.2.1 paginator con impresion
    • 3. Historial de revisión
  • Reportes
    • OpenPDF
      • Enlaces
      • Introduccion
      • Reportes con ReportUtils.java
      • Reporte con ReportUtils y <jmoordbjsf:paginator>
      • Turoriales
      • Informe con 6 columnas
      • Tamaño de pagina
      • Centrar en el reporte
      • Margenes
      • Fuentes en las celdas
      • Formatear Fechas
      • Imagenes
      • grupos
      • subreportes
      • firmar pdf
      • Agregar autor al pdf
      • Reporte simple
    • iReport
    • Imprimir condicional
    • DynamicReports
    • iText
    • PDFBox
    • JaspertReport from code
    • Nerval Reports
    • DynamicJasper
    • Eclipse birt
  • Overview
    • jmoordb web
      • Autoincrementable
        • Autoincrementable
        • Generar autoincrementable para múltiples tiendas relacionadas sin @Referenced
        • Login
          • Login simple
          • Login con Multiples roles
          • Obtener el Ip del cliente
          • Generar el UUID
          • Session Expirada redirigir automaticamente
        • Password
          • Cambiar password
          • Encriptar password
        • Usuario
          • Usuario con un solo Rol
          • Usuario con multiples roles
    • JavaEE
      • Java Security EE
        • Validar paginas
      • Email
        • Enviar emails formateados
        • CompletableFuture para envio de emails
        • Emails con copias cc, bcc
      • JPA
        • <p:autocomplete> con JPA
        • <p:autocomplete> JPA con eventos
        • <p:autocomplete> JPA con Integer
        • <p:autocomplete> JPA con scroll
        • <p:autocomplete> con Converter
    • Java Server Faces
      • eliminar bordes de <p:fieldSet>
      • reset
      • commandButton verdes
      • JsfUtil.updateJSFComponent(componente)
      • <p:growl> Centrado
      • <p:fieldSet>
      • Actualizar componente primefaces desde codigo Java
      • Codigo barra/QR
        • codigosbarra
        • Generar/Leer Codigo QR
        • Scanner un codigo QR con primefaces
      • Barra de progreso y bloqueo para procesos muy largos
      • Dialogo
        • Centrar Dialog
        • Cerrar dialogo desde código
        • Invocar dialogo desde codigo
        • dialogconfirm
        • Cambiar los colores del Dialog
        • Modal
        • Dialogo con <p:schedule>
      • Menu
        • <b:navCommandLink/>
        • Eventos de menu
        • CommandLink con parametros en menu
        • Usar <b:flyOutMenu>
        • Menus dinámicos mediante <p:repeat
        • Filtrar desde el menu dinamico
      • Message
        • Cerrar automaticamente messages
      • inputText
        • inputTextArea Scroll
        • Bloquear tecla Enter inputText
        • Validar rangos
        • Convertir a mayusculas
        • eventos en el inputText
      • outputLabel
        • Mostrar un icono en un outputLabel
      • selectOneMenu
        • <b:selectOneMenu String
        • <b:selectOneMenu> eventos Ajax
        • <p:selectOneMenu eventos
        • <b:selectOneMenu sin converter
        • concatenar String
        • <f:selectItem>
        • <b:selectOneMenu relacionados
        • <b:selectOneMenu> simple
        • <b:selectOneMenu> formulario view.xhtml
        • mesSelectOneMenu
        • Ajustar el tamaño
      • Datatable
        • DataTable Agrupados y rowExpansion
        • Saber que columna se edita
        • tamaño de columnas
        • Marcar como vistos
        • <p:datatable> con <p:autocomplete>
        • <p:repeat> con dataTable
        • <p:repeat> en un componente
        • <p:datatable> con exporter
        • Mostrar un datatable dentro de un dialogo
        • Filas coloreadas
        • Reflexion para contar valores en un datatable
        • Datatable con paginacion
        • <p:datatable> expandableRowGroups
        • <p:datatable> columnas agrupadas
        • color columna
        • <b:datatable> con dialogs
        • Busquedas
        • <b:datatable> con colores en las filas
        • <b:datatable> filtrado por el Agente seleccionado
        • <b:datatable> Filtrado por el usuario logueado
        • <b:dataTable con repeat para atributos List<>
      • Autocomplete
        • autocomplete insertar nuevos valores
        • Componente autocomplete
        • Autocomplete con findRegex() Expresiones Regulares
        • <p:autocomplete> multiple
        • Autocomplete con findText
        • Autocomplete relacionados
        • <p:autocomplete> con Integer y String
        • Autocomplete con dropdwon
        • Autocomplete con minQueryLength=
        • Autocomplete Relacionados con dropdown (Provincia- distrito)
        • Cambiar color <p:autocomplete>
        • <p:autocomplete> Multiples relacionados
        • <p:autocomplete Usuarios por multiples Roles
        • <p:autocomplete> Multiples dropdown="true" relacionados con
        • <p:autocomplete> con lambda stream
        • Autocomplete
        • Con Rangos de fechas
          • Autocomplete con rangos de fechas excluyendo el registro actual
      • Iconos e imagenes
        • <p:commandLink> con imagenes
        • <p:commandButton> con imagenes
        • <h:graphicImage>
      • Paso de parametros
        • Desde un <p:commandLink>
        • Desde un <p:button>
      • Ajax
        • Eventos
        • Eventos al cargar pagina
      • Datagrid
        • Quitar bordes con poseidon
        • <p:datagrid>
      • Tabs
        • Diseñar tabs
      • Notificaciones
        • Notificaciones
        • Notificaciones en la barra
      • Graficas
        • <p:chart> pie
        • <p:char> pie por varios atributos
      • Ommifaces
        • Untitled
        • Ejecutar Comando
    • Formatos y Fechas
      • Formatear fechas y horas en un String para un datatable
      • Formatear decimales
      • Formatear fecha
      • Formateo de fechas y horas por separado
      • outputLabel formateado
    • Fechas
      • Primer/Ultimo dia en fechas del mes
      • Insertar horas minutos y segundos a una fecha
      • validarRangoFechas
      • Determinar el numero de meses entre fechas
      • Descomponener una fecha
      • Obtener el nombre del dia
      • Calcular dias entre fechas
      • Operaciones con fechas
      • Filtrar por dias Atrasados
      • Fecha actual
      • Primer dia y ultimo dia del mes de la fecha actual
      • Sumar mes a fecha actual
      • Fechas null
      • Conocer si alguien esta de vacaciones
      • Formatear una fecha
      • Si cumple años
      • Filtrar cumpleaños en JPA
      • <a:searchBetweenDate> Filtrar entre Fechas
      • Mostrar los que estan de vacaciones en un mes
      • Calcular numero de días de vacaciones del mes
      • Comparar Fechas
      • Mostrar fecha y hora en un datatable
      • Validar que la Hora no sea cero
      • F iltrar entre fechas de un List<Entity>
      • Búsquedas por Día filterDayWithoutHour()
      • Validar fechas y horas
      • Validar meses superiores en Cierre
      • Primera y ultima fecha del Mes
      • <p:calendar>
        • eventos-en-el-pcalendar
        • Eventos en el <p:calendar> /EntreFechas
        • Eventos en el <p:calendar> entre fechas
      • HoraMinutos formato AM/PM de una fecha
        • Google Calendar
    • Rangos de Fechas
      • Encontrar si esta disponible entre dos fechas en rangos de fechas inicial y final con filtro adicion
      • Buscar una fecha y hora en un rango
      • Actualizar las fechas en rango de dos fechas y validar los disponibles excluyendo el entity actual
      • filterBetweenDatePaginationWithoutHour()Buscar en rangos de fechas excluyendo la hora con paginacion
    • Generales
      • Habilitar Empty
    • Mongodb
      • Combinar bases de datos
      • Referencias en bases datos distintas
      • Crear bases de datos en tiempo de ejecucion
      • Agregar campos autoincrementables, renombrar campos
      • Transacciones
    • Controller
      • Filtrar desde el list.xhtml
      • ChoferController.java
      • ReservadoController.java
      • OrdenController.java
      • ModeloController.java
      • Validar null
    • Formularios
      • Relaciones con atributos no Referenciados
      • Maestro-Detalle Orden de Proveedor a Bodega
      • Dos campos como campo llave
      • Crear registros de entitys diferentes en el mismo formulario
      • Formulario con llave secundaria sin mostrar autoincrementable
      • Cambiar numero de cedula
      • Formulario referenciado (Grupoarticulo->Modelo)
      • Usuario
      • Facturas
        • Factura codigo xhtml
        • FacturaController.java
      • Maestro-Detalle Factura
      • Formulario sin componente new
      • Solo formulario new.xhtml no usar list.xhtml ni el view.xhtml
    • JmoordbLanguages
    • JmoordbResourcesFiles
      • Pasarlos a un services
    • list.xtml
      • Filtrar por un entity Referenciado
      • Formularios con Ordenacion
      • Filtrar por atributos referenciados
      • <a:searchYesNo>
    • Entity
    • Services
    • Blogs
      • Java
      • Mongodb
    • Glassfish
    • PDF
      • Download
    • Links
    • Ubuntu
      • Minimizar aplicaciones en Ubuntu con un solo clic
      • Maven
      • Reiniciar GnomeShell
    • Databases
      • Ranking
    • Tutoriales JavaEE 8
    • Busquedas en List<> Embebidos y Referenciados
      • Buscar en un List<> en cualquier posicion usando and y or
      • Buscar elemento en un List<> Embebido/Referenciado
      • Limpiar autocomplete y otros filtros
      • Filtrar embebidos referenciados de forma inversa
      • Buscar en un List<Viaje> dentro de Solicitud
    • Search
    • Eventos
      • Escuchar eventos
      • Eventos
    • Microservicios
      • Microservicios con Java EE Jakarta
    • Java
      • Copiar Beans
      • List
        • Ordenar una List Java 8
        • Filtrar un List<> con Stream
        • Encontrar un elemento en un List con Lambda/Stream
      • List<Object>
      • Método retorna List<Object>
      • Mock
        • Disenos online
      • Brownies Collections
      • Batch
      • Maven
        • Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.3:exploded (default-cli) on proje
      • NetBeans
        • Colapsar codigo
      • Formatear String
      • Lambda/Stream
      • Filtrar de varias listas
      • stream
      • lambda /stream
      • Patrones de Diseño
        • Builder Desing Pattern
    • Primefaces
      • PhotoCam
        • Tomar foto
      • Schedule
        • <p:scheduler> con paginacion
        • <p:schedule> LazyScheduleModel
        • <p:schedule> con filtros autocomplete
        • <p:schedule> con GMT-5 para Panama
        • <p:schedule> con dialogos
        • Colores en <p:schedule>
        • <p:schedule> con dialogos diferentes en el mismo evento
        • <p:schedule con <p:ajax event="viewChange">
        • <p:schedule> imprimir
      • Dashboard
        • Dashboard basico <p:knob
          • <p:knob>
          • Dashboard con link <p:knob
        • Dashboard <p:knob> <b:bagde>
        • Dashboard con Paneles
      • <p:chips>
        • <p:chips> simple
      • <p:dataGrid
    • Entity Configuración
    • Arquitectura
      • Project ejb
      • Proyecto Web
      • Pasos al crear un entity
      • list.xhtml
      • new.xhtml
      • view.xhtml
    • BitBucket/NetBeans
      • Crear Ramas desde Bitbucket
      • Crear rama desde NetBeans
      • Cambiar ramas desde NetBeans
      • Push a una rama
      • Permisos a una rama
      • Clonar una rama
      • Crear un pull request bitbucket
      • Recuperar una revisión git desde Bitbucket
    • Controller
      • Atributos
      • set/get
      • constructor
      • init
      • preRenderView
      • reset
      • prepare
      • showAll
      • isNew
      • save
      • edit
      • delete
      • deleteAll
      • print
      • printAll
      • handleSelect
      • handleAutocompleteOfListXhtml
      • last
      • first
      • next
      • back
      • skip
      • move
      • clear
      • searchBy(String string)
    • Componentes
      • JsfUtil.updateJsfComponent()
    • Genericos implementar en un Controller
    • LambdaMetaFactory
    • Patrones
    • @Producer Reducir Repository
  • Cierre Mensual
    • Cierre mensual
  • fontAwesome Local
    • fontAwesome Local
  • Componentes
    • Componentes JSF
      • <a:paginatorReport>
      • Distribuir componentes Java Server Faces
      • Crear composite distribuible con Maven
      • Clases como parámetros y métodos en el composite
      • Agregar css
  • LambdaMetaFactory
    • LambdaMetaFactory
      • <jmoordbjsf:Ajax Status>
      • Invocar metodos desde un controller
  • Patrones de Diseño
    • Patrones de Diseño
    • Builder
  • @Producer Reducir Repository
    • @Producer Reducir Repository
    • Validar en el inicio del controller con nuevo esquema
    • AdminFaces
      • include
      • template
      • resources
      • web.xml
    • Cargar archivo propiedades
    • Maven Crear arquetipo en base a un proyecto
      • Configurar path maven
      • archivo settings.xml
      • Crear arquetipo desde NetBeans
      • Crear el arquetipo desde consola
      • Crear el proyecto en base al arquetipo
      • Clonar adminfaces archetype
    • PayaraMicro
    • Archivos de propiedades con adminfaces
  • Web Socket
    • WebSocket
      • Web Socket
        • dependencias
        • web.xml
        • Archivos de configuracion
        • Pushsocket
        • index.xhtml
        • reciver.xhtml
        • Ejecutarlo
      • WebSocket en menu con <:remoteCommand>
        • top.xhtml
        • template.xhtml
        • web.xml
        • Clases
        • ConfigurationContoller.java
        • PushSocket.java
        • Mensajes.java
      • WebSocket con Notificaciones en bases de datos
        • pom.xml
        • web.xml
        • template.xthml
        • top.xhtml
        • index.xhtml
        • LoginController.java
        • PushSocket.java
        • JmoordbNotificationsController.java
        • list.xhtml
        • Enviar notificaciones todos los usuarios
    • Pagina de Inicio en Java EE
    • Control de Viajes
      • Generar pasajeros por viajes
        • validarRangoFechas
    • Vehiculos recomendados
  • DBUtils
  • Archivos Properties
  • MICROSERVICES
    • MICROSERVICES
      • Archivos properties con Producer
      • Archivos Properties con @Inject
Powered by GitBook
On this page

Was this helpful?

  1. Overview
  2. Formularios
  3. Facturas

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>
}
PreviousFactura codigo xhtmlNextMaestro-Detalle Factura

Last updated 6 years ago

Was this helpful?