/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.rjconsultores.ventaboletos.service.impl; import java.util.Calendar; import java.util.List; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.rjconsultores.ventaboletos.dao.PuntoVentaDAO; import com.rjconsultores.ventaboletos.dao.UsuarioUbicacionDAO; import com.rjconsultores.ventaboletos.entidad.Constante; import com.rjconsultores.ventaboletos.entidad.Empresa; import com.rjconsultores.ventaboletos.entidad.FormaPagoDet; import com.rjconsultores.ventaboletos.entidad.Parada; import com.rjconsultores.ventaboletos.entidad.PuntoVenta; import com.rjconsultores.ventaboletos.entidad.Usuario; import com.rjconsultores.ventaboletos.exception.IntegracionException; import com.rjconsultores.ventaboletos.exception.ValidacionCampoException; import com.rjconsultores.ventaboletos.service.ConstanteService; import com.rjconsultores.ventaboletos.service.PuntoVentaService; import com.rjconsultores.ventaboletos.utilerias.ApplicationProperties; import com.rjconsultores.ventaboletos.utilerias.UsuarioLogado; import com.rjconsultores.ws.totvs.service.TotvsService; import com.rjconsultores.ws.utileria.Atributos; import com.rjconsultores.ws.utileria.Atributos.CodPaisBanco; import com.rjconsultores.ws.utileria.Atributos.ContribuinteICMS; import com.rjconsultores.ws.utileria.Atributos.ContribuinteSimplesNacional; import com.rjconsultores.ws.utileria.Atributos.InscricaoMunicipal; import com.rjconsultores.ws.utileria.Atributos.TipoCliente; import com.rjconsultores.ws.utileria.Atributos.TipoEntidade; import com.rjconsultores.ws.utileria.Atributos.TipoFornecedor; import com.rjconsultores.ws.utileria.Atributos.TipoPessoa; import com.rjconsultores.ws.utileria.RetornoTotvs; import com.rjconsultores.ws.utileria.RetornoTotvs.TipoRetorno; /** * * @author Administrador */ @Service("puntoVentaService") public class PuntoVentaServiceImpl implements PuntoVentaService { private static Logger log = LoggerFactory.getLogger(PuntoVentaServiceImpl.class); private static final int CANAL_VENTA_PROPRIAS = 11; private static final int CANAL_VENTA_FRANQUEADAS = 12; private static final int CANAL_VENTA_PRESTACAO_SERVICO = 13; private static final int CANAL_VENTA_MOTORISTA = 14; private static final int CANAL_VENTA_COBRADOR = 15; @Autowired private PuntoVentaDAO puntoVentaDAO; @Autowired private ConstanteService constanteService; @Autowired private UsuarioUbicacionDAO usuarioUbicacionDAO; // FIXME : Remover esse método de quem está usando. Esse método carrega muitos dados @Deprecated public List obtenerTodos() { return puntoVentaDAO.obtenerTodos(); } public PuntoVenta obtenerID(Integer id) { return puntoVentaDAO.obtenerID(id); } @Transactional(noRollbackFor = { IntegracionException.class, ValidacionCampoException.class }) public PuntoVenta suscribir(PuntoVenta entidad) throws IntegracionException, ValidacionCampoException { entidad.setUsuarioId(UsuarioLogado.getUsuarioLogado().getUsuarioId()); entidad.setFecmodif(Calendar.getInstance().getTime()); entidad.setActivo(Boolean.TRUE); Exception respEx = null; try { if (entidad.getIndIntegracion() != TipoRetorno.CONCLUIDA.getValor()) { String resp = integracionTotvs(entidad); TipoRetorno retornoTotvs = RetornoTotvs.validaRetornoTotvs(resp); switch (retornoTotvs) { case CONCLUIDA: entidad.setIndIntegracion(TipoRetorno.CONCLUIDA.getValor()); break; case JA_CADASTRADA: entidad.setIndIntegracion(TipoRetorno.JA_CADASTRADA.getValor()); respEx = new IntegracionException(Atributos.MSG_ERRO_JA_CADASTRADO); break; case ERRO: entidad.setIndIntegracion(TipoRetorno.ERRO.getValor()); respEx = new IntegracionException(Atributos.MSG_ERRO_GENERICA + resp); break; default: break; } } else { respEx = new IntegracionException(Atributos.MSG_ERRO_NAO_ENVIO); } } catch (ValidacionCampoException ev) { entidad.setIndIntegracion(TipoRetorno.ERRO.getValor()); respEx = ev; } catch (Exception e) { entidad.setIndIntegracion(TipoRetorno.ERRO.getValor()); log.error(Atributos.MSG_ERRO_GENERICA, e); respEx = new IntegracionException(Atributos.MSG_ERRO_GENERICA + e.getMessage()); } entidad = puntoVentaDAO.suscribir(entidad); if (respEx != null) { if (respEx instanceof IntegracionException) { throw (IntegracionException) respEx; } else if (respEx instanceof ValidacionCampoException) { throw (ValidacionCampoException) respEx; } } return entidad; } @Transactional(noRollbackFor = { IntegracionException.class, ValidacionCampoException.class }) public PuntoVenta actualizacion(PuntoVenta entidad) throws IntegracionException, ValidacionCampoException { entidad.setUsuarioId(UsuarioLogado.getUsuarioLogado().getUsuarioId()); entidad.setFecmodif(Calendar.getInstance().getTime()); entidad.setActivo(Boolean.TRUE); Exception respEx = null; try { if (entidad.getIndIntegracion() != TipoRetorno.CONCLUIDA.getValor()) { String resp = integracionTotvs(entidad); TipoRetorno retornoTotvs = RetornoTotvs.validaRetornoTotvs(resp); switch (retornoTotvs) { case CONCLUIDA: entidad.setIndIntegracion(TipoRetorno.CONCLUIDA.getValor()); break; case JA_CADASTRADA: entidad.setIndIntegracion(TipoRetorno.JA_CADASTRADA.getValor()); respEx = new IntegracionException(Atributos.MSG_ERRO_JA_CADASTRADO); break; case ERRO: entidad.setIndIntegracion(TipoRetorno.ERRO.getValor()); respEx = new IntegracionException(Atributos.MSG_ERRO_GENERICA + resp); break; default: break; } } else { respEx = new IntegracionException(Atributos.MSG_ERRO_NAO_ENVIO); } } catch (ValidacionCampoException e) { entidad.setIndIntegracion(TipoRetorno.ERRO.getValor()); respEx = e; } catch (Exception e) { entidad.setIndIntegracion(TipoRetorno.ERRO.getValor()); log.error(Atributos.MSG_ERRO_GENERICA, e); respEx = new IntegracionException(Atributos.MSG_ERRO_GENERICA + e.getMessage()); } entidad = puntoVentaDAO.actualizacion(entidad); if (respEx != null) { if (respEx instanceof IntegracionException) { throw (IntegracionException) respEx; } else if (respEx instanceof ValidacionCampoException) { throw (ValidacionCampoException) respEx; } } return entidad; } @Transactional public void borrar(PuntoVenta entidad) { for (FormaPagoDet forma : entidad.getLsFormaPagoDet()) { forma.setUsuarioId(UsuarioLogado.getUsuarioLogado().getUsuarioId()); forma.setFecmodif(Calendar.getInstance().getTime()); forma.setActivo(Boolean.FALSE); } if (entidad.getAgenciaId() != null) { entidad.getAgenciaId().setUsuarioId(UsuarioLogado.getUsuarioLogado().getUsuarioId()); entidad.getAgenciaId().setFecmodif(Calendar.getInstance().getTime()); entidad.getAgenciaId().setActivo(Boolean.FALSE); } if (entidad.getComissaoId() != null) { entidad.getComissaoId().setUsuarioId(UsuarioLogado.getUsuarioLogado().getUsuarioId()); entidad.getComissaoId().setFecmodif(Calendar.getInstance().getTime()); entidad.getComissaoId().setActivo(Boolean.FALSE); } if (entidad.getDiversosId() != null) { entidad.getDiversosId().setUsuarioId(UsuarioLogado.getUsuarioLogado().getUsuarioId()); entidad.getDiversosId().setFecmodif(Calendar.getInstance().getTime()); entidad.getDiversosId().setActivo(Boolean.FALSE); } if (entidad.getTitularId() != null) { entidad.getTitularId().setUsuarioId(UsuarioLogado.getUsuarioLogado().getUsuarioId()); entidad.getTitularId().setFecmodif(Calendar.getInstance().getTime()); entidad.getTitularId().setActivo(Boolean.FALSE); } entidad.setUsuarioId(UsuarioLogado.getUsuarioLogado().getUsuarioId()); entidad.setFecmodif(Calendar.getInstance().getTime()); entidad.setActivo(Boolean.FALSE); puntoVentaDAO.actualizacion(entidad); } public List buscaLike(String strEstacion) { return puntoVentaDAO.buscaLike(strEstacion); } public List buscar(String nomPuntoVenta, String numPuntoVenta) { return puntoVentaDAO.busca(nomPuntoVenta, numPuntoVenta); } public List buscaPuntoVenta(String numPuntoVenta) { return puntoVentaDAO.buscaPuntoVenta(numPuntoVenta); } public List buscaPuntoVentaParada(Parada paradaId) { return puntoVentaDAO.buscaPuntoVentaParada(paradaId); } public List buscarPuntoVentaSubordinados(PuntoVenta puntoVenta) { List lsPuntoVentaSubordinados = puntoVentaDAO.buscarPuntoVentaSubordinados(puntoVenta); return lsPuntoVentaSubordinados; } public List buscarPuntosVentaMovimentacionBilhetes(List empresas) { List puntosVenta = puntoVentaDAO.buscarPuntosVentaMovimentacionBilhetes(empresas); return puntosVenta; } public List buscarPuntosVentaPorUsuario(Usuario usuario) { List puntosVenta = usuarioUbicacionDAO.buscarPuntoVentaPorUsuario(usuario); return puntosVenta; } private boolean validaCanalVenta(Integer tipoptovtaId) { boolean resp = false; switch (tipoptovtaId) { case CANAL_VENTA_PROPRIAS: resp = true; break; case CANAL_VENTA_FRANQUEADAS: resp = true; break; case CANAL_VENTA_MOTORISTA: resp = true; break; case CANAL_VENTA_COBRADOR: resp = true; break; default: break; } return resp; } private void validaCampos(PuntoVenta puntoVenta) throws ValidacionCampoException { if (puntoVenta.getNumDoCPuntoVenta() == null) { throw new ValidacionCampoException("editarPuntoVentaController.erro.numDoCPuntoVenta"); } if (puntoVenta.getNumIEPuntoVenta() == null) { throw new ValidacionCampoException("editarPuntoVentaController.erro.numIEPuntoVenta"); } if (puntoVenta.getAgenciaId() == null) { throw new ValidacionCampoException("editarPuntoVentaController.erro.agenciaId"); } else { if (puntoVenta.getAgenciaId().getNumagencia() == null) { throw new ValidacionCampoException("editarPuntoVentaController.erro.numagencia"); } if (puntoVenta.getAgenciaId().getNumconta() == null) { throw new ValidacionCampoException("editarPuntoVentaController.erro.numconta"); } if (puntoVenta.getAgenciaId().getDigito() == null) { throw new ValidacionCampoException("editarPuntoVentaController.erro.digito"); } if (puntoVenta.getAgenciaId().getInstiFinanceiraId() == null) { throw new ValidacionCampoException("editarPuntoVentaController.erro.instiFinanceiraId"); } else { if (puntoVenta.getAgenciaId().getInstiFinanceiraId().getCodigo() == null) { throw new ValidacionCampoException("editarPuntoVentaController.erro.instiFinanceiraId.codigo"); } } } } private String integracionTotvs(PuntoVenta puntoVenta) throws Exception { if (ApplicationProperties.getInstance().integracionTotvs()) { validaCampos(puntoVenta); boolean clienteValido = validaCanalVenta(puntoVenta.getTipoPuntoVenta().getTipoptovtaId().intValue()); boolean fornecedorValido = (puntoVenta.getTipoPuntoVenta().getTipoptovtaId() == CANAL_VENTA_PRESTACAO_SERVICO); if (fornecedorValido) clienteValido = true; String endpointFornecedor = getEndpointFornecedor(); String endpointCliente = getEndpointCliente(); String xidsvp = puntoVenta.getNumPuntoVenta(); String cnpjEmpresaProtheus = Atributos.CNPJ_EMPRESA_PROTHEUS; String nome = puntoVenta.getNombpuntoventa(); String cgc = puntoVenta.getNumDoCPuntoVenta(); String endereco = puntoVenta.getDireccioncalle() + "," + puntoVenta.getDireccionnumero() == null ? "" : puntoVenta.getDireccionnumero(); String complemen = puntoVenta.getCompl() == null ? "" : puntoVenta.getCompl(); String bairro = puntoVenta.getColonia() == null ? null : puntoVenta.getColonia().getDesccolonia(); String codmun = puntoVenta.getColonia() == null ? null : puntoVenta.getColonia().getCiudad().getCodmunicipio().toString(); codmun = (codmun == null) ? "" : StringUtils.leftPad(codmun, 5, '0'); String est = puntoVenta.getColonia() == null ? null : puntoVenta.getColonia().getCiudad().getEstado().getCveestado(); String codpais = CodPaisBanco.BRASIL.getValor(); String cep = puntoVenta.getColonia() == null ? null : puntoVenta.getColonia().getCodpostal(); String tel = puntoVenta.getNumtelefonouno(); String ddd = null; try { String[] telefone = tel == null ? null : tel.split("\\)"); ddd = tel == null ? null : telefone[0].replaceAll("\\(", ""); tel = tel == null ? null : telefone[1].replaceAll("\\(", ""); } catch (Exception e) { tel = puntoVenta.getNumtelefonouno(); } String email = puntoVenta.getDescCorreo() == null ? "" : puntoVenta.getDescCorreo(); String fax = puntoVenta.getNumfax() == null ? "" : puntoVenta.getNumfax(); String inscr = puntoVenta.getNumIEPuntoVenta(); String inscrm = InscricaoMunicipal.ISENTO.name(); String nreduz = puntoVenta.getRazonSocial() != null ? puntoVenta.getRazonSocial() : puntoVenta.getNombpuntoventa(); String simpnac = ContribuinteSimplesNacional.NAO.getValor(); String tppessoa = TipoFornecedor.OS.name(); String tppessoaCliente = TipoCliente.F.name(); String tipoPessoa = TipoPessoa.F.name(); if (isCNPJ(cgc)) { tipoPessoa = TipoPessoa.J.name(); } String obs = StringUtils.isBlank(puntoVenta.getComentarios()) ? "sem obs." : puntoVenta.getComentarios(); String conta = "1110101001001"; // DEVE SER REVISADO COM A GUANABARA String naturez = ""; String cnae = ""; String fator = ""; String agencia = puntoVenta.getAgenciaId() == null ? "" : puntoVenta.getAgenciaId().getNumagencia(); String dgverag = ""; try { String[] agenciaComp = agencia == null ? null : agencia.split("-"); agencia = agencia == null ? null : agenciaComp[0]; dgverag = agencia == null ? null : agenciaComp[1]; } catch (Exception e) { agencia = puntoVenta.getAgenciaId() == null ? "" : puntoVenta.getAgenciaId().getNumagencia(); } String banco = puntoVenta.getAgenciaId().getInstiFinanceiraId() == null ? "" : puntoVenta.getAgenciaId().getInstiFinanceiraId().getCodigo(); String ctacorr = puntoVenta.getAgenciaId() == null ? "" : puntoVenta.getAgenciaId().getNumconta(); String dgverct = puntoVenta.getAgenciaId() == null ? "" : puntoVenta.getAgenciaId().getDigito(); String resp = null; Exception respEx = null; if (fornecedorValido) { try { resp = TotvsService.cadastrarFornecedor(endpointFornecedor, bairro, cep, cgc, cnae, codmun, codpais, complemen, conta, ddd, email, endereco, est, inscr, inscrm, naturez, nome, nreduz, simpnac, tel, tipoPessoa, tppessoa, cnpjEmpresaProtheus, xidsvp, agencia, banco, dgverag, ctacorr, dgverct); } catch (Exception e) { log.error("", e); respEx = e; } } String contrib = ContribuinteICMS.NAO.getValor(); String entid = TipoEntidade.TRANSPORTE_PASSAGEIRO.getValor(); String pais = puntoVenta.getColonia() == null ? null : puntoVenta.getColonia().getCiudad().getEstado().getPais().getNombpais(); pais = "";// segundo mateus, passar em branco, segundo orientação do mateus da totvs if (clienteValido) { try { resp = TotvsService.cadastrarCliente(endpointCliente, bairro, cep, cgc, codmun, codpais, complemen, conta, contrib, ddd, email, cnpjEmpresaProtheus, endereco, entid, fator, fax, inscr, inscrm, naturez, nome, nreduz, obs, pais, tppessoaCliente, tel, tipoPessoa, est, xidsvp); } catch (Exception e) { log.error("", e); respEx = e; } if (respEx != null) { throw respEx; } } return resp; } return null; } private String getEndpointFornecedor() { Constante constante = constanteService.buscarPorNomeConstante("WS_TOTVS_FORNECEDOR_ENDPOINT"); if (constante == null) { return ""; } return constante.getValorconstante(); } private String getEndpointCliente() { Constante constante = constanteService.buscarPorNomeConstante("WS_TOTVS_CLIENTE_ENDPOINT"); if (constante == null) { return ""; } return constante.getValorconstante(); } private String somenteNumeros(String s) { if (s == null || StringUtils.isBlank(s)) { return ""; } s = StringUtils.trim(s); return s.replaceAll("[^0-9]", ""); } private boolean isCNPJ(String vlr) { vlr = somenteNumeros(vlr); return vlr.length() > 11; } }