AdmMono/src/com/rjconsultores/ventaboletos/service/impl/FiscalServiceImpl.java

495 lines
17 KiB
Java
Raw Blame History

package com.rjconsultores.ventaboletos.service.impl;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.rjconsultores.ventaboletos.dao.FiscalDAO;
import com.rjconsultores.ventaboletos.entidad.Empresa;
import com.rjconsultores.ventaboletos.entidad.EsquemaCorrida;
import com.rjconsultores.ventaboletos.service.FiscalService;
import com.rjconsultores.ventaboletos.utilerias.DateUtil;
import com.rjconsultores.ventaboletos.utilerias.UsuarioLogado;
import com.rjconsultores.ventaboletos.utilerias.UtileriasFiscal;
import com.rjconsultores.ventaboletos.vo.impressaofiscal.ImportacionFiscalVO;
import com.rjconsultores.ventaboletos.vo.impressaofiscal.ItemFiscalVO;
@Service("fiscalService")
public class FiscalServiceImpl implements FiscalService {
private static Logger log = Logger.getLogger(FiscalServiceImpl.class);
public static final String DATE_FORMAT_FISCAL = "yyyyMMdd";
public static final BigDecimal CEM = BigDecimal.valueOf(100);
@Autowired
private FiscalDAO fiscalDAO;
@Override
@Transactional
public int gerarRegistroP2_F2(List<EsquemaCorrida> lsEsquemaCorrida, Date dataDe, Date dataAte) {
return fiscalDAO.gerarRegistroP2_F2(lsEsquemaCorrida, dataDe, dataAte);
}
@Override
public File importacionFiscalECF(Date inicio, Date fim, Empresa empresa) {
try {
List<ItemFiscalVO> itens = fiscalDAO.buscaDatosFiscaisECF(inicio, fim, empresa.getEmpresaId());
List<ImportacionFiscalVO> list = agruparItensFiscais(itens);
String nomeArquivo = UsuarioLogado.getUsuarioLogado().getNombusuario() + "_" + Calendar.getInstance().getTime().getTime() + "_" + "fiscal";
File arquivo = File.createTempFile(nomeArquivo, ".tmp");
FileWriter arq = new FileWriter(arquivo);
PrintWriter gravarArq = new PrintWriter(arq);
String cnpjFilial = empresa.getCnpj();
String brancos372 = StringUtils.rightPad("", 372, " ");
String dataAgora = DateUtil.getStringDate(Calendar.getInstance().getTime(), DATE_FORMAT_FISCAL);
String abertura = aberturaDeArquivo("0", dataAgora, cnpjFilial, brancos372, "00001");
gravarArq.println(abertura);
Integer seq = 1;
for (ImportacionFiscalVO fiscal : list) {
String data = fiscal.getDataEmissao();
String brancos213 = StringUtils.rightPad("", 213, " ");
String serie = StringUtils.rightPad("", 3, " ");
String especie = "CF" + StringUtils.rightPad("", 3, " ");
String codigoCliente = StringUtils.rightPad("", 6, "9");
String filialCliente = StringUtils.rightPad("", 2, "9");
String condicaoPagamento = StringUtils.rightPad("", 3, "9");
String valorPIS = StringUtils.rightPad("", 14, " ");
String valorCofins = StringUtils.rightPad("", 14, " ");
String valorCSLL = StringUtils.rightPad("", 14, " ");
String coo = fiscal.getCoo();
if (coo.length() < 9) {
coo = StringUtils.rightPad("", (9 - coo.length()), " ") + coo;
}
String valorTotalDocumanto = fiscal.getValorTotal().toString();
if (valorTotalDocumanto.length() < 14) {
valorTotalDocumanto = StringUtils.rightPad("", (14 - valorTotalDocumanto.length()), " ") + valorTotalDocumanto;
}
String valorItens = fiscal.getValorTotal().toString();
if (valorItens.length() < 14) {
valorItens = StringUtils.rightPad("", (14 - valorItens.length()), " ") + valorItens;
}
HashMap<String, String> aliquotaBaseCalculo = getAliquotaBaseCalculo(fiscal);
String aliquota = aliquotaBaseCalculo.get("aliquota");
String imposto = aliquotaBaseCalculo.get("imposto");
String totalICMSIsento = aliquotaBaseCalculo.get("totalICMSIsento");
String totalICMSNaotributado = aliquotaBaseCalculo.get("totalICMSNaotributado");
String origen = fiscal.getOrigenId().toString();
if (origen.length() < 5) {
origen = StringUtils.rightPad("", (5 - origen.length()), " ") + origen;
}
seq++;
String sequencial = seq.toString();
if (sequencial.length() < 5) {
sequencial = StringUtils.rightPad("", (5 - sequencial.length()), "0") + sequencial;
}
String header = headerDocumentoFiscal("1", data, cnpjFilial, coo, serie, especie, codigoCliente,
filialCliente, condicaoPagamento, valorTotalDocumanto, valorItens, aliquota, imposto,
valorPIS, valorCofins, valorCSLL, totalICMSIsento, totalICMSNaotributado, origen, brancos213, sequencial);
gravarArq.println(header);
for (String itemDoc : montarItensFiscais(fiscal.getItensFiscais(), seq)) {
gravarArq.println(itemDoc);
seq++;
}
}
String qtdeDocGerados = StringUtils.rightPad("", 5, " ") + "1";
String qtdeItensDocGerados = StringUtils.rightPad("", 5, " ") + "2";
String brancos382 = StringUtils.rightPad("", 382, " ");
seq++;
String sequencial = seq.toString();
if (sequencial.length() < 5) {
sequencial = StringUtils.rightPad("", (5 - sequencial.length()), "0") + sequencial;
}
String fechamento = fechamentoDeArquivo("3", qtdeDocGerados, qtdeItensDocGerados, brancos382, sequencial);
gravarArq.println(fechamento);
arq.close();
return arquivo;
} catch (IOException e) {
log.error("", e);
}
return null;
}
private List<String> montarItensFiscais(List<ItemFiscalVO> itensFiscais, Integer seq) {
List<String> itensDocs = new ArrayList<String>();
for (ItemFiscalVO item : itensFiscais) {
String tipoPassagem = null;
if (item.getRepTributado().length() == 7 && item.getRepTributado().substring(2, 3).equals("T")) {
tipoPassagem = item.getTipoPassagem();
if (tipoPassagem == null)
tipoPassagem = "E";
} else {
tipoPassagem = "E";
}
String numItem = item.getNumItem();
String cfop = null;
if (tipoPassagem.equals("E")) {
cfop = StringUtils.rightPad("", 1, " ") + "6357";
} else if (tipoPassagem.equals("M")) {
cfop = StringUtils.rightPad("", 1, " ") + "5357";
}
String codigoTES = "999";
String codProduto = item.getCodProduto();
if (codProduto.length() < 15) {
codProduto = StringUtils.rightPad("", (15 - codProduto.length()), " ") + codProduto;
}
String unidade = "UN";
String quantidade = "001";
String valorUnitario = item.getValorItem().toString();
if (valorUnitario.length() < 15) {
valorUnitario = StringUtils.rightPad("", (15 - valorUnitario.length()), " ") + valorUnitario;
}
String valorTotal = item.getValorItem().toString();
if (valorTotal.length() < 15) {
valorTotal = StringUtils.rightPad("", (15 - valorTotal.length()), " ") + valorTotal;
}
String aliquotaItem = StringUtils.rightPad("", 7, " ");
String impostoItem = StringUtils.rightPad("", 15, " ");
String totalICMSIsentoItem = StringUtils.rightPad("", 15, " ");
String totalICMSNaotributadoItem = StringUtils.rightPad("", 15, " ");
HashMap<String, BigDecimal> aliquotaItens = new HashMap<String, BigDecimal>(0);
// Verificando se <20> um produto tribut<75>vel. Formato: XXTYYYY (XX - Posicao / YYYY - Aliquota)
if (item.getRepTributado().length() == 7 && item.getRepTributado().substring(2, 3).equals("T")) {
String key = tipoPassagem + item.getRepTributado().substring(3, 7);
if (!aliquotaItens.containsKey(key)) {
aliquotaItens.put(key, BigDecimal.ZERO);
}
BigDecimal soma = item.getValorItem().divide(BigDecimal.TEN.multiply(BigDecimal.TEN));
aliquotaItens.put(key, soma.add(aliquotaItens.get(key)));
} else if (item.getRepTributado().equals("N1")) {
BigDecimal soma = item.getValorItem();
totalICMSNaotributadoItem = soma.toString();
if (totalICMSNaotributadoItem.length() < 15) {
totalICMSNaotributadoItem = StringUtils.rightPad("", (15 - totalICMSNaotributadoItem.length()), " ") + totalICMSNaotributadoItem;
}
}
for (String key : aliquotaItens.keySet()) {
aliquotaItem = key.substring(1, 5);
BigDecimal aliquotaCalc = BigDecimal.valueOf(Double.valueOf(aliquotaItem) / CEM.doubleValue());
aliquotaCalc = UtileriasFiscal.arredondar(aliquotaCalc);
BigDecimal baseCalculo = aliquotaItens.get(key);
baseCalculo = UtileriasFiscal.arredondar(baseCalculo);
BigDecimal valorImposto = baseCalculo.multiply(aliquotaCalc.divide(CEM));
valorImposto = UtileriasFiscal.arredondar(valorImposto);
impostoItem = valorImposto.toString().replace(".", "").replace(",", "");
impostoItem = UtileriasFiscal.formataNumerico(impostoItem, impostoItem.length());
aliquotaItem = aliquotaCalc.toString().replace(".", "").replace(",", "");
aliquotaItem = UtileriasFiscal.formataNumerico(aliquotaItem, aliquotaItem.length());
if (aliquotaItem.length() < 7) {
aliquotaItem = StringUtils.rightPad("", (7 - aliquotaItem.length()), " ") + aliquotaItem;
}
if (impostoItem.length() < 15) {
impostoItem = StringUtils.rightPad("", (15 - impostoItem.length()), " ") + impostoItem;
}
}
String aliquotaPIS = StringUtils.rightPad("", 7, " ");
String valorPIS = StringUtils.rightPad("", 15, " ");
String aliquotaCofins = StringUtils.rightPad("", 7, " ");
String valorCofins = StringUtils.rightPad("", 15, " ");
String aliquotaCSLL = StringUtils.rightPad("", 7, " ");
String valorCSLL = StringUtils.rightPad("", 15, " ");
String aliquotaISS = StringUtils.rightPad("", 7, " ");
String valorISS = StringUtils.rightPad("", 15, " ");
seq++;
String sequencial = seq.toString();
if (sequencial.length() < 5) {
sequencial = StringUtils.rightPad("", (5 - sequencial.length()), "0") + sequencial;
}
String brancos193 = StringUtils.rightPad("", 193, " ");
String itemDoc = itensDocumentoFiscal("2", numItem, cfop, codigoTES, codProduto,
unidade, quantidade, valorUnitario, valorTotal, aliquotaItem, impostoItem,
aliquotaPIS, valorPIS, aliquotaCofins, valorCofins, aliquotaCSLL, valorCSLL,
aliquotaISS, valorISS, totalICMSIsentoItem, totalICMSNaotributadoItem,
brancos193, sequencial);
itensDocs.add(itemDoc);
}
return itensDocs;
}
private List<ImportacionFiscalVO> agruparItensFiscais(List<ItemFiscalVO> itens) {
List<ImportacionFiscalVO> list = new ArrayList<ImportacionFiscalVO>();
for (ItemFiscalVO item : itens) {
ImportacionFiscalVO fiscal = item;
Integer index = null;
boolean novaInsercao = false;
if (list.contains(fiscal)) {
index = list.indexOf(fiscal);
fiscal = list.get(index);
} else {
list.add(fiscal);
novaInsercao = true;
}
if (fiscal.getItensFiscais() == null) {
fiscal.setItensFiscais(new ArrayList<ItemFiscalVO>());
}
fiscal.getItensFiscais().add(item);
if (!novaInsercao) {
list.set(index, fiscal);
}
}
return list;
}
private HashMap<String, String> getAliquotaBaseCalculo(ImportacionFiscalVO fiscal) {
HashMap<String, String> resp = new HashMap<String, String>();
String aliquota = null;
String imposto = null;
String totalICMSIsento = null;
String totalICMSNaotributado = null;
for (ItemFiscalVO item : fiscal.getItensFiscais()) {
HashMap<String, BigDecimal> aliquotaBaseCalculo = new HashMap<String, BigDecimal>(0);
// Verificando se <20> um produto tribut<75>vel. Formato: XXTYYYY (XX - Posicao / YYYY - Aliquota)
if (item.getRepTributado().length() == 7 && item.getRepTributado().substring(2, 3).equals("T")) {
String tipoPassagem = item.getTipoPassagem();
if (tipoPassagem == null) {
tipoPassagem = "E";
}
String key = tipoPassagem + item.getRepTributado().substring(3, 7);
if (!aliquotaBaseCalculo.containsKey(key)) {
aliquotaBaseCalculo.put(key, BigDecimal.ZERO);
}
BigDecimal soma = item.getValorItem().divide(BigDecimal.TEN.multiply(BigDecimal.TEN));
aliquotaBaseCalculo.put(key, soma.add(aliquotaBaseCalculo.get(key)));
} else if (item.getRepTributado().equals("N1")) {
BigDecimal soma = item.getValorItem();
totalICMSNaotributado = soma.toString();
if (totalICMSNaotributado.length() < 14) {
totalICMSNaotributado = StringUtils.rightPad("", (14 - totalICMSNaotributado.length()), " ") + totalICMSNaotributado;
}
}
for (String key : aliquotaBaseCalculo.keySet()) {
aliquota = key.substring(1, 5);
BigDecimal aliquotaCalc = BigDecimal.valueOf(Double.valueOf(aliquota) / CEM.doubleValue());
aliquotaCalc = UtileriasFiscal.arredondar(aliquotaCalc);
BigDecimal baseCalculo = aliquotaBaseCalculo.get(key);
baseCalculo = UtileriasFiscal.arredondar(baseCalculo);
BigDecimal valorImposto = baseCalculo.multiply(aliquotaCalc.divide(CEM));
valorImposto = UtileriasFiscal.arredondar(valorImposto);
imposto = valorImposto.toString().replace(".", "").replace(",", "");
imposto = UtileriasFiscal.formataNumerico(imposto, imposto.length());
aliquota = aliquotaCalc.toString().replace(".", "").replace(",", "");
aliquota = UtileriasFiscal.formataNumerico(aliquota, aliquota.length());
if (aliquota.length() < 14) {
aliquota = StringUtils.rightPad("", (14 - aliquota.length()), " ") + aliquota;
}
if (imposto.length() < 14) {
imposto = StringUtils.rightPad("", (14 - imposto.length()), " ") + imposto;
}
}
}
if (StringUtils.isBlank(aliquota))
aliquota = StringUtils.rightPad("", 14, " ");
if (StringUtils.isBlank(imposto))
imposto = StringUtils.rightPad("", 14, " ");
if (StringUtils.isBlank(totalICMSIsento))
totalICMSIsento = StringUtils.rightPad("", 14, " ");
if (StringUtils.isBlank(totalICMSNaotributado))
totalICMSNaotributado = StringUtils.rightPad("", 14, " ");
resp.put("aliquota", aliquota);
resp.put("imposto", imposto);
resp.put("totalICMSIsento", totalICMSIsento);
resp.put("totalICMSNaotributado", totalICMSNaotributado);
return resp;
}
private String aberturaDeArquivo(String identificador, String data, String cnpjFilial, String brancos372, String sequencial) {
StringBuilder abertura = new StringBuilder();
abertura.append(identificador);
abertura.append(data);
abertura.append(cnpjFilial);
abertura.append(brancos372);
abertura.append(sequencial);
return abertura.toString();
}
private String headerDocumentoFiscal(String identificador, String data, String cnpjImpressora, String coo, String serie,
String especie, String codigoCliente, String filialCliente, String condicaoPagamento, String valorTotalDocumanto,
String valorItens, String aliquota, String imposto, String valorPIS, String valorCofins, String valorCSLL,
String totalICMSIsento, String totalICMSNaotributado, String origen, String brancos213, String sequencial) {
StringBuilder header = new StringBuilder();
header.append(identificador);
header.append(data);
header.append(cnpjImpressora);
header.append(coo);
header.append(serie);
header.append(especie);
header.append(codigoCliente);
header.append(filialCliente);
header.append(condicaoPagamento);
header.append(valorTotalDocumanto);
header.append(valorItens);
header.append(aliquota);
header.append(imposto);
header.append(valorPIS);
header.append(valorCofins);
header.append(valorCSLL);
header.append(totalICMSIsento);
header.append(totalICMSNaotributado);
header.append(origen);
header.append(brancos213);
header.append(sequencial);
return header.toString();
}
private String itensDocumentoFiscal(String identificador, String numItem, String cfop, String codigoTES, String codProduto,
String unidade, String quantidade, String valorUnitario, String valorTotal, String aliquotaItem, String impostoItem,
String valorPIS, String aliquotaPIS, String aliquotaCofins, String valorCofins, String aliquotaCSLL, String valorCSLL,
String aliquotaISS, String valorISS, String totalICMSIsentoItem, String totalICMSNaotributadoItem,
String brancos193, String sequencial) {
StringBuilder item = new StringBuilder();
item.append(identificador);
item.append(numItem);
item.append(cfop);
item.append(codigoTES);
item.append(codProduto);
item.append(unidade);
item.append(quantidade);
item.append(valorUnitario);
item.append(valorTotal);
item.append(aliquotaItem);
item.append(impostoItem);
item.append(aliquotaPIS);
item.append(valorPIS);
item.append(aliquotaCofins);
item.append(valorCofins);
item.append(aliquotaCSLL);
item.append(valorCSLL);
item.append(aliquotaISS);
item.append(valorISS);
item.append(totalICMSIsentoItem);
item.append(totalICMSNaotributadoItem);
item.append(brancos193);
item.append(sequencial);
return item.toString();
}
private String fechamentoDeArquivo(String identificador, String qtdeDocGerados, String qtdeItensDocGerados, String brancos382, String sequencial) {
StringBuilder fechamento = new StringBuilder();
fechamento.append(identificador);
fechamento.append(qtdeDocGerados);
fechamento.append(qtdeItensDocGerados);
fechamento.append(brancos382);
fechamento.append(sequencial);
return fechamento.toString();
}
}