py.com.palermo.servicioarthy.impl.gestioncomercial.PortalGeneralService.java Source code

Java tutorial

Introduction

Here is the source code for py.com.palermo.servicioarthy.impl.gestioncomercial.PortalGeneralService.java

Source

/*
 * 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 py.com.palermo.servicioarthy.impl.gestioncomercial;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import py.com.palermo.servicioarthy.modelo.AltaCliente;
import py.com.palermo.servicioarthy.impl.gestioncomercial.modelo.Vendedor;
import py.com.palermo.servicioarthy.interfaz.AccesoDenegadoException;
import py.com.palermo.servicioarthy.modelo.Chequesdiferidos;
import py.com.palermo.servicioarthy.modelo.Cobranza;
import py.com.palermo.servicioarthy.modelo.Cobranzaaplicacionpago;
import py.com.palermo.servicioarthy.modelo.Cobranzadetalle;
import py.com.palermo.servicioarthy.modelo.Devolucion;
import py.com.palermo.servicioarthy.modelo.DevolucionDetalle;
import py.com.palermo.servicioarthy.modelo.Documento;
import py.com.palermo.servicioarthy.modelo.Encryptador;
import py.com.palermo.servicioarthy.modelo.Encuesta;

import py.com.palermo.servicioarthy.modelo.Factura;
import py.com.palermo.servicioarthy.modelo.FacturaAplicacionPago;
import py.com.palermo.servicioarthy.modelo.FacturaCobro;
import py.com.palermo.servicioarthy.modelo.FacturaDetalle;
import py.com.palermo.servicioarthy.modelo.Feriado;
import py.com.palermo.servicioarthy.modelo.LogOperacion;
import py.com.palermo.servicioarthy.modelo.Meta;
import py.com.palermo.servicioarthy.modelo.Pdvmovil;
import py.com.palermo.servicioarthy.modelo.Relevamiento;
import py.com.palermo.servicioarthy.modelo.RespuestaEncuesta;
import py.com.palermo.servicioarthy.modelo.Usuario;
import py.com.palermo.servicioarthy.modelo.VersionApp;
import py.com.palermo.servicioarthy.response.ChequesDiferidosResponse;
import py.com.palermo.servicioarthy.response.EncuestaResponse;
import py.com.palermo.servicioarthy.response.FacturasResponse;
import py.com.palermo.servicioarthy.response.FeriadoResponse;

/**
 *
 * @author cromero
 */
@Stateless
public class PortalGeneralService {

    @PersistenceContext(unitName = "PortalGeneralPU")
    private EntityManager em;

    public void guarda(Object entity) {

        em.merge(entity);
    }

    public void setRespuestaEncuesta(RespuestaEncuesta r) {
        if (r.getFechaCadena() != null) {
            LocalDateTime localDateTime = LocalDateTime.parse(r.getFechaCadena(),
                    DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
            r.setFecha(localDateTime.toDate());
        }
        guarda(r);
    }

    public void setCliente(AltaCliente c) {
        AltaCliente a = null;
        try {
            a = (AltaCliente) em
                    .createQuery("SELECT a FROM AltaCliente a WHERE a.sucursalId = ?1 AND a.codigo = ?2")
                    .setParameter(1, c.getSucursalId()).setParameter(2, c.getCodigo()).getSingleResult();
        } catch (Exception e) {

        }

        if (a == null) {
            if (c.getClasificacionId() != null && c.getClasificacionId().compareTo(BigInteger.ZERO) == 0) {
                c.setClasificacionId(null);
            }

            if (c.getZonaId() != null && c.getZonaId().compareTo(BigInteger.ZERO) == 0) {
                c.setClasificacionId(null);
            }
            System.out.println("El cliente es nuevo");
            em.merge(c);
        } else {
            System.out.println("El cliente ya existe, y va a actualizar");
            /*a.setRazonsocial(c.getRazonsocial());
            a.setNombreComercial(c.getNombreComercial());
            a.setTelefono(c.getTelefono());
            a.setRuc(c.getRuc());
            a.setDireccion(c.getDireccion());
                
            a.setEstadoDescarga(c.getEstadoDescarga());
            a.setObservacion(c.getObservacion());
            a.setCanalId(c.getCanalId());
            a.setVisitasDias(c.getVisitasDias());
            a.setVisitasOrden(c.getVisitasOrden());*/
            a.setFotoUrl(c.getFotoUrl());
            a.setGpsLat(c.getGpsLat());
            a.setGpsLong(c.getGpsLong());
            em.merge(a);
        }

    }

    public FacturasResponse getFacturasPendientes(String usuario, Vendedor v) {
        FacturasResponse R = new FacturasResponse();
        Usuario u = null;
        try {
            u = (Usuario) em.createQuery("SELECT u FROM Usuario u WHERE u.username = ?1 AND u.estado = 'ACTIVO'")
                    .setParameter(1, usuario).getSingleResult();
        } catch (Exception e) {
        }

        if (u != null && u.getRolcustom() != null) {

            //List<Vendedor> vendedores = getVendedoresDeRef(u.getReferenciaExterna());
            List<Factura> facturas = getFacturasPendientesPorVendedor(v);
            //            switch (u.getRolcustom().getNombre()) {
            //                case "Cobrador":
            //                    facturas = getFacturasPendientesDeCobrador(vendedores);
            //                    break;
            //                case "Vendedor":
            //                    if (vendedores != null && !vendedores.isEmpty()) {
            //                        facturas = 
            //                    }
            //                    break;
            //            }

            if (facturas != null) {
                R.setFacturas(facturas.toArray(new Factura[facturas.size()]));
                R.setCodRetorno(UtilCons.COD_EXITO);
                R.setMensaje(UtilCons.MENSAJE_EXITO);
            } else {
                R.setCodRetorno(UtilCons.COD_ERROR);
                R.setMensaje("No hay facturas pendientes");
            }
        }
        return R;
    }

    public FeriadoResponse getFeriados(String usuario) {
        FeriadoResponse R = new FeriadoResponse();
        Usuario u = null;
        try {
            u = (Usuario) em.createQuery("SELECT u FROM Usuario u WHERE u.username = ?1 AND u.estado = 'ACTIVO'")
                    .setParameter(1, usuario).getSingleResult();
        } catch (Exception e) {
        }

        List<Feriado> feriados = getFeriados();

        if (feriados != null) {
            R.setFeriados(feriados.toArray(new Feriado[feriados.size()]));
            R.setCodRetorno(UtilCons.COD_EXITO);
            R.setMensaje(UtilCons.MENSAJE_EXITO);
        } else {
            R.setCodRetorno(UtilCons.COD_ERROR);
            R.setMensaje("No hay feriados cargados");
        }

        return R;
    }

    public EncuestaResponse getEncuestas(String usuario) {
        EncuestaResponse R = new EncuestaResponse();
        Usuario u = null;
        try {
            u = (Usuario) em.createQuery("SELECT u FROM Usuario u WHERE u.username = ?1 AND u.estado = 'ACTIVO'")
                    .setParameter(1, usuario).getSingleResult();
        } catch (Exception e) {
        }

        List<Encuesta> encuestas = getEncuestas();

        if (encuestas != null) {
            R.setEncuestas(encuestas.toArray(new Encuesta[encuestas.size()]));
            R.setCodRetorno(UtilCons.COD_EXITO);
            R.setMensaje(UtilCons.MENSAJE_EXITO);
        } else {
            R.setCodRetorno(UtilCons.COD_ERROR);
            R.setMensaje("No hay encuestas cargadas");
        }
        return R;
    }

    public List<Vendedor> getVendedoresDeRef(String refExterna) {
        List<Vendedor> R = new ArrayList<>();
        String[] vds = refExterna.split(";");

        for (String s : vds) {
            String[] vd = s.split(",");

            Short idEmpresa = Short.valueOf(vd[0]);
            Short idSucursal = Short.valueOf(vd[1]);
            Short idVendedor = Short.valueOf(vd[2]);

            R.add(new Vendedor(idEmpresa, idSucursal, idVendedor));
        }
        return R;
    }

    public List<Factura> getFacturasPendientesDeCobrador(List<Vendedor> vendedores) {
        List<Factura> R = new ArrayList<>();
        for (Vendedor v : vendedores) {
            List<Factura> facturas = getFacturasPendientesPorVendedor(v);
            if (facturas != null && !facturas.isEmpty()) {
                R.addAll(facturas);
            }
        }
        return R;
    }

    public List<Factura> getFacturasPendientesPorVendedor(Vendedor v) {
        List<Factura> R = new ArrayList<>();
        if (v != null) {
            R = em.createQuery(
                    "SELECT f from Factura f WHERE f.pendiente = 'S' AND f.puntoDeExpedicion = ?1 AND f.sucursalId = ?2")
                    .setParameter(1, v.getVendedorpuntoexpedicionnro()).setParameter(2, v.getSucursalesid())
                    .getResultList();
        }
        return R;
    }

    public List<Feriado> getFeriados() {
        List<Feriado> R = new ArrayList<>();

        R = em.createQuery("SELECT f from Feriado f WHERE f.estado = 'ACTIVO'").getResultList();

        return R;
    }

    public List<Encuesta> getEncuestas() {
        return em.createQuery(
                "SELECT e from Encuesta e WHERE e.estado = 'ACTIVO' AND e.estadoEncuesta <> 'FINALIZADO' AND :fecha BETWEEN e.fechaInicio AND e.fechaFin")
                .setParameter("fecha", new Date()).getResultList();
    }

    public ChequesDiferidosResponse getChequesDiferidos(String usuario, Vendedor v) {
        ChequesDiferidosResponse R = new ChequesDiferidosResponse();
        Usuario u = null;
        try {
            u = (Usuario) em.createQuery("SELECT u FROM Usuario u WHERE u.username = ?1 AND u.estado = 'ACTIVO'")
                    .setParameter(1, usuario).getSingleResult();
        } catch (Exception e) {
        }

        if (u != null && u.getRolcustom() != null) {

            List<Chequesdiferidos> chequesDiferidos = getChequesDiferidosPorVendedor(v);

            if (chequesDiferidos != null) {
                R.setChequesDiferidos(chequesDiferidos.toArray(new Chequesdiferidos[chequesDiferidos.size()]));
                R.setCodRetorno(UtilCons.COD_EXITO);
                R.setMensaje(UtilCons.MENSAJE_EXITO);
            } else {
                R.setCodRetorno(UtilCons.COD_ERROR);
                R.setMensaje("No hay Cheques Diferidos");
            }
        }
        return R;
    }

    public List<Chequesdiferidos> getChequesDiferidosPorVendedor(Vendedor v) {
        List<Chequesdiferidos> R = new ArrayList<>();

        if (v != null) {
            /*R = em.createQuery("SELECT c from Chequesdiferidos c WHERE c.vendedorid = ?1 AND c.sucursalid = ?2")
            .setParameter(1, v.getVendedorid())
            .setParameter(2, v.getSucursalesid())
            .getResultList();*/

            R = em.createQuery("SELECT c from Chequesdiferidos c WHERE c.vendedorid = ?1")
                    .setParameter(1, v.getVendedorid()).getResultList();

        }

        return R;
    }

    public Factura getFacturaPorHash(int hash) {
        Factura f = null;
        try {
            f = (Factura) em.createQuery("SELECT f FROM Factura f where f.codigoHash = ?1").setParameter(1, hash)
                    .getSingleResult();
            System.out.println("===========================================================");
            System.out.println("GET FACTURA POR HASH, Encontr ID: " + f.getId());
            System.out.println("GET FACTURA POR HASH, Encontr HASH: " + f.getCodigoHash());
        } catch (Exception e) {
            System.out.println("GET FACTURA POR HASH: " + e.getMessage());
        }
        return f;
    }

    public String setFactura(Factura f) {

        if (f.getFechaCadena() != null) {
            LocalDateTime localDateTime = LocalDateTime.parse(f.getFechaCadena(),
                    DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
            f.setFecha(localDateTime.toDate());
        }

        Factura vivo = em.find(Factura.class, f.getId());
        if (vivo != null && vivo.getEstadoDescarga().compareToIgnoreCase("T") == 0) {
            return f.getId();
        }

        for (FacturaCobro c : f.getCobros()) {
            if (c.getDocumentoId() != null && c.getDocumentoId().compareToIgnoreCase("0") == 0) {
                c.setDocumentoId(null);
            }
        }
        f.setEstadoDescarga("N");
        em.merge(f);
        return f.getId();
    }

    public String setLog(LogOperacion l) {

        if (l.getFechaCadena() != null) {
            LocalDateTime localDateTime = LocalDateTime.parse(l.getFechaCadena(),
                    DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
            l.setFecha(localDateTime.toDate());
        }

        String R = l.getId() + "";
        l.setId(null);
        em.persist(l);
        return R;
    }

    public String setVersion(VersionApp v) {
        em.merge(v);
        return v.getTelefonoid();
    }

    public String setRelevamiento(Relevamiento r) {

        if (r.getFechaCadena() != null) {
            LocalDateTime localDateTime = LocalDateTime.parse(r.getFechaCadena(),
                    DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
            r.setFecha(localDateTime.toDate());
        }

        String R = r.getId() + "";
        Relevamiento rbd = null;
        try {
            rbd = (Relevamiento) em.createQuery("SELECT r FROM Relevamiento r where r.hashKey = ?1")
                    .setParameter(1, r.getHashKey()).getSingleResult();
        } catch (Exception e) {

        }

        if (rbd != null && rbd.getEstadoDescarga().compareToIgnoreCase("T") == 0) {
            return R;
        }

        if (rbd == null) {
            r.setId(null);
            r.setEstadoDescarga("N");
            em.persist(r);
        } else {
            rbd.setMotivoNoVentaId(r.getMotivoNoVentaId());
            rbd.setEstadoAnulacion(r.getEstadoAnulacion());
            rbd.setEstadoDescarga("N");
            em.merge(rbd);
        }

        return R;
    }

    public String setDevolucion(Devolucion d, List<DevolucionDetalle> detalles) {

        if (d.getFechaCadena() != null) {
            LocalDateTime localDateTime = LocalDateTime.parse(d.getFechaCadena(),
                    DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
            d.setFecha(localDateTime.toDate());
        }

        String R = d.getId() + "";
        Devolucion rbd = null;
        try {
            rbd = (Devolucion) em.createQuery("SELECT d FROM Devolucion d where d.hashKey = :hash")
                    .setParameter("hash", d.getHashKey().trim()).getSingleResult();
        } catch (Exception e) {

        }

        if (rbd != null && rbd.getEstadoDescarga().compareToIgnoreCase("T") == 0) {
            return R;
        }

        d.setEstadoDescarga("N");
        if (rbd == null) {
            System.out.println("Detalles devolucion: " + detalles);
            d.setId(null);
            System.out.println("Paso 1:");

            em.persist(d);
            em.flush();
            em.refresh(d);

            for (DevolucionDetalle dt : detalles) {
                dt.setId(null);
                dt.setDevolucionId(d.getId());
                em.persist(dt);
            }
        } else {
            rbd = copiaDevolucion(rbd, d);
            rbd.setEstadoDescarga("N");
            em.merge(rbd);
            em.flush();
            em.refresh(rbd);

            em.createQuery("DELETE FROM DevolucionDetalle d WHERE d.devolucionId = ?1").setParameter(1, rbd.getId())
                    .executeUpdate();

            for (DevolucionDetalle dt : detalles) {
                dt.setId(null);
                dt.setDevolucionId(rbd.getId());
                em.persist(dt);
            }
        }

        return R;
    }

    private Devolucion copiaDevolucion(Devolucion o1, Devolucion o2) {
        o1.setEmpresaId(o2.getEmpresaId());
        o1.setSucursalId(o2.getSucursalId());
        o1.setVendedorId(o2.getVendedorId());
        o1.setEstadoDescarga(o2.getEstadoDescarga());
        o1.setEstadoEliminacion(o2.getEstadoEliminacion());
        o1.setClienteId(o2.getClienteId());
        o1.setFecha(o2.getFecha());
        o1.setFechaCadena(o2.getFechaCadena());
        o1.setGpsLat(o2.getGpsLat());
        o1.setGpsLong(o2.getGpsLong());
        o1.setCantidadGruesas(o2.getCantidadGruesas());
        o1.setHashKey(o2.getHashKey());

        return o1;
    }

    public Cobranza setCobranza(Cobranza c, List<Cobranzadetalle> detalles,
            List<Cobranzaaplicacionpago> aplicaciones) {

        if (c.getFechaCadena() != null) {
            LocalDateTime localDateTime = LocalDateTime.parse(c.getFechaCadena(),
                    DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
            c.setFecha(localDateTime.toDate());
        }

        Cobranza vivo = em.find(Cobranza.class, c.getId());
        if (vivo != null && vivo.getEstadodescarga().compareTo('T') == 0) {
            return c;
        }

        em.createQuery("DELETE FROM Cobranzadetalle c WHERE c.cobranzaid = ?1").setParameter(1, c.getId())
                .executeUpdate();

        em.createQuery("DELETE FROM Cobranzaaplicacionpago c WHERE c.cobranzaid = ?1").setParameter(1, c.getId())
                .executeUpdate();

        c.setEstadodescarga('N');
        String[] arrayId = c.getId().split(",");
        short sucursalId = Short.valueOf(arrayId[1]);
        c.setSucursalId(sucursalId);

        em.merge(c);
        for (Cobranzadetalle cd : detalles) {
            if (cd.getFechaCadena() != null) {
                LocalDateTime localDateTime = LocalDateTime.parse(cd.getFechaCadena(),
                        DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
                cd.setFechaFactura(localDateTime.toDate());
            }

            cd.setCobranza(c);
            em.merge(cd);
        }

        for (Cobranzaaplicacionpago cap : aplicaciones) {

            if (cap.getFechaCadena() != null) {
                LocalDateTime localDateTime = LocalDateTime.parse(cap.getFechaCadena(),
                        DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
                cap.setValorfecha(localDateTime.toDate());
            }

            cap.setCobranza(c);
            em.merge(cap);
        }
        return c;
    }

    public Cobranzaaplicacionpago setCobranzaAplicacionPago(Cobranzaaplicacionpago c) {

        if (c.getFechaCadena() != null) {
            LocalDateTime localDateTime = LocalDateTime.parse(c.getFechaCadena(),
                    DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
            c.setValorfecha(localDateTime.toDate());
        }

        em.merge(c);
        return c;
    }

    public String registraDispositivo(Pdvmovil p) {
        String R = "400";
        if (p != null) {
            try {
                if (yaEstaRegistrado(p.getDeviceid())) {
                    return "300";
                }

                em.merge(p);
                R = "200";
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return R;
    }

    public void setDocmentos(Documento[] documentos) {
        for (Documento d : documentos) {
            String[] arrayId = d.getId().split(",");
            Integer sucursalId = Integer.valueOf(arrayId[1]);
            d.setSucursalesId(sucursalId);
            em.merge(d);
        }
    }

    public void setDocumento(Documento d) {
        String[] arrayId = d.getId().split(",");
        Integer sucursalId = Integer.valueOf(arrayId[1]);
        d.setSucursalesId(sucursalId);
        em.merge(d);

    }

    public void setFacturas(Factura[] facturas) {
        for (Factura f : facturas) {
            f.getCodigoHash();
            em.merge(f);
        }
    }

    private boolean yaEstaRegistrado(String deviceId) {
        boolean R = false;

        try {
            em.createQuery("SELECT p FROM Pdvmovil p where p.deviceid = ?1").setParameter(1, deviceId)
                    .getSingleResult();
            R = true;
        } catch (Exception e) {
        }
        return R;
    }

    private boolean estaActivo(String deviceId) {
        boolean R = false;

        try {
            em.createQuery("SELECT p FROM Pdvmovil p where p.deviceid = ?1 AND p.estado = ?2")
                    .setParameter(1, deviceId).setParameter(2, "ACTIVO").getSingleResult();
            R = true;
        } catch (Exception e) {
        }
        return R;
    }

    public String verifica(String deviceId) {

        if (!yaEstaRegistrado(deviceId)) {
            return "300";
        }

        if (!estaActivo(deviceId)) {
            return "400";
        }

        return "200";
    }

    public boolean login(String usuario, String password) {
        boolean R = false;

        Usuario u = null;
        try {
            String encrypt = Encryptador.encrypta(password);

            u = (Usuario) em.createQuery("SELECT u FROM Usuario u WHERE u.username = ?1 AND u.password = ?2")
                    .setParameter(1, usuario).setParameter(2, encrypt).getSingleResult();

            R = true;
        } catch (Exception e) {
        }

        return R;
    }

    public String getRefVendedor(String nombreUsuario) {
        String R = null;
        Usuario u = null;
        try {

            u = (Usuario) em.createQuery("SELECT u FROM Usuario u WHERE UPPER(u.username) = ?1")
                    .setParameter(1, nombreUsuario.trim().toUpperCase()).getSingleResult();

            if (u != null) {
                R = u.getReferenciaExterna();
            }

        } catch (Exception e) {
        }

        return R;
    }

    public String getRolUsuario(String nombreUsuario) {
        String R = null;
        Usuario u = null;
        try {

            u = (Usuario) em.createQuery("SELECT u FROM Usuario u WHERE UPPER(u.username) = ?1")
                    .setParameter(1, nombreUsuario.trim().toUpperCase()).getSingleResult();

            if (u != null) {
                R = u.getRolcustom() != null ? u.getRolcustom().getNombre() : null;
            }

        } catch (Exception e) {
        }

        return R;
    }

    public List<Meta> getMetas(Vendedor v) throws AccesoDenegadoException {

        List<Meta> R = new ArrayList<>();
        if (v != null) {
            String refExterna = v.getEmpresasid() + "," + v.getSucursalesid() + "," + v.getVendedorid();
            R = em.createQuery("SELECT m from Meta m  WHERE m.estado = 'ACTIVO' AND m.refExterna = ?1")
                    .setParameter(1, refExterna).getResultList();
        }
        return R;
    }

    public Meta getMetaActual(Vendedor v) throws AccesoDenegadoException {

        Meta R = null;
        if (v != null) {

            String refExterna = v.getEmpresasid() + "," + v.getSucursalesid() + "," + v.getVendedorid();
            LocalDate localDate = new LocalDate();
            int mes = localDate.getMonthOfYear();
            int anio = localDate.getYear();
            try {
                R = (Meta) em.createQuery(
                        "SELECT m from Meta m  WHERE m.estado = 'ACTIVO' AND m.refExterna = ?1 AND m.mes = ?2 AND m.anio = ?3")
                        .setParameter(1, refExterna).setParameter(2, mes).setParameter(3, anio).getSingleResult();

                R.setDiasTrabajados(ConsultasPalermo.calculaDiasTrabajados(new Date()));
                R.setEmpresaId(v.getEmpresasid());
                R.setSucursalId(v.getSucursalesid());
                R.setVendedorId(new Integer(v.getVendedorid()));
                R.setCantidadAlcanzada(0d);

            } catch (Exception e) {
                System.err.println("No hay metas para este vendedor: " + e.getMessage());
            }
        }
        return R;
    }

    public List<Factura> getFacturasNoDescardas(Vendedor v) throws AccesoDenegadoException {

        List<Factura> R = new ArrayList<>();
        if (v != null) {
            R = em.createQuery(
                    "SELECT f from Factura f WHERE f.estadoDescarga = 'N' AND f.vendedorId = ?1 and f.sucursalId = ?2")
                    .setParameter(1, v.getVendedorid()).setParameter(2, v.getSucursalesid()).getResultList();
        }
        return R;
    }

    public List<Documento> getDocumentosNoDescardos(Vendedor v) throws AccesoDenegadoException {

        List<Documento> R = new ArrayList<>();
        if (v != null) {
            R = em.createQuery(
                    "SELECT d from Documento d WHERE d.estadoDescarga = 'N' AND d.vendedorId = ?1 AND d.estadoEliminacion = 'N' AND d.sucursalesId= ?2")
                    .setParameter(1, v.getVendedorid()).setParameter(2, v.getSucursalesid()).getResultList();
        }

        return R;
    }

    public Documento getDocumento(Vendedor v, String documentoId) throws AccesoDenegadoException {

        Documento R = null;
        if (v != null) {
            try {
                R = (Documento) em.createQuery(
                        "SELECT d from Documento d WHERE d.estadoDescarga = 'N' AND d.vendedorId = ?1 AND d.estadoEliminacion = 'N' AND d.id=?2 AND d.sucursalesId= ?3")
                        .setParameter(1, v.getVendedorid()).setParameter(2, documentoId)
                        .setParameter(3, v.getSucursalesid()).getSingleResult();
            } catch (Exception e) {
                System.out.println(
                        "py.com.palermo.servicioarthy.impl.gestioncomercial.PortalGeneralService.getDocumento(): "
                                + e.getMessage());
            }

        }

        return R;
    }

    public List<FacturaDetalle> getFacturasDetallesNoDescardas(Vendedor v) throws AccesoDenegadoException {

        List<FacturaDetalle> R = new ArrayList<>();
        if (v != null) {
            R = em.createQuery(
                    "SELECT f from FacturaDetalle f WHERE f.factura.estadoDescarga = 'N' AND f.factura.vendedorId = ?1 AND f.factura.sucursalId = ?2")
                    .setParameter(1, v.getVendedorid()).setParameter(2, v.getSucursalesid()).getResultList();
        }
        return R;
    }

    public List<FacturaCobro> getFacturasCobrosNoDescardas(Vendedor v) throws AccesoDenegadoException {

        List<FacturaCobro> R = new ArrayList<>();
        if (v != null) {
            R = em.createQuery(
                    "SELECT f from FacturaCobro f WHERE f.factura.estadoDescarga = 'N' AND f.factura.vendedorId = ?1 AND f.factura.sucursalId = ?2")
                    .setParameter(1, v.getVendedorid()).setParameter(2, v.getSucursalesid()).getResultList();
        }
        return R;
    }

    public List<FacturaAplicacionPago> getFacturasAplicacionesNoDescardas(Vendedor v)
            throws AccesoDenegadoException {

        List<FacturaAplicacionPago> R = new ArrayList<>();
        if (v != null) {
            R = em.createQuery(
                    "SELECT f from FacturaAplicacionPago f WHERE f.factura.estadoDescarga = 'N' AND f.factura.vendedorId = ?1 AND f.factura.sucursalId = ?2")
                    .setParameter(1, v.getVendedorid()).setParameter(2, v.getSucursalesid()).getResultList();
        }
        return R;
    }

    public List<Relevamiento> getRelevamientosNoDescardos(Vendedor v) throws AccesoDenegadoException {

        List<Relevamiento> R = new ArrayList<>();
        if (v != null) {
            R = em.createQuery(
                    "SELECT r from Relevamiento r WHERE r.estadoDescarga = 'N' AND r.vendedorId = ?1 AND r.empresaId = ?2 AND r.sucursalId = ?3 AND r.estadoAnulacion = 'N'")
                    .setParameter(1, v.getVendedorid()).setParameter(2, v.getEmpresasid())
                    .setParameter(3, v.getSucursalesid()).getResultList();
        }
        return R;
    }

    public List<Devolucion> getDevolucionesNoDescargadas(Vendedor v) throws AccesoDenegadoException {

        List<Devolucion> R = new ArrayList<>();
        if (v != null) {
            R = em.createQuery(
                    "SELECT r from Devolucion r WHERE r.estadoDescarga = 'N' AND r.vendedorId = ?1 AND r.estadoEliminacion = 'N' AND r.empresaId = ?2 AND r.sucursalId = ?3")
                    .setParameter(1, v.getVendedorid()).setParameter(2, v.getEmpresasid())
                    .setParameter(3, v.getSucursalesid()).getResultList();
        }
        return R;
    }

    public List<DevolucionDetalle> getDevolucionesDetalles(Integer devolucionId) throws AccesoDenegadoException {
        List<DevolucionDetalle> R = new ArrayList<>();

        R = em.createQuery("SELECT r from DevolucionDetalle r WHERE r.devolucionId = ?1")
                .setParameter(1, devolucionId).getResultList();

        return R;
    }

    public List<DevolucionDetalle> getDevolucionesDetalles(String devolucionHashKey)
            throws AccesoDenegadoException {
        List<DevolucionDetalle> R = new ArrayList<>();

        R = em.createQuery("SELECT r from DevolucionDetalle r WHERE r.devolucionHashKey = ?1")
                .setParameter(1, devolucionHashKey).getResultList();

        return R;
    }

    public List<Cobranza> getCobranzasNoDescardas(Vendedor v) throws AccesoDenegadoException {

        List<Cobranza> R = new ArrayList<>();
        if (v != null) {
            R = em.createQuery(
                    "SELECT c from Cobranza c WHERE c.estadodescarga = 'N' AND c.vendedorid = ?1 AND c.estadoanulacion = 'N' AND c.sucursalId = ?2")
                    .setParameter(1, v.getVendedorid()).setParameter(2, v.getSucursalesid()).getResultList();
        }
        return R;
    }

    public List<Cobranzadetalle> getCobranzasDetalles(Cobranza c) {

        List<Cobranzadetalle> R = new ArrayList<>();
        if (c != null) {
            R = em.createQuery("SELECT c from Cobranzadetalle c WHERE c.cobranza = ?1").setParameter(1, c)
                    .getResultList();
        }
        return R;
    }

    public List<Cobranzaaplicacionpago> getCobranzasAplicaciones(Cobranza c) {

        List<Cobranzaaplicacionpago> R = new ArrayList<>();
        if (c != null) {
            R = em.createQuery("SELECT c from Cobranzaaplicacionpago c WHERE c.cobranza = ?1").setParameter(1, c)
                    .getResultList();
        }
        return R;
    }

}