DanfcePos   A
last analyzed

Complexity

Total Complexity 30

Size/Duplication

Total Lines 360
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 30
c 0
b 0
f 0
lcom 1
cbo 1
dl 0
loc 360
ccs 0
cts 212
cp 0
rs 10

15 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A loadNFCe() 0 17 4
A monta() 0 12 1
A printDanfe() 0 7 2
A getCommands() 0 5 1
A parteI() 0 23 2
A parteII() 0 10 1
A parteIII() 0 20 2
A parteIV() 0 8 1
A parteV() 0 16 2
A parteVI() 0 8 1
A parteVII() 0 26 3
A parteVIII() 0 33 5
A parteIX() 0 16 2
A tipoPag() 0 19 2
1
<?php
2
3
namespace Posprint;
4
5
/**
6
 * Esta classe foi colocada aqui apenas para facilitar
7
 * o desenvolvimento, seu local correto
8
 * em caso de contingência criar duas vias consumidor
9
 * e estabelecimento
10
 */
11
12
use Posprint\Printers\PrinterInterface;
13
use InvalidArgumentException;
14
15
class DanfcePos
16
{
17
    /**
18
     * NFCe
19
     * @var \SimpleXMLElement
20
     */
21
    protected $nfce;
22
    /**
23
     * protNFe
24
     * @var \SimpleXMLElement
25
     */
26
    protected $protNFe;
27
    /**
28
     * Printer
29
     * @var PrinterInterface
30
     */
31
    protected $printer;
32
    /**
33
     * Documento montado
34
     * @var array
35
     */
36
    protected $da = [];
37
    /**
38
     * Total de itens da NFCe
39
     * @var integer
40
     */
41
    protected $totItens = 0;
42
    
43
    /**
44
     * URI referente a pagina de consulta da NFCe pela chave de acesso
45
     * @var string
46
     */
47
    protected $uri = '';
48
    
49
    protected $aURI = [
50
      'AC' => 'http://sefaznet.ac.gov.br/nfce/consulta.xhtml',
51
      'AM' => 'http://sistemas.sefaz.am.gov.br/nfceweb/formConsulta.do',
52
      'BA' => 'http://nfe.sefaz.ba.gov.br/servicos/nfce/Modulos/Geral/NFCEC_consulta_chave_acesso.aspx',
53
      'MT' => 'https://www.sefaz.mt.gov.br/nfce/consultanfce',
54
      'MA' => 'http://www.nfce.sefaz.ma.gov.br/portal/consultaNFe.do?method=preFilterCupom&',
55
      'PA' => 'https://appnfc.sefa.pa.gov.br/portal/view/consultas/nfce/consultanfce.seam',
56
      'PB' => 'https://www.receita.pb.gov.br/ser/servirtual/documentos-fiscais/nfc-e/consultar-nfc-e',
57
      'PR' => 'http://www.sped.fazenda.pr.gov.br/modules/conteudo/conteudo.php?conteudo=100',
58
      'RJ' => 'http://www4.fazenda.rj.gov.br/consultaDFe/paginas/consultaChaveAcesso.faces',
59
      'RS' => 'https://www.sefaz.rs.gov.br/NFE/NFE-COM.aspx',
60
      'RO' => 'http://www.nfce.sefin.ro.gov.br/home.jsp',
61
      'RR' => 'https://www.sefaz.rr.gov.br/nfce/servlet/wp_consulta_nfce',
62
      'SE' => 'http://www.nfce.se.gov.br/portal/portalNoticias.jsp?jsp=barra-menu/servicos/consultaDANFENFCe.htm',
63
      'SP' => 'https://www.nfce.fazenda.sp.gov.br/NFCeConsultaPublica/Paginas/ConsultaPublica.aspx'
64
    ];
65
66
    /**
67
     * Carrega a impressora a ser usada
68
     * a mesma deverá já ter sido pré definida inclusive seu
69
     * conector
70
     * @param PrinterInterface $printer
71
     */
72
    public function __construct(PrinterInterface $printer)
73
    {
74
        $this->printer = $printer;
75
    }
76
    
77
    /**
78
     * Carrega a NFCe
79
     * @param string $nfcexml
80
     */
81
    public function loadNFCe($nfcexml)
82
    {
83
        $xml = $nfcexml;
84
        if (is_file($nfcexml)) {
85
            $xml = @file_get_contents($nfcexml);
86
        }
87
        if (empty($xml)) {
88
            throw new InvalidArgumentException('Não foi possivel ler o documento.');
89
        }
90
        $nfe = simplexml_load_string($xml, null, LIBXML_NOCDATA);
91
        $this->protNFe = $nfe->protNFe;
0 ignored issues
show
Bug introduced by
The property protNFe does not seem to exist in SimpleXMLElement.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
92
        $this->nfce = $nfe->NFe;
0 ignored issues
show
Bug introduced by
The property NFe does not seem to exist in SimpleXMLElement.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
93
        if (empty($this->protNFe)) {
94
            //NFe sem protocolo
95
            $this->nfce = $nfe;
96
        }
97
    }
98
    
99
    /**
100
     * Monta a DANFCE para uso de impressoras POS
101
     */
102
    public function monta()
103
    {
104
        $this->parteI();
105
        $this->parteII();
106
        $this->parteIII();
107
        $this->parteIV();
108
        $this->parteV();
109
        $this->parteVI();
110
        $this->parteVII();
111
        $this->parteVIII();
112
        $this->parteIX();
113
    }
114
    
115
    /**
116
     * Manda os dados para a impressora ou
117
     * retorna os comandos em ordem e legiveis
118
     * para a tela
119
     */
120
    public function printDanfe()
121
    {
122
        $resp = $this->printer->send();
123
        if (!empty($resp)) {
124
            echo str_replace("\n", "<br>", $resp);
125
        }
126
    }
127
    
128
    /**
129
     * Recupera a sequiencia de comandos para envio
130
     * posterior para a impressora por outro
131
     * meio como o QZ.io (tray)
132
     *
133
     * @return string
134
     */
135
    public function getCommands()
136
    {
137
        $aCmds = $this->printer->getBuffer('binA');
138
        return implode("\n", $aCmds);
139
    }
140
    
141
    /**
142
     * Parte I - Emitente
143
     * Dados do emitente
144
     * Campo Obrigatório
145
     */
146
    protected function parteI()
147
    {
148
        $razao = (string) $this->nfce->infNFe->emit->xNome;
149
        $cnpj = (string) $this->nfce->infNFe->emit->CNPJ;
150
        $ie = (string) $this->nfce->infNFe->emit->IE;
151
        $im = (string) $this->nfce->infNFe->emit->IM;
152
        $log = (string) $this->nfce->infNFe->emit->enderEmit->xLgr;
153
        $nro = (string) $this->nfce->infNFe->emit->enderEmit->nro;
154
        $bairro = (string) $this->nfce->infNFe->emit->enderEmit->xBairro;
155
        $mun = (string) $this->nfce->infNFe->emit->enderEmit->xMun;
156
        $uf = (string) $this->nfce->infNFe->emit->enderEmit->UF;
157
        if (array_key_exists($uf, $this->aURI)) {
158
            $this->uri = $this->aURI[$uf];
159
        }
160
        $this->printer->setAlign('C');
161
        $this->printer->text($razao);
162
        $this->printer->text('CNPJ: '.$cnpj.'     '.'IE: ' . $ie);
163
        $this->printer->text('IM: '.$im);
164
        $this->printer->setAlign('L');
165
        //o que acontece quando o texto é maior que o numero de carecteres da linha ??
166
        $this->printer->text($log . ', ' . $nro . ' ' . $bairro . ' ' . $mun . ' ' . $uf);
167
        //linha divisória ??
168
    }
169
    
170
    /**
171
     * Parte II - Informações Gerais
172
     * Campo Obrigatório
173
     */
174
    protected function parteII()
175
    {
176
        $this->printer->setAlign('C');
177
        $this->printer->text('DANFE NFC-e Documento Auxiliar');
178
        $this->printer->text('da Nota Fiscal eletrônica para consumidor final');
179
        $this->printer->setBold();
180
        $this->printer->text('Não permite aproveitamento de crédito de ICMS');
181
        $this->printer->setBold();
182
        //linha divisória ??
183
    }
184
    
185
    /**
186
     * Parte III - Detalhes da Venda
187
     * Campo Opcional
188
     */
189
    protected function parteIII()
190
    {
191
        $this->printer->setAlign('L');
192
        $this->printer->text('Item Cod   Desc         Qtd    V.Unit  V.Total');
193
        //obter dados dos itens da NFCe
194
        $det = $this->nfce->infNFe->det;
195
        $this->totItens = $det->count();
196
        for ($x=0; $x<=$this->totItens-1; $x++) {
197
            $nItem = (int) $det[$x]->attributes()->{'nItem'};
198
            $cProd = (string) $det[$x]->prod->cProd;
199
            $xProd = (string) $det[$x]->prod->xProd;
200
            $qCom = (float) $det[$x]->prod->qCom;
201
            $uCom = (string) $det[$x]->prod->uCom;
202
            $vUnCom = (float) $det[$x]->prod->vUnCom;
203
            $vProd = (float) $det[$x]->prod->vProd;
204
            //falta formatar os campos e o espaçamento entre eles
205
            $this->printer->text($nItem .  $cProd. $xProd . $qCom . $uCom . $vUnCom . $vProd);
206
        }
207
        //linha divisória ??
208
    }
209
    
210
    /**
211
     * Parte V - Informação de tributos
212
     * Campo Obrigatório
213
     */
214
    protected function parteIV()
215
    {
216
        $vTotTrib = (float) $this->nfce->infNFe->total->ICMSTot->vTotTrib;
217
        $this->printer->setAlign('L');
218
        $this->printer->text('Informação dos Tributos Totais:' . '' . 'R$ ' .  $vTotTrib);
219
        $this->printer->text('Incidentes (Lei Federal 12.741 /2012) - Fonte IBPT');
220
        //linha divisória ??
221
    }
222
    
223
    /**
224
     * Parte IV - Totais da Venda
225
     * Campo Obrigatório
226
     */
227
    protected function parteV()
228
    {
229
        $vNF = (float) $this->nfce->infNFe->total->ICMSTot->vNF;
230
        $this->printer->setAlign('L');
231
        $this->printer->text('QTD. TOTAL DE ITENS' . ' ' . $this->totItens);
232
        $this->printer->text('VALOR TOTAL            R$ ' . $vNF);
233
        $this->printer->text('FORMA PAGAMENTO          VALOR PAGO');
234
        $pag = $this->nfce->infNFe->pag;
235
        $tot = $pag->count();
236
        for ($x=0; $x<=$tot-1; $x++) {
237
            $tPag = (string) $this->tipoPag((string) $pag[0]->tPag);
238
            $vPag = (float) $pag[0]->vPag;
239
            $this->printer->text($tPag . '                  R$ '. $vPag);
240
        }
241
        //linha divisória ??
242
    }
243
    
244
    /**
245
     * Parte VI - Mensagem de Interesse do Contribuinte
246
     * conteudo de infCpl
247
     * Campo Opcional
248
     */
249
    protected function parteVI()
250
    {
251
        $infCpl = (string) $this->nfce->infNFe->infAdic->infCpl;
252
        $this->printer->setAlign('L');
253
        $this->printer->text($infCpl);
254
        $this->printer->lineFeed();
255
        //linha divisória ??
256
    }
257
    
258
    /**
259
     * Parte VII - Mensagem Fiscal e Informações da Consulta via Chave de Acesso
260
     * Campo Obrigatório
261
     */
262
    protected function parteVII()
263
    {
264
        $tpAmb = (int) $this->nfce->infNFe->ide->tpAmb;
265
        if ($tpAmb == 2) {
266
            $this->printer->setAlign('C');
267
            $this->printer->text('EMITIDA EM AMBIENTE DE HOMOLOGAÇÃO - SEM VALOR FISCAL');
268
        }
269
        $tpEmis = (int) $this->nfce->infNFe->ide->tpEmis;
270
        if ($tpEmis != 1) {
271
            $this->printer->setAlign('C');
272
            $this->printer->text('EMITIDA EM AMBIENTE DE CONTINGẼNCIA');
273
        }
274
        $nNF = (float) $this->nfce->infNFe->ide->nNF;
275
        $serie = (int) $this->nfce->infNFe->ide->serie;
276
        $dhEmi = (string) $this->nfce->infNFe->ide->dhEmi;
277
        $Id = (string) $this->nfce->infNFe->attributes()->{'Id'};
278
        $chave = substr($Id, 3, strlen($Id)-3);
279
        $this->printer->setAlign('L');
280
        $this->printer->text('Nr. ' . $nNF. ' Serie ' .$serie . ' Emissão ' .$dhEmi . ' via Consumidor');
281
        $this->printer->setAlign('C');
282
        $this->printer->text('Consulte pela chave de acesso em');
283
        $this->printer->text($this->uri);
284
        $this->printer->text('CHAVE DE ACESSO');
285
        $this->printer->text($chave);
286
        //linha divisória ??
287
    }
288
    
289
    /**
290
     * Parte VIII - Informações sobre o Consumidor
291
     * Campo Opcional
292
     */
293
    protected function parteVIII()
294
    {
295
        $this->printer->setAlign('C');
296
        $dest = $this->nfce->infNFe->dest;
297
        if (empty($dest)) {
298
            $this->printer->text('CONSUMIDOR NÃO IDENTIFICADO');
299
            return;
300
        }
301
        $xNome = (string) $this->nfce->infNFe->dest->xNome;
302
        $this->printer->text($xNome);
303
        $cnpj = (string) $this->nfce->infNFe->dest->CNPJ;
304
        $cpf = (string) $this->nfce->infNFe->dest->CPF;
305
        $idEstrangeiro = (string) $this->nfce->infNFe->dest->idEstrangeiro;
306
        $this->printer->setAlign('L');
307
        if (!empty($cnpj)) {
308
            $this->printer->text('CNPJ ' . $cnpj);
309
        }
310
        if (!empty($cpf)) {
311
            $this->printer->text('CPF ' . $cpf);
312
        }
313
        if (!empty($idEstrangeiro)) {
314
            $this->printer->text('Extrangeiro ' . $idEstrangeiro);
315
        }
316
        $xLgr = (string) $this->nfce->infNFe->dest->enderDest->xLgr;
317
        $nro = (string) $this->nfce->infNFe->dest->enderDest->nro;
318
        $xCpl = (string) $this->nfce->infNFe->dest->enderDest->xCpl;
319
        $xBairro = (string) $this->nfce->infNFe->dest->enderDest->xBairro;
320
        $xMun = (string) $this->nfce->infNFe->dest->enderDest->xMun;
321
        $uf = (string) $this->nfce->infNFe->dest->enderDest->UF;
322
        $cep = (string) $this->nfce->infNFe->dest->enderDest->CEP;
0 ignored issues
show
Unused Code introduced by
$cep is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
323
        $this->printer->text($xLgr . '' . $nro . '' . $xCpl . '' . $xBairro . '' . $xMun . '' . $uf);
324
        //linha divisória ??
325
    }
326
    
327
    /**
328
     * Parte IX - QRCode
329
     * Consulte via Leitor de QRCode
330
     * Protocolo de autorização 1234567891234567 22/06/2016 14:43:51
331
     * Campo Obrigatório
332
     */
333
    protected function parteIX()
334
    {
335
        $this->printer->setAlign('C');
336
        $this->printer->text('Consulte via Leitor de QRCode');
337
        $qr = (string) $this->nfce->infNFeSupl->qrCode;
338
        $this->printer->barcodeQRCode($qr);
339
        if (!empty($this->protNFe)) {
340
            $nProt = (string) $this->protNFe->infProt->nProt;
341
            $dhRecbto = (string) $this->protNFe->infProt->dhRecbto;
342
            $this->printer->text('Protocolo de autorização ' . $nProt . $dhRecbto);
343
        } else {
344
            $this->printer->setBold();
345
            $this->printer->text('NOTA FISCAL INVÁLIDA - SEM PROTOCOLO DE AUTORIZAÇÃO');
346
            $this->printer->lineFeed();
347
        }
348
    }
349
    
350
    /**
351
     * Retorna o texto referente ao tipo de pagamento efetuado
352
     * @param int $tPag
353
     * @return string
354
     */
355
    private function tipoPag($tPag)
356
    {
357
        $aPag = [
358
            '01' => 'Dinheiro',
359
            '02' => 'Cheque',
360
            '03' => 'Cartao de Credito',
361
            '04' => 'Cartao de Debito',
362
            '05' => 'Credito Loja',
363
            '10' => 'Vale Alimentacao',
364
            '11' => 'Vale Refeicao',
365
            '12' => 'Vale Presente',
366
            '13' => 'Vale Combustivel',
367
            '99' => 'Outros'
368
        ];
369
        if (array_key_exists($tPag, $aPag)) {
370
            return $aPag[$tPag];
371
        }
372
        return '';
373
    }
374
}
375