Subversion Repositories Integrator Subversion

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 espaco 1
package br.com.ec.domain.model;
2
 
3
import java.io.ByteArrayInputStream;
4
import java.io.ByteArrayOutputStream;
5
import java.io.IOException;
6
import java.io.Serializable;
7
import java.io.StringReader;
8
import java.text.ParseException;
9
import java.text.SimpleDateFormat;
10
import java.util.ArrayList;
11
import java.util.Date;
12
import java.util.List;
13
 
14
import javax.persistence.Column;
15
import javax.persistence.Entity;
16
import javax.persistence.GeneratedValue;
17
import javax.persistence.GenerationType;
18
import javax.persistence.Id;
19
import javax.persistence.JoinColumn;
20
import javax.persistence.ManyToOne;
21
import javax.persistence.Table;
22
import javax.persistence.Transient;
23
import javax.validation.constraints.NotNull;
24
import javax.xml.bind.JAXBContext;
25
import javax.xml.bind.JAXBException;
26
import javax.xml.bind.Unmarshaller;
27
import javax.xml.parsers.DocumentBuilder;
28
import javax.xml.parsers.DocumentBuilderFactory;
29
import javax.xml.transform.Transformer;
30
import javax.xml.transform.TransformerFactory;
31
import javax.xml.transform.dom.DOMSource;
32
import javax.xml.transform.stream.StreamResult;
33
import javax.xml.transform.stream.StreamSource;
34
 
35
import org.apache.commons.io.IOUtils;
36
import org.hibernate.annotations.ForeignKey;
37
import org.primefaces.model.DefaultStreamedContent;
38
import org.w3c.dom.Document;
39
 
40
import br.com.ec.domain.dto.NfceItemDTO;
41
import br.com.ec.domain.model.tipos.TipoModeloNotaFiscal;
42
import br.com.ec.domain.model.tipos.TipoNotaFiscal;
43
import br.edu.cesmac.core.exception.NegocioException;
44
import br.edu.cesmac.core.generic.identidade.Identidade;
45
import br.edu.cesmac.core.interfaces.Alterar;
46
import br.edu.cesmac.core.interfaces.Cadastrar;
47
import br.edu.cesmac.core.util.StringUtil;
48
import br.edu.cesmac.core.util.VerificadorUtil;
49
import br.edu.cesmac.relatorio.util.RelatorioUtils;
50
import br.edu.cesmac.web.util.DataUtil;
51
import nfce.java.TNfeProc;
52
 
53
@Entity
54
@Table(name="sec_nota_fiscal", schema="sc_sec")
55
public class NotaFiscal implements Serializable, Identidade {
56
 
57
        private static final long serialVersionUID = 1L;
58
 
59
        private Long sequencial;
60
        private Long numeroNotaFiscal;
61
        private String chave;
62
        private String serie;
63
        private Venda venda;
64
        private Pessoa pessoaJuridicaEmitente;
65
        private Pessoa pessoaJuridicaDestinatario;
66
        private String observacaoVenda;
67
//      private Transporte transporte;
68
        private String descricaoComplementares;
69
        private Date dataHoraEmissao;
70
        private String textoXml;
71
        private String tipoNotaFiscal;
72
        private String tipoModeloNotaFiscal;
73
        private String protocoloAutorizacao;
74
        private String caminhoQrcode;
75
 
76
        private String statusRetorno;
77
        private String motivoRetorno;
78
        private Date dataHoraEvento;
79
        private String textoXmlEvento;
80
 
81
        private List<NotaFiscalProduto> listaNFRemessaProdutos;
82
 
83
        private byte[] arquivoXml;
84
 
85
        private List<Parcela> listaParcelas;
86
        private List<CompraProduto> listaCompraProduto;
87
        private List<Lancamento> listaLancamento;
88
        private List<VendaFormaPagamento> listaFormaPagamento;
89
 
90
        private Boolean notaFiscalPendente;
91
 
92
        @Override
93
        @Transient
94
        public Object getId() {
95
                return this.getSequencial();
96
        }
97
        @Override
98
        public void setId(Object id) {
99
                this.sequencial = (Long) id;
100
        }
101
 
102
        @Id
103
        @GeneratedValue(strategy = GenerationType.IDENTITY)
104
        @Column(name="seq_nota_fiscal", nullable=false)
105
        public Long getSequencial() {
106
                return sequencial;
107
        }
108
        public void setSequencial(Long sequencial) {
109
                this.sequencial = sequencial;
110
        }
111
 
112
        @Column(name="cod_nota_fiscal")
113
        public String getChave() {
114
                return chave;
115
        }
116
        public void setChave(String chave) {
117
                this.chave = chave;
118
        }
119
 
120
        @Column(name="dsc_serie")
121
        public String getSerie() {
122
                return serie;
123
        }
124
        public void setSerie(String serie) {
125
                this.serie = serie;
126
        }
127
 
128
        @Column(name="num_nota_fiscal", nullable=false)
129
        public Long getNumeroNotaFiscal() {
130
                return numeroNotaFiscal;
131
        }
132
        public void setNumeroNotaFiscal(Long numeroNotaFiscal) {
133
                this.numeroNotaFiscal = numeroNotaFiscal;
134
        }
135
 
136
        @ManyToOne
137
        @ForeignKey(name = "fk_notafiscal_venda")
138
        @JoinColumn(name="seq_venda", referencedColumnName="seq_venda", insertable=true, updatable=false)
139
        public Venda getVenda() {
140
                return venda;
141
        }
142
        public void setVenda(Venda venda) {
143
                this.venda = venda;
144
        }
145
 
146
        @ManyToOne
147
        @ForeignKey(name = "fk_notafiscal_emitente")
148
        @JoinColumn(name="seq_pessoa_emitente", referencedColumnName="seq_pessoa", insertable=true, updatable=false)
149
        public Pessoa getPessoaJuridicaEmitente() {
150
                return pessoaJuridicaEmitente;
151
        }
152
        public void setPessoaJuridicaEmitente(Pessoa pessoaJuridicaEmitente) {
153
                this.pessoaJuridicaEmitente = pessoaJuridicaEmitente;
154
        }
155
 
156
        @ManyToOne
157
        @ForeignKey(name = "fk_notafiscal_destinatario")
158
        @JoinColumn(name="seq_pessoa_destinatario", referencedColumnName="seq_pessoa", insertable=true, updatable=false)
159
        public Pessoa getPessoaJuridicaDestinatario() {
160
                return pessoaJuridicaDestinatario;
161
        }
162
        public void setPessoaJuridicaDestinatario(Pessoa pessoaJuridicaDestinatario) {
163
                this.pessoaJuridicaDestinatario = pessoaJuridicaDestinatario;
164
        }
165
 
166
        @Column(name="dsc_obs_venda")
167
        public String getObservacaoVenda() {
168
                return observacaoVenda;
169
        }
170
        public void setObservacaoVenda(String observacaoVenda) {
171
                this.observacaoVenda = observacaoVenda;
172
        }
173
 
174
        @Column(name="dsc_complementares")
175
        public String getDescricaoComplementares() {
176
                return descricaoComplementares;
177
        }
178
        public void setDescricaoComplementares(String descricaoComplementares) {
179
                this.descricaoComplementares = descricaoComplementares;
180
        }
181
 
182
        @Column(name="dth_emissao", nullable=false)
183
        public Date getDataHoraEmissao() {
184
                return dataHoraEmissao;
185
        }
186
        public void setDataHoraEmissao(Date dataHoraEmissao) {
187
                this.dataHoraEmissao = dataHoraEmissao;
188
        }
189
 
190
        @Column(name="txt_xml")
191
        public String getTextoXml() {
192
                return textoXml;
193
        }
194
        public void setTextoXml(String textoXml) {
195
                this.textoXml = textoXml;
196
        }
197
 
198
        @Column(name="tip_nota_fiscal", nullable=false)
199
        @NotNull(message="Obrigatório informar o tipo da nota fiscal", groups={Cadastrar.class, Alterar.class})
200
        public String getTipoNotaFiscal() {
201
                return tipoNotaFiscal;
202
        }
203
        public void setTipoNotaFiscal(String tipoNotaFiscal) {
204
                this.tipoNotaFiscal = tipoNotaFiscal;
205
        }
206
        @Transient
207
        public String getDescricaoDoTipoNotaFiscal() {
208
                return VerificadorUtil.naoEstaNuloOuVazio(getTipoNotaFiscal())? TipoNotaFiscal.parse(getTipoNotaFiscal()).getDescricao() : null;
209
        }
210
 
211
        @Column(name="tip_modelo_notafiscal", nullable=false)
212
        @NotNull(message="Obrigatório informar o tipo do modelo da nota fiscal", groups={Cadastrar.class, Alterar.class})
213
        public String getTipoModeloNotaFiscal() {
214
                return tipoModeloNotaFiscal;
215
        }
216
        public void setTipoModeloNotaFiscal(String tipoModeloNotaFiscal) {
217
                this.tipoModeloNotaFiscal = tipoModeloNotaFiscal;
218
        }
219
        @Transient
220
        public String getDescricaoDoTipoModeloNotaFiscal() {
221
                return VerificadorUtil.naoEstaNuloOuVazio(getTipoModeloNotaFiscal())? TipoModeloNotaFiscal.parse(getTipoModeloNotaFiscal()).getDescricao() : null;
222
        }
223
 
224
        @Column(name="dsc_protocolo_autorizacao")
225
        public String getProtocoloAutorizacao() {
226
                return protocoloAutorizacao;
227
        }
228
        public void setProtocoloAutorizacao(String protocoloAutorizacao) {
229
                this.protocoloAutorizacao = protocoloAutorizacao;
230
        }
231
 
232
        @Column(name="dsc_caminho_qrcode")
233
        public String getCaminhoQrcode() {
234
                return caminhoQrcode;
235
        }
236
        public void setCaminhoQrcode(String caminhoQrcode) {
237
                this.caminhoQrcode = caminhoQrcode;
238
        }
239
 
240
        @Column(name="dsc_status_retorno")
241
        public String getStatusRetorno() {
242
                return statusRetorno;
243
        }
244
        public void setStatusRetorno(String statusRetorno) {
245
                this.statusRetorno = statusRetorno;
246
        }
247
 
248
        @Column(name="dsc_motivo_retorno")
249
        public String getMotivoRetorno() {
250
                return motivoRetorno;
251
        }
252
        public void setMotivoRetorno(String motivoRetorno) {
253
                this.motivoRetorno = motivoRetorno;
254
        }
255
 
256
        @Column(name="dth_evento")
257
        public Date getDataHoraEvento() {
258
                return dataHoraEvento;
259
        }
260
        public void setDataHoraEvento(Date dataHoraEvento) {
261
                this.dataHoraEvento = dataHoraEvento;
262
        }
263
 
264
        @Column(name="txt_xml_evento", nullable=false)
265
        public String getTextoXmlEvento() {
266
                return textoXmlEvento;
267
        }
268
        public void setTextoXmlEvento(String textoXmlEvento) {
269
                this.textoXmlEvento = textoXmlEvento;
270
        }
271
 
272
//      @OneToMany(mappedBy="notaFiscal", cascade=CascadeType.ALL, orphanRemoval=true)
273
        @Transient
274
        public List<NotaFiscalProduto> getListaNFRemessaProdutos() {
275
                return listaNFRemessaProdutos;
276
        }
277
        public void setListaNFRemessaProdutos(List<NotaFiscalProduto> listaNFRemessaProdutos) {
278
                this.listaNFRemessaProdutos = listaNFRemessaProdutos;
279
        }
280
 
281
        @Transient
282
        public Boolean temPessoaJuridica() {
283
                if (VerificadorUtil.estaNulo(getVenda())) return false;
284
                if (VerificadorUtil.estaNulo(getVenda().getLoja())) return false;
285
                return VerificadorUtil.naoEstaNulo(getVenda().getLoja().getPessoaJuridica());
286
        }
287
 
288
        @Transient
289
        public String getRazaoSocialDaLoja() {
290
                return temPessoaJuridica()? getVenda().getLoja().getPessoaJuridica().getRazaoSocial() : "";
291
        }
292
 
293
        @Transient
294
        public String getCnpjDaLoja() {
295
                return temPessoaJuridica()? StringUtil.formatarCnpj(getVenda().getLoja().getPessoaJuridica().getCpfCnpj()) : "";
296
        }
297
 
298
        @Transient
299
        public byte[] getArquivoXml() {
300
                return arquivoXml;
301
        }
302
        public void setArquivoXml(byte[] arquivoXml) {
303
                this.arquivoXml = arquivoXml;
304
        }
305
 
306
        @Transient
307
        public List<Parcela> getListaParcelas() {
308
                return listaParcelas;
309
        }
310
        public void setListaParcelas(List<Parcela> listaParcelas) {
311
                this.listaParcelas = listaParcelas;
312
        }
313
 
314
        @Transient
315
        public List<CompraProduto> getListaCompraProduto() {
316
                return listaCompraProduto;
317
        }
318
        public void setListaCompraProduto(List<CompraProduto> listaCompraProduto) {
319
                this.listaCompraProduto = listaCompraProduto;
320
        }
321
 
322
        @Transient
323
        public List<Lancamento> getListaLancamento() {
324
                return listaLancamento;
325
        }
326
        public void setListaLancamento(List<Lancamento> listaLancamento) {
327
                this.listaLancamento = listaLancamento;
328
        }
329
 
330
        @Transient
331
        public List<VendaFormaPagamento> getListaFormaPagamento() {
332
                return listaFormaPagamento;
333
        }
334
        public void setListaFormaPagamento(List<VendaFormaPagamento> listaFormaPagamento) {
335
                this.listaFormaPagamento = listaFormaPagamento;
336
        }
337
 
338
        @Transient
339
        public Boolean getNotaFiscalPendente() {
340
                return notaFiscalPendente;
341
        }
342
        public void setNotaFiscalPendente(Boolean notaFiscalPendente) {
343
                this.notaFiscalPendente = notaFiscalPendente;
344
        }
345
 
346
        @Override
347
        public int hashCode() {
348
                final int prime = 31;
349
                int result = 1;
350
                result = prime * result + ((chave == null) ? 0 : chave.hashCode());
351
                return result;
352
        }
353
 
354
        @Override
355
        public boolean equals(Object obj) {
356
                if (this == obj)
357
                        return true;
358
                if (obj == null)
359
                        return false;
360
                if (getClass() != obj.getClass())
361
                        return false;
362
                NotaFiscal other = (NotaFiscal) obj;
363
                if (chave == null) {
364
                        if (other.chave != null)
365
                                return false;
366
                } else if (!chave.equals(other.chave))
367
                        return false;
368
                return true;
369
        }
370
 
371
        @Transient
372
        public Double getTotalLancamentos() {
373
                Double total = 0.0;
374
                if (!VerificadorUtil.isListaNulaOuVazia(getListaLancamento())) {
375
                        for (Lancamento lancamento : getListaLancamento()) {
376
                                total = total + lancamento.getValorVenda();
377
                        }
378
                }
379
                return total;  
380
        }
381
 
382
        @Transient
383
        public Double getTotalPago() {
384
                Double total = 0.0;
385
                if (!VerificadorUtil.isListaNulaOuVazia(getListaFormaPagamento())) {
386
                        for (VendaFormaPagamento vendaFormaPagamento : getListaFormaPagamento()) {
387
                                total = total + vendaFormaPagamento.getValorPagamento();
388
                        }
389
                }
390
                return total;  
391
        }
392
 
393
        @Transient
394
        public Double getValorNotaFiscal() {
395
                if (VerificadorUtil.naoEstaNuloOuVazio(getTextoXml())) {
396
                        if (getTextoXml().indexOf("<vNF>") > 0) {
397
                                String valorLocalizado = getTextoXml().substring(getTextoXml().indexOf("<vNF>"), getTextoXml().indexOf("</vNF>"))
398
                                                                                        .replace("<vNF>", "").replace("</vNF>", "");
399
                                return new Double(valorLocalizado);
400
                        }
401
                }
402
                return 0.0;
403
        }
404
 
405
        @Transient
406
        public Double getTotalValorProdutosRemessa() {
407
                Double total = new Double(0.0);
408
                if (VerificadorUtil.naoEstaNuloOuVazio(getListaNFRemessaProdutos())) {
409
                        for (NotaFiscalProduto notaFiscalProduto : getListaNFRemessaProdutos()) {
410
                                total = total + notaFiscalProduto.getProduto().getValorCompra() * notaFiscalProduto.getQuantidade();
411
                        }
412
                }
413
                return total;
414
        }
415
 
416
        @Transient
417
        public Boolean ehNotaFiscalDeRemessa() {
418
                return VerificadorUtil.naoEstaNulo(getTipoNotaFiscal()) ? getTipoNotaFiscal().equals(TipoNotaFiscal.NFE_REMESSA.getValor()) : false;
419
        }
420
 
421
        @Transient
422
        public byte[] criarArquivoXml() {
423
                ByteArrayInputStream in = null;
424
                ByteArrayOutputStream bos = null;
425
                try {
426
                        in = new ByteArrayInputStream(getTextoXml().getBytes());
427
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
428
                        DocumentBuilder builder = dbf.newDocumentBuilder();
429
                        Document xml = builder.parse(in);
430
 
431
                        bos = new ByteArrayOutputStream();
432
                        TransformerFactory transformerFactory = TransformerFactory.newInstance();
433
                        Transformer transformer = transformerFactory.newTransformer();
434
                        DOMSource source = new DOMSource(xml);
435
                        StreamResult result = new StreamResult(bos);
436
                        transformer.transform(source, result);
437
 
438
                        DefaultStreamedContent arquivo = (DefaultStreamedContent) RelatorioUtils.gerarArquivo(bos.toByteArray(), "ArquivoXML", "xml");
439
                        return IOUtils.toByteArray(arquivo.getStream());
440
                } catch (Exception e) {
441
                        e.printStackTrace();
442
                } finally {
443
                        try {
444
                                in.close();
445
                                bos.close();
446
                        } catch (IOException e) {
447
                                e.printStackTrace();
448
                        }
449
                }
450
                return null;
451
        }
452
 
453
        @Transient
454
        public byte[] getRetornarArquivoXml() {
455
                setArquivoXml(criarArquivoXml());
456
                return getArquivoXml();
457
        }
458
 
459
        @Transient
460
        public void gerarChaveAcessoNfe(String codigoUFEmitente, String dataAAMM, String cnpjCpfEmitente, String modeloNf,
461
                        String serieNF, String tpEmissao, String numeroNF) {
462
                try {
463
            StringBuilder chave = new StringBuilder();
464
            chave.append(StringUtil.lpadTo(codigoUFEmitente, 2, '0'));
465
            chave.append(StringUtil.lpadTo(dataAAMM, 4, '0'));
466
            chave.append(StringUtil.lpadTo(cnpjCpfEmitente.replaceAll("\\D",""), 14, '0'));
467
            chave.append(StringUtil.lpadTo(modeloNf, 2, '0'));
468
            chave.append(StringUtil.lpadTo(serieNF, 3, '0'));
469
            chave.append(StringUtil.lpadTo(String.valueOf(numeroNF), 9, '0'));
470
            chave.append(StringUtil.lpadTo(tpEmissao, 1, '0'));
471
            chave.append(StringUtil.lpadTo(numeroNF, 8, '0'));
472
            chave.append(StringUtil.modulo11(chave.toString()));
473
            chave.insert(0, "NFe");
474
            setChave(chave.toString());
475
        } catch (Exception e) {
476
                System.out.println(e.toString());
477
                throw new NegocioException(e.getMessage());
478
        }
479
        }
480
 
481
        @Transient
482
        public Long getSequencialDaVenda() {
483
                return VerificadorUtil.naoEstaNulo(getVenda())? getVenda().getSequencial() : null;
484
        }
485
 
486
        @Transient
487
        public void preencherNumeroPelaChave() {
488
                if (VerificadorUtil.naoEstaNuloOuVazio(getChave())) {
489
                        setNumeroNotaFiscal(new Long(getChave().substring(25, 34)));
490
                }
491
        }
492
 
493
        @Transient
494
        public void preencherMotivoPadrao() {
495
                setMotivoRetorno("Autorizado o uso da NF-e");
496
        }
497
 
498
        @Transient
499
        public void preencherSeriePadrao() {
500
                setSerie("1");
501
        }
502
 
503
        @Transient
504
        public void preencherStatusPadrao() {
505
                setStatusRetorno("100");
506
        }
507
 
508
        @Transient
509
        public void preencherQRCodePadrao() {
510
                setCaminhoQrcode("http://nfce.sefaz.al.gov.br/QRCode/consultarNFCe.jsp?p=" + getChave() + "|2|1|1|437A52AD9DE9BDD04D6BFF55ED997C5199ECC64D");
511
        }
512
 
513
        @Transient
514
        public String retornarCodigoNumerico() {
515
                if (VerificadorUtil.naoEstaNuloOuVazio(getChave())) {
516
                        if (getChave().length() > 42) {
517
                                return getChave().substring(35, 43);
518
                        }
519
                }
520
                return "";
521
        }
522
 
523
        @Transient
524
        public void preencherComXML() {
525
                if (VerificadorUtil.naoEstaNuloOuVazio(this.getTextoXml())) {
526
                        TNfeProc tNfeProc = unmarshal(this.getTextoXml());
527
                        preencher(tNfeProc);
528
                }
529
 
530
        }
531
 
532
        @Transient
533
        public void preencher(TNfeProc nfeProc) {
534
                if (VerificadorUtil.naoEstaNulo(nfeProc)) {
535
                        if (VerificadorUtil.naoEstaNulo(nfeProc.getNFe())) {
536
                                if (VerificadorUtil.naoEstaNulo(nfeProc.getNFe().getInfNFe())) {
537
                                        if (VerificadorUtil.naoEstaNulo(nfeProc.getNFe().getInfNFe().getIde())) {
538
                                                //this.setCodigoNotaFiscal(new Long(nfeProc.getNFe().getInfNFe().getIde().getCNF()));
539
                                                this.setNumeroNotaFiscal(new Long(nfeProc.getNFe().getInfNFe().getIde().getNNF()));
540
                                                this.setSerie(nfeProc.getNFe().getInfNFe().getIde().getSerie());
541
                                                this.setDataHoraEmissao(DataUtil.retornarDataApartirString("yyyy-MM-dd'T'HH:mm:ss", nfeProc.getNFe().getInfNFe().getIde().getDhEmi()));
542
                                        }
543
                                        if (VerificadorUtil.naoEstaNulo(nfeProc.getNFe().getInfNFe().getInfAdic())) {
544
                                                this.setDescricaoComplementares(nfeProc.getNFe().getInfNFe().getInfAdic().getInfCpl());
545
                                        }
546
                                }
547
                                if (VerificadorUtil.naoEstaNulo(nfeProc.getNFe().getInfNFeSupl())) {}
548
                                if (VerificadorUtil.naoEstaNulo(nfeProc.getNFe().getSignature())) {}
549
                        }
550
                        if (VerificadorUtil.naoEstaNulo(nfeProc.getProtNFe())) {
551
                                if (VerificadorUtil.naoEstaNulo(nfeProc.getProtNFe().getInfProt())) {
552
                                        this.setChave(nfeProc.getProtNFe().getInfProt().getChNFe());
553
                                        this.setDataHoraEvento(DataUtil.retornarDataApartirString("yyyy-MM-dd'T'HH:mm:ss", nfeProc.getProtNFe().getInfProt().getDhRecbto()));
554
                                        this.setProtocoloAutorizacao(nfeProc.getProtNFe().getInfProt().getNProt());
555
                                        this.setStatusRetorno(nfeProc.getProtNFe().getInfProt().getCStat());
556
                                        this.setMotivoRetorno(nfeProc.getProtNFe().getInfProt().getXMotivo());
557
                                }
558
                        }
559
                }
560
        }
561
 
562
        @Transient
563
        public TNfeProc unmarshal(String stringXml) {
564
        JAXBContext context = null;
565
        try {
566
            context = JAXBContext.newInstance(nfce.java.TNfeProc.class);
567
            Unmarshaller unmarshaller = context.createUnmarshaller();
568
            return (TNfeProc) unmarshaller.unmarshal(new StreamSource(new StringReader(stringXml)));
569
        } catch (JAXBException e) {
570
            e.printStackTrace();
571
        }
572
        return null;
573
    }
574
 
575
}