Passed
Push — master ( 28679e...eb8237 )
by Roberto
58s queued 10s
created

Tools::sefazAtorInteressado()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 15
cp 0
rs 9.504
c 0
b 0
f 0
cc 3
nc 3
nop 5
crap 12
1
<?php
2
3
namespace NFePHP\NFe;
4
5
/**
6
 * Class responsible for communication with SEFAZ extends
7
 * NFePHP\NFe\Common\Tools
8
 *
9
 * @category  NFePHP
10
 * @package   NFePHP\NFe\Tools
11
 * @copyright NFePHP Copyright (c) 2008-2020
12
 * @license   http://www.gnu.org/licenses/lgpl.txt LGPLv3+
13
 * @license   https://opensource.org/licenses/MIT MIT
14
 * @license   http://www.gnu.org/licenses/gpl.txt GPLv3+
15
 * @author    Roberto L. Machado <linux.rlm at gmail dot com>
16
 * @link      http://github.com/nfephp-org/sped-nfe for the canonical source repository
17
 */
18
19
use NFePHP\Common\Strings;
20
use NFePHP\Common\Signer;
21
use NFePHP\Common\UFList;
22
use NFePHP\NFe\Common\Tools as ToolsCommon;
23
use RuntimeException;
24
use InvalidArgumentException;
25
26
class Tools extends ToolsCommon
27
{
28
    const EVT_CONFIRMACAO = 210200; //only one per nfe seq=n
29
    const EVT_CIENCIA = 210210; //only one per nfe seq=1
30
    const EVT_DESCONHECIMENTO = 210220; //only one per nfe seq=n
31
    const EVT_NAO_REALIZADA = 210240; //only one per nfe but seq=n
32
    const EVT_CCE = 110110; //many seq=n
33
    const EVT_CANCELA = 110111; //only seq=1
34
    const EVT_CANCELASUBSTITUICAO = 110112;
35
    const EVT_EPEC = 110140; //only seq=1
36
    const EVT_ATORINTERESSADO = 110150;
37
38
    /**
39
     * Request authorization to issue NFe in batch with one or more documents
40
     * @param array $aXml array of nfe's xml
41
     * @param string $idLote lote number
42
     * @param int $indSinc flag to use synchronous communication
43
     * @param bool $compactar flag to compress data with gzip
44
     * @param array $xmls array with xmls substitutes if contigency is on
45
     * @return string soap response xml
46
     * @throws InvalidArgumentException
47
     */
48
    public function sefazEnviaLote(
49
        $aXml,
50
        $idLote = '',
51
        $indSinc = 0,
52
        $compactar = false,
53
        &$xmls = []
54
    ) {
55
        if (!is_array($aXml)) {
56
            throw new InvalidArgumentException('Envia Lote: XMLs de NF-e deve ser um array!');
57
        }
58
        if ($indSinc == 1 && count($aXml) > 1) {
59
            throw new InvalidArgumentException('Envio sincrono deve ser usado para enviar '
60
                . 'uma UNICA nota por vez. Você está tentando enviar varias.');
61
        }
62
        $servico = 'NfeAutorizacao';
63
        $this->checkContingencyForWebServices($servico);
64
        if ($this->contingency->type != '') {
65
            // Em modo de contingencia esses XMLs deverão ser modificados e re-assinados e retornados
66
            // no parametro $xmls para serem armazenados pelo aplicativo pois serão alterados.
67
            foreach ($aXml as $doc) {
68
                //corrigir o xml para o tipo de contigência setado
69
                $xmls[] = $this->correctNFeForContingencyMode($doc);
70
            }
71
            $aXml = $xmls;
72
        }
73
        $ax = [];
74
        foreach ($aXml as $xml) {
75
            $ax[] = trim(preg_replace("/<\?xml.*?\?>/", "", $xml));
76
        }
77
        $sxml = trim(implode("", $ax));
78
        $this->servico($servico, $this->config->siglaUF, $this->tpAmb);
79
        $request = "<enviNFe xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
80
            . "<idLote>$idLote</idLote>"
81
            . "<indSinc>$indSinc</indSinc>"
82
            . "$sxml"
83
            . "</enviNFe>";
84
        $this->isValid($this->urlVersion, $request, 'enviNFe');
85
        $this->lastRequest = $request;
86
        //montagem dos dados da mensagem SOAP
87
        $parameters = ['nfeDadosMsg' => $request];
88
        $body = "<nfeDadosMsg xmlns=\"$this->urlNamespace\">$request</nfeDadosMsg>";
89
        if ($compactar) {
90
            $gzdata = base64_encode(gzencode($request, 9, FORCE_GZIP));
91
            $parameters = ['nfeDadosMsgZip' => $gzdata];
92
            $body = "<nfeDadosMsgZip xmlns=\"$this->urlNamespace\">$gzdata</nfeDadosMsgZip>";
93
        }
94
        $this->lastResponse = $this->sendRequest($body, $parameters);
95
        return $this->lastResponse;
96
    }
97
98
    /**
99
     * Check status of Batch of NFe sent by receipt of this shipment
100
     * @param string $recibo
101
     * @param int $tpAmb
102
     * @return string
103
     * @throws InvalidArgumentException
104
     */
105 1
    public function sefazConsultaRecibo($recibo, $tpAmb = null)
106
    {
107 1
        if (empty($recibo)) {
108 1
            throw new InvalidArgumentException('Consulta Recibo: numero do recibo vazio!');
109
        }
110
        if (empty($tpAmb)) {
111
            $tpAmb = $this->tpAmb;
112
        }
113
        //carrega serviço
114
        $servico = 'NfeRetAutorizacao';
115
        $this->checkContingencyForWebServices($servico);
116
        $this->servico($servico, $this->config->siglaUF, $tpAmb);
117
        if ($this->urlService == '') {
118
            $msg = "A consulta de NFe nao esta disponivel na SEFAZ {$this->config->siglaUF}!";
119
            throw new RuntimeException($msg);
120
        }
121
        $request = "<consReciNFe xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
122
            . "<tpAmb>$tpAmb</tpAmb>"
123
            . "<nRec>$recibo</nRec>"
124
            . "</consReciNFe>";
125
        $this->isValid($this->urlVersion, $request, 'consReciNFe');
126
        $this->lastRequest = $request;
127
        $parameters = ['nfeDadosMsg' => $request];
128
        $body = "<nfeDadosMsg xmlns=\"$this->urlNamespace\">$request</nfeDadosMsg>";
129
        $this->lastResponse = $this->sendRequest($body, $parameters);
130
        return $this->lastResponse;
131
    }
132
133
    /**
134
     * Check the NFe status for the 44-digit key and retrieve the protocol
135
     * @param string $chave
136
     * @param int $tpAmb
137
     * @return string
138
     * @throws InvalidArgumentException
139
     */
140 3
    public function sefazConsultaChave($chave, $tpAmb = null)
141
    {
142 3
        if (empty($chave)) {
143 1
            throw new InvalidArgumentException('Consulta chave: a chave esta vazia!');
144
        }
145 2
        if (strlen($chave) != 44 || !is_numeric($chave)) {
146 2
            throw new InvalidArgumentException("Consulta chave: chave \"$chave\" invalida!");
147
        }
148
        $uf = UFList::getUFByCode(substr($chave, 0, 2));
149
        if (empty($tpAmb)) {
150
            $tpAmb = $this->tpAmb;
151
        }
152
        //carrega serviço
153
        $servico = 'NfeConsultaProtocolo';
154
        $this->checkContingencyForWebServices($servico);
155
        $this->servico($servico, $uf, $tpAmb);
156
        $request = "<consSitNFe xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
157
            . "<tpAmb>$tpAmb</tpAmb>"
158
            . "<xServ>CONSULTAR</xServ>"
159
            . "<chNFe>$chave</chNFe>"
160
            . "</consSitNFe>";
161
        $this->isValid($this->urlVersion, $request, 'consSitNFe');
162
        $this->lastRequest = $request;
163
        $parameters = ['nfeDadosMsg' => $request];
164
        $body = "<nfeDadosMsg xmlns=\"$this->urlNamespace\">$request</nfeDadosMsg>";
165
        $this->lastResponse = $this->sendRequest($body, $parameters);
166
        return $this->lastResponse;
167
    }
168
169
    /**
170
     * Request to disable one or an NFe sequence of a given series
171
     * @param int $nSerie
172
     * @param int $nIni
173
     * @param int $nFin
174
     * @param string $xJust
175
     * @param int $tpAmb
176
     * @param string $ano
177
     * @return string
178
     * @throws InvalidArgumentException
179
     */
180
    public function sefazInutiliza($nSerie, $nIni, $nFin, $xJust, $tpAmb = null, $ano = null)
181
    {
182
        if (empty($nIni) || empty($nFin) || empty($xJust)) {
183
            throw new InvalidArgumentException('Inutilizacao: parametros incompletos!');
184
        }
185
        if (empty($tpAmb)) {
186
            $tpAmb = $this->tpAmb;
187
        }
188
        $xJust = Strings::replaceUnacceptableCharacters($xJust);
189
        $servico = 'NfeInutilizacao';
190
        $this->checkContingencyForWebServices($servico);
191
        //carrega serviço
192
        $this->servico($servico, $this->config->siglaUF, $tpAmb);
193
        $cnpj = $this->config->cnpj;
194
        $strAno = $ano;
195
        if (empty($ano)) {
196
            $strAno = (string) date('y');
197
        }
198
        $strSerie = str_pad($nSerie, 3, '0', STR_PAD_LEFT);
199
        $strInicio = str_pad($nIni, 9, '0', STR_PAD_LEFT);
200
        $strFinal = str_pad($nFin, 9, '0', STR_PAD_LEFT);
201
        $idInut = "ID"
202
            . $this->urlcUF
203
            . $strAno
204
            . $cnpj
205
            . $this->modelo
206
            . $strSerie
207
            . $strInicio
208
            . $strFinal;
209
        //limpa os caracteres indesejados da justificativa
210
        $xJust = Strings::replaceUnacceptableCharacters($xJust);
211
        //montagem do corpo da mensagem
212
        $msg = "<inutNFe xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">" .
213
            "<infInut Id=\"$idInut\">" .
214
            "<tpAmb>$tpAmb</tpAmb>" .
215
            "<xServ>INUTILIZAR</xServ>" .
216
            "<cUF>$this->urlcUF</cUF>" .
217
            "<ano>$strAno</ano>" .
218
            "<CNPJ>$cnpj</CNPJ>" .
219
            "<mod>$this->modelo</mod>" .
220
            "<serie>$nSerie</serie>" .
221
            "<nNFIni>$nIni</nNFIni>" .
222
            "<nNFFin>$nFin</nNFFin>" .
223
            "<xJust>$xJust</xJust>" .
224
            "</infInut></inutNFe>";
225
        //assina a solicitação
226
        $request = Signer::sign(
227
            $this->certificate,
228
            $msg,
229
            'infInut',
230
            'Id',
231
            $this->algorithm,
232
            $this->canonical
233
        );
234
        $request = Strings::clearXmlString($request, true);
235
        $this->isValid($this->urlVersion, $request, 'inutNFe');
236
        $this->lastRequest = $request;
237
        $parameters = ['nfeDadosMsg' => $request];
238
        $body = "<nfeDadosMsg xmlns=\"$this->urlNamespace\">$request</nfeDadosMsg>";
239
        $this->lastResponse = $this->sendRequest($body, $parameters);
240
        return $this->lastResponse;
241
    }
242
243
    /**
244
     * Search for the registration data of an NFe issuer,
245
     * if in contingency mode this service will cause a
246
     * Exception and remember not all Sefaz have this service available,
247
     * so it will not work in some cases.
248
     * @param string $uf federation unit (abbreviation)
249
     * @param string $cnpj CNPJ number (optional)
250
     * @param string $iest IE number (optional)
251
     * @param string $cpf CPF number (optional)
252
     * @return string xml soap response
253
     * @throws InvalidArgumentException
254
     */
255
    public function sefazCadastro($uf, $cnpj = '', $iest = '', $cpf = '')
256
    {
257
        $filter = '';
258
        if (!empty($cnpj)) {
259
            $filter = "<CNPJ>$cnpj</CNPJ>";
260
        } elseif (!empty($iest)) {
261
            $filter = "<IE>$iest</IE>";
262
        } elseif (!empty($cpf)) {
263
            $filter = "<CPF>$cpf</CPF>";
264
        }
265
        if (empty($uf) || empty($filter)) {
266
            throw new InvalidArgumentException('Sigla UF esta vazia ou CNPJ+IE+CPF vazios!');
267
        }
268
        //carrega serviço
269
        $servico = 'NfeConsultaCadastro';
270
        $this->checkContingencyForWebServices($servico);
271
        $this->servico($servico, $uf, $this->tpAmb, true);
272
        $request = "<ConsCad xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
273
            . "<infCons>"
274
            . "<xServ>CONS-CAD</xServ>"
275
            . "<UF>$uf</UF>"
276
            . "$filter"
277
            . "</infCons>"
278
            . "</ConsCad>";
279
        if (strtoupper($uf) == 'MT') {
280
            $request = "<nfeDadosMsg>$request</nfeDadosMsg>" ;
281
        }
282
        $this->isValid($this->urlVersion, $request, 'consCad');
283
        $this->lastRequest = $request;
284
        $parameters = ['nfeDadosMsg' => $request];
285
        if ($this->urlVersion === '2.00') {
286
            $this->objHeader = new \SOAPHeader(
287
                $this->urlNamespace,
288
                'nfeCabecMsg',
289
                ['cUF' => $this->urlcUF, 'versaoDados' => $this->urlVersion]
290
            );
291
        }
292
        $body = "<nfeDadosMsg xmlns=\"$this->urlNamespace\">$request</nfeDadosMsg>";
293
        $this->lastResponse = $this->sendRequest($body, $parameters);
294
        return $this->lastResponse;
295
    }
296
297
    /**
298
     * Check services status SEFAZ/SVC
299
     * If $uf is empty use normal check with contingency
300
     * If $uf is NOT empty ignore contingency mode
301
     * @param string $uf  initials of federation unit
302
     * @param int $tpAmb
303
     * @return string xml soap response
304
     */
305
    public function sefazStatus($uf = '', $tpAmb = null)
306
    {
307
        if (empty($tpAmb)) {
308
            $tpAmb = $this->tpAmb;
309
        }
310
        $ignoreContingency = true;
311
        if (empty($uf)) {
312
            $uf = $this->config->siglaUF;
313
            $ignoreContingency = false;
314
        }
315
        $servico = 'NfeStatusServico';
316
        $this->checkContingencyForWebServices($servico);
317
        $this->servico($servico, $uf, $tpAmb, $ignoreContingency);
318
        $request = "<consStatServ xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
319
            . "<tpAmb>$tpAmb</tpAmb>"
320
            . "<cUF>$this->urlcUF</cUF>"
321
            . "<xServ>STATUS</xServ>"
322
            . "</consStatServ>";
323
        $this->isValid($this->urlVersion, $request, 'consStatServ');
324
        $this->lastRequest = $request;
325
        $parameters = ['nfeDadosMsg' => $request];
326
        $body = "<nfeDadosMsg xmlns=\"$this->urlNamespace\">$request</nfeDadosMsg>";
327
        $this->lastResponse = $this->sendRequest($body, $parameters);
328
        return $this->lastResponse;
329
    }
330
331
    /**
332
     * Service for the distribution of summary information and
333
     * electronic tax documents of interest to an actor.
334
     * @param integer $ultNSU  last NSU number recived
335
     * @param integer $numNSU  NSU number you wish to consult
336
     * @param string $fonte data source 'AN' and for some cases it may be 'RS'
337
     * @return string
338
     */
339
    public function sefazDistDFe($ultNSU = 0, $numNSU = 0, $fonte = 'AN')
340
    {
341
        //carrega serviço
342
        $servico = 'NfeDistribuicaoDFe';
343
        $this->checkContingencyForWebServices($servico);
344
        $this->servico($servico, $fonte, $this->tpAmb, true);
345
        $cUF = UFList::getCodeByUF($this->config->siglaUF);
346
        $cnpj = $this->config->cnpj;
347
        $ultNSU = str_pad($ultNSU, 15, '0', STR_PAD_LEFT);
348
        $tagNSU = "<distNSU><ultNSU>$ultNSU</ultNSU></distNSU>";
349
        if ($numNSU != 0) {
350
            $numNSU = str_pad($numNSU, 15, '0', STR_PAD_LEFT);
351
            $tagNSU = "<consNSU><NSU>$numNSU</NSU></consNSU>";
352
        }
353
        //monta a consulta
354
        $consulta = "<distDFeInt xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
355
            . "<tpAmb>".$this->tpAmb."</tpAmb>"
356
            . "<cUFAutor>$cUF</cUFAutor>";
357
        if ($this->typePerson === 'J') {
358
            $consulta .= "<CNPJ>$cnpj</CNPJ>";
359
        } else {
360
            $consulta .= "<CPF>$cnpj</CPF>";
361
        }
362
        $consulta .= "$tagNSU"
363
            . "</distDFeInt>";
364
        //valida o xml da requisição
365
        $this->isValid($this->urlVersion, $consulta, 'distDFeInt');
366
        $this->lastRequest = $consulta;
367
        //montagem dos dados da mensagem SOAP
368
        $request = "<nfeDadosMsg xmlns=\"$this->urlNamespace\">$consulta</nfeDadosMsg>";
369
        $parameters = ['nfeDistDFeInteresse' => $request];
370
        $body = "<nfeDistDFeInteresse xmlns=\"$this->urlNamespace\">"
371
            . $request
372
            . "</nfeDistDFeInteresse>";
373
        //este webservice não requer cabeçalho
374
        $this->objHeader = null;
375
        $this->lastResponse = $this->sendRequest($body, $parameters);
376
        return $this->lastResponse;
377
    }
378
379
    /**
380
     * Request authorization for Letter of Correction
381
     * @param string $chave
382
     * @param string $xCorrecao
383
     * @param int $nSeqEvento
384
     * @return string
385
     * @throws InvalidArgumentException
386
     */
387
    public function sefazCCe($chave, $xCorrecao, $nSeqEvento = 1)
388
    {
389
        if (empty($chave) || empty($xCorrecao)) {
390
            throw new InvalidArgumentException('CC-e: chave ou motivo da correcao vazio!');
391
        }
392
        $uf = $this->validKeyByUF($chave);
393
        $xCorrecao = Strings::replaceUnacceptableCharacters(substr(trim($xCorrecao), 0, 1000));
394
        $xCondUso = 'A Carta de Correcao e disciplinada pelo paragrafo '
395
            . '1o-A do art. 7o do Convenio S/N, de 15 de dezembro de 1970 '
396
            . 'e pode ser utilizada para regularizacao de erro ocorrido '
397
            . 'na emissao de documento fiscal, desde que o erro nao esteja '
398
            . 'relacionado com: I - as variaveis que determinam o valor '
399
            . 'do imposto tais como: base de calculo, aliquota, '
400
            . 'diferenca de preco, quantidade, valor da operacao ou da '
401
            . 'prestacao; II - a correcao de dados cadastrais que implique '
402
            . 'mudanca do remetente ou do destinatario; III - a data de '
403
            . 'emissao ou de saida.';
404
        $tagAdic = "<xCorrecao>"
405
            . $xCorrecao
406
            . "</xCorrecao><xCondUso>$xCondUso</xCondUso>";
407
        return $this->sefazEvento($uf, $chave, self::EVT_CCE, $nSeqEvento, $tagAdic);
408
    }
409
    
410
    /**
411
     * Evento do Ator Interessado
412
     * NOTA: NT2020.007
413
     * @param string $chave
414
     * @param int $tpAutor
415
     * @param string $verAplic
416
     * @param int $nSeqEvento
417
     * @param array $interessados
418
     * @return string
419
     */
420
    public function sefazAtorInteressado(
421
        $chave,
422
        $tpAutor,
423
        $verAplic,
424
        $nSeqEvento = 1,
425
        $interessados = []
426
    ) {
427
        $xCondUso = 'O emitente ou destinatário da NF-e, declara que permite o '
428
            . 'transportador declarado no campo CNPJ/CPF deste evento a '
429
            . 'autorizar os transportadores subcontratados ou redespachados '
430
            . 'a terem acesso ao download da NFe';
431
        $tagAdic = "<cOrgaoAutor>{$this->urlcUF}</cOrgaoAutor>"
432
            . "<tpAutor>{$tpAutor}</tpAutor>"
433
            . "<verAplic>{$verAplic}</verAplic>";
434
        foreach ($interessados as $aut) {
435
            $obj = (object) $aut;
436
            $tagAdic .= "<autXML>";
437
            $tagAdic .=  !empty($obj->CNPJ)
438
                ? "<CNPJ>{$obj->CNPJ}</CNPJ>"
439
                : "<CPF>{$obj->CPF}</CPF>";
440
            $tagAdic .= "<tpAutorizacao>{$obj->tpAutorizacao}</tpAutorizacao>"
441
                . "</autXML>";
442
        }
443
        $tagAdic .= "<xCondUso>$xCondUso</xCondUso>";
444
        return $this->sefazEvento($uf, $chave, self::EVT_ATORINTERESSADO, $nSeqEvento, $tagAdic);
0 ignored issues
show
Bug introduced by
The variable $uf does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
445
    }
446
447
    /**
448
     * Request extension of the term of return of products of an NF-e of
449
     * consignment for industrialization to order with suspension of ICMS
450
     * in interstate operations
451
     * @param  string  $chNFe
452
     * @param  string  $nProt
453
     * @param  integer $tipo 1-primerio prazo, 2-segundo prazo
454
     * @param  array   $itens
455
     * @param  integer $nSeqEvento
456
     * @return string
457
     */
458
    public function sefazEPP(
459
        $chNFe,
460
        $nProt,
461
        $itens = array(),
462
        $tipo = 1,
463
        $nSeqEvento = 1
464
    ) {
465
        $uf = UFList::getUFByCode(substr($chNFe, 0, 2));
466
        $tpEvento = 111500;
467
        if ($tipo == 2) {
468
            $tpEvento = 111501;
469
        }
470
        $tagAdic = "<nProt>$nProt</nProt>";
471
        foreach ($itens as $item) {
472
            $tagAdic .= "<itemPedido numItem=\""
473
                . $item[0]
474
                . "\"><qtdeItem>"
475
                . $item[1]
476
                ."</qtdeItem></itemPedido>";
477
        }
478
        return $this->sefazEvento(
479
            $uf,
480
            $chNFe,
481
            $tpEvento,
482
            $nSeqEvento,
483
            $tagAdic
484
        );
485
    }
486
487
    /**
488
     * Request the cancellation of the request for an extension of the term
489
     * of return of products of an NF-e of consignment for industrialization
490
     * by order with suspension of ICMS in interstate operations
491
     * @param string $chave
492
     * @param string $nProt
493
     * @param integer $nSeqEvento
494
     * @return string
495
     * @throws InvalidArgumentException
496
     */
497
    public function sefazECPP($chave, $nProt, $nSeqEvento = 1)
498
    {
499
        if (empty($chave) || empty($nProt)) {
500
            throw new InvalidArgumentException('A chave ou o numero do protocolo estao vazios!');
501
        }
502
        $uf = UFList::getUFByCode(substr($chave, 0, 2));
503
        $tpEvento = 111502;
504
        $origEvent = 111500;
505
        if ($nSeqEvento == 2) {
506
            $tpEvento = 111503;
507
            $origEvent = 111501;
508
        }
509
        $sSeqEvento = str_pad($nSeqEvento, 2, "0", STR_PAD_LEFT);
510
        $idPedidoCancelado = "ID$origEvent$chave$sSeqEvento";
511
        $tagAdic = "<idPedidoCancelado>"
512
                . "$idPedidoCancelado"
513
                . "</idPedidoCancelado>"
514
                . "<nProt>$nProt</nProt>";
515
        return $this->sefazEvento($uf, $chave, $tpEvento, $nSeqEvento, $tagAdic);
516
    }
517
518
    /**
519
     * Requires nfe cancellation
520
     * @param  string $chave key of NFe
521
     * @param  string $xJust justificative 255 characters max
522
     * @param  string $nProt protocol number
523
     * @return string
524
     * @throws InvalidArgumentException
525
     */
526
    public function sefazCancela($chave, $xJust, $nProt)
527
    {
528
        if (empty($chave) || empty($xJust) || empty($nProt)) {
529
            throw new InvalidArgumentException('Cancelamento: chave, just ou numprot vazio!');
530
        }
531
        $uf = $this->validKeyByUF($chave);
532
        $xJust = Strings::replaceUnacceptableCharacters(substr(trim($xJust), 0, 255));
533
        $nSeqEvento = 1;
534
        $tagAdic = "<nProt>$nProt</nProt><xJust>$xJust</xJust>";
535
        return $this->sefazEvento($uf, $chave, self::EVT_CANCELA, $nSeqEvento, $tagAdic);
536
    }
537
538
    /**
539
     * Requires nfe cancellation by substitution
540
     * @param  string $chave key of NFe
541
     * @param  string $xJust justificative 255 characters max
542
     * @param  string $nProt protocol number
543
     * @param  string $chNFeRef key of New NFe
544
     * @param  string $verAplic version of applicative
545
     * @return string
546
     * @throws InvalidArgumentException
547
     */
548
    public function sefazCancelaPorSubstituicao($chave, $xJust, $nProt, $chNFeRef, $verAplic)
549
    {
550
        if ($this->modelo != 65) {
551
            throw new InvalidArgumentException(
552
                'Cancelamento pro Substituição deve ser usado apenas para '
553
                . 'operações com modelo 65 NFCe'
554
            );
555
        }
556
        if (empty($chave) || empty($xJust) || empty($nProt)
557
            || empty($chNFeRef) || empty($verAplic)) {
558
            throw new InvalidArgumentException(
559
                'CancelamentoPorSubs: chave da NFCe cancelada, justificativa, '
560
                . 'protocolo, chave da NFCe substituta, ou versão do aplicativo '
561
                . 'emissor não podem ser vazios!'
562
            );
563
        }
564
        $uf = $this->validKeyByUF($chave);
565
        $xJust = Strings::replaceUnacceptableCharacters(substr(trim($xJust), 0, 255));
566
        $nSeqEvento = 1;
567
        $cOrgao = substr($chave, 0, 2);
568
        $tagAdic = "<cOrgaoAutor>$cOrgao</cOrgaoAutor>"
569
            . "<tpAutor>1</tpAutor>"
570
            . "<verAplic>$verAplic</verAplic>"
571
            . "<nProt>$nProt</nProt>"
572
            . "<xJust>$xJust</xJust>"
573
            . "<chNFeRef>$chNFeRef</chNFeRef>";
574
        return $this->sefazEvento($uf, $chave, self::EVT_CANCELASUBSTITUICAO, $nSeqEvento, $tagAdic);
575
    }
576
577
    /**
578
     * Request the registration of the manifestation of recipient
579
     * @param string $chave
580
     * @param int $tpEvento
581
     * @param string $xJust Justification for not carrying out the operation
582
     * @param int $nSeqEvento
583
     * @return string
584
     * @throws InvalidArgumentException
585
     */
586
    public function sefazManifesta($chave, $tpEvento, $xJust = '', $nSeqEvento = 1)
587
    {
588
        if (empty($chave) || empty($tpEvento)) {
589
            throw new InvalidArgumentException('Manifestacao: chave ou tipo de evento vazio!');
590
        }
591
        $tagAdic = '';
592
        if ($tpEvento == self::EVT_NAO_REALIZADA) {
593
            $xJust = Strings::replaceUnacceptableCharacters(substr(trim($xJust), 0, 255));
594
            $tagAdic = "<xJust>$xJust</xJust>";
595
        }
596
        return $this->sefazEvento('AN', $chave, $tpEvento, $nSeqEvento, $tagAdic);
597
    }
598
599
    /**
600
     * Request the registration of the manifestation of recipient in batch
601
     * @param \stdClass $std
602
     * @return string
603
     * @throws InvalidArgumentException
604
     * @throws RuntimeException
605
     */
606
    public function sefazManifestaLote(\stdClass $std)
607
    {
608
        $allowed = [
609
            self::EVT_CONFIRMACAO,
610
            self::EVT_CIENCIA,
611
            self::EVT_DESCONHECIMENTO,
612
            self::EVT_NAO_REALIZADA,
613
        ];
614
        if (empty($std) || empty($std->evento)) {
615
            throw new InvalidArgumentException('Manifestacao: parametro "std" ou evento estao vazios!');
616
        }
617
        if (count($std->evento) > 20) {
618
            throw new RuntimeException('Manifestacao: o lote de eventos esta limitado a 20!');
619
        }
620
        $evt = new \stdClass();
621
        $i = 0;
622
        foreach ($std->evento as $s) {
623
            if (!in_array($s->tpEvento, $allowed)) { // se o evento não estiver entre os permitidos ignore
624
                continue;
625
            }
626
            $tagAdic = '';
627
            if ($s->tpEvento == self::EVT_NAO_REALIZADA) {
628
                $xJust = Strings::replaceUnacceptableCharacters(substr(trim($s->xJust), 0, 255));
629
                $tagAdic = "<xJust>$xJust</xJust>";
630
            }
631
            $evt->evento[$i] = new \stdClass();
632
            $evt->evento[$i]->chave = $s->chNFe;
633
            $evt->evento[$i]->tpEvento = $s->tpEvento;
634
            $evt->evento[$i]->nSeqEvento = $s->nSeqEvento;
635
            $evt->evento[$i]->tagAdic = $tagAdic;
636
            $i++;
637
        }
638
        return $this->sefazEventoLote('AN', $evt);
639
    }
640
641
    /**
642
     * Send event to SEFAZ in batch
643
     * @param string $uf
644
     * @param \stdClass $std
645
     * @return string
646
     * @throws RuntimeException
647
     * @throws InvalidArgumentException
648
     */
649
    public function sefazEventoLote($uf, \stdClass $std)
650
    {
651
        if (empty($uf) || empty($std)) {
652
            throw new InvalidArgumentException('Evento Lote: UF ou parametro "std" vazio!');
653
        }
654
        if (count($std->evento) > 20) {
655
            throw new RuntimeException('Evento Lote: o lote de eventos esta limitado a 20!');
656
        }
657
        $servico = 'RecepcaoEvento';
658
        $this->checkContingencyForWebServices($servico);
659
        $this->servico($servico, $uf, $this->tpAmb, false);
660
        $batchRequest = '';
661
        foreach ($std->evento as $evt) {
662
            if ($evt->tpEvento == self::EVT_EPEC) {
663
                continue; //não é possivel enviar EPEC com outros eventos
664
            }
665
            $ev = $this->tpEv($evt->tpEvento);
666
            $descEvento = $ev->desc;
667
            $cnpj = $this->config->cnpj;
668
            $dt = new \DateTime('now', new \DateTimeZone($this->timezone));
669
            $dhEvento = $dt->format('Y-m-d\TH:i:sP');
670
            $sSeqEvento = str_pad($evt->nSeqEvento, 2, "0", STR_PAD_LEFT);
671
            $eventId = "ID".$evt->tpEvento.$evt->chave.$sSeqEvento;
672
            $cOrgao = UFList::getCodeByUF($uf);
673
            $request = "<evento xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
674
                . "<infEvento Id=\"$eventId\">"
675
                . "<cOrgao>$cOrgao</cOrgao>"
676
                . "<tpAmb>$this->tpAmb</tpAmb>";
677
            if ($this->typePerson === 'J') {
678
                $request .= "<CNPJ>$cnpj</CNPJ>";
679
            } else {
680
                $request .= "<CPF>$cnpj</CPF>";
681
            }
682
            $request .= "<chNFe>$evt->chave</chNFe>"
683
                . "<dhEvento>$dhEvento</dhEvento>"
684
                . "<tpEvento>$evt->tpEvento</tpEvento>"
685
                . "<nSeqEvento>$evt->nSeqEvento</nSeqEvento>"
686
                . "<verEvento>$this->urlVersion</verEvento>"
687
                . "<detEvento versao=\"$this->urlVersion\">"
688
                . "<descEvento>$descEvento</descEvento>"
689
                . "$evt->tagAdic"
690
                . "</detEvento>"
691
                . "</infEvento>"
692
                . "</evento>";
693
            //assinatura dos dados
694
            $request = Signer::sign(
695
                $this->certificate,
696
                $request,
697
                'infEvento',
698
                'Id',
699
                $this->algorithm,
700
                $this->canonical
701
            );
702
            $batchRequest .= Strings::clearXmlString($request, true);
703
        }
704
        $dt = new \DateTime('now', new \DateTimeZone($this->timezone));
705
        $lote = $dt->format('YmdHis') . rand(0, 9);
706
        $request = "<envEvento xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
707
            . "<idLote>$lote</idLote>"
708
            . $batchRequest
709
            . "</envEvento>";
710
        $this->isValid($this->urlVersion, $request, 'envEvento');
711
        $this->lastRequest = $request;
712
        $parameters = ['nfeDadosMsg' => $request];
713
        $body = "<nfeDadosMsg xmlns=\"$this->urlNamespace\">$request</nfeDadosMsg>";
714
        $this->lastResponse = $this->sendRequest($body, $parameters);
715
        return $this->lastResponse;
716
    }
717
718
    /**
719
     * Request authorization for issuance in contingency EPEC
720
     * @param  string $xml
721
     * @return string
722
     * @throws InvalidArgumentException
723
     * @throws RuntimeException
724
     */
725
    public function sefazEPEC(&$xml)
726
    {
727
        if (empty($xml)) {
728
            throw new InvalidArgumentException('EPEC: parametro xml esta vazio!');
729
        }
730
        $nSeqEvento = 1;
731
        if ($this->contingency->type !== 'EPEC') {
732
            throw new RuntimeException('A contingencia EPEC deve estar ativada!');
733
        }
734
        $xml = $this->correctNFeForContingencyMode($xml);
735
        $dom = new \DOMDocument('1.0', 'UTF-8');
736
        $dom->preserveWhiteSpace = false;
737
        $dom->formatOutput = false;
738
        $dom->loadXML($xml);
739
        $infNFe = $dom->getElementsByTagName('infNFe')->item(0);
740
        $emit = $dom->getElementsByTagName('emit')->item(0);
741
        $dest = $dom->getElementsByTagName('dest')->item(0);
742
        $cOrgaoAutor = UFList::getCodeByUF($this->config->siglaUF);
743
        $chNFe = substr($infNFe->getAttribute('Id'), 3, 44);
744
        // EPEC
745
        $dhEmi = $dom->getElementsByTagName('dhEmi')->item(0)->nodeValue;
746
        $tpNF = $dom->getElementsByTagName('tpNF')->item(0)->nodeValue;
747
        $emitIE = $emit->getElementsByTagName('IE')->item(0)->nodeValue;
748
        $destUF = $dest->getElementsByTagName('UF')->item(0)->nodeValue;
749
        $total = $dom->getElementsByTagName('total')->item(0);
750
        $vNF = $total->getElementsByTagName('vNF')->item(0)->nodeValue;
751
        $vICMS = $total->getElementsByTagName('vICMS')->item(0)->nodeValue;
752
        $vST = $total->getElementsByTagName('vST')->item(0)->nodeValue;
753
        $dID = !empty($dest->getElementsByTagName('CNPJ')->item(0)) ?
754
                $dest->getElementsByTagName('CNPJ')->item(0)->nodeValue : null;
755
        if (!empty($dID)) {
756
            $destID = "<CNPJ>$dID</CNPJ>";
757
        } else {
758
            $dID = $dest->getElementsByTagName('CPF')->item(0)->nodeValue;
759
            if (!empty($dID)) {
760
                $destID = "<CPF>$dID</CPF>";
761
            } else {
762
                $dID = $dest->getElementsByTagName('idEstrangeiro')
763
                    ->item(0)
764
                    ->nodeValue;
765
                $destID = "<idEstrangeiro>$dID</idEstrangeiro>";
766
            }
767
        }
768
        $dIE = !empty($dest->getElementsByTagName('IE')->item(0)->nodeValue) ?
769
                $dest->getElementsByTagName('IE')->item(0)->nodeValue : '';
770
        $destIE = '';
771
        if (!empty($dIE)) {
772
            $destIE = "<IE>$dIE</IE>";
773
        }
774
        $tagAdic = "<cOrgaoAutor>$cOrgaoAutor</cOrgaoAutor>"
775
            . "<tpAutor>1</tpAutor>"
776
            . "<verAplic>$this->verAplic</verAplic>"
777
            . "<dhEmi>$dhEmi</dhEmi>"
778
            . "<tpNF>$tpNF</tpNF>"
779
            . "<IE>$emitIE</IE>"
780
            . "<dest>"
781
            . "<UF>$destUF</UF>"
782
            . $destID
783
            . $destIE
784
            . "<vNF>$vNF</vNF>"
785
            . "<vICMS>$vICMS</vICMS>"
786
            . "<vST>$vST</vST>"
787
            . "</dest>";
788
789
        return $this->sefazEvento('AN', $chNFe, self::EVT_EPEC, $nSeqEvento, $tagAdic);
790
    }
791
792
    /**
793
     * Send event to SEFAZ
794
     * @param string $uf
795
     * @param string $chave
796
     * @param int $tpEvento
797
     * @param int $nSeqEvento
798
     * @param string $tagAdic
799
     * @return string
800
     */
801
    public function sefazEvento(
802
        $uf,
803
        $chave,
804
        $tpEvento,
805
        $nSeqEvento = 1,
806
        $tagAdic = ''
807
    ) {
808
        $ignore = $tpEvento == self::EVT_EPEC;
809
        $servico = 'RecepcaoEvento';
810
        $this->checkContingencyForWebServices($servico);
811
        $this->servico($servico, $uf, $this->tpAmb, $ignore);
812
        $ev = $this->tpEv($tpEvento);
813
        $descEvento = $ev->desc;
814
        $cnpj = isset($this->config->cnpj) ? $this->config->cnpj : '';
815
        $dt = new \DateTime(date("Y-m-d H:i:sP"), new \DateTimeZone($this->timezone));
816
        $dhEvento = $dt->format('Y-m-d\TH:i:sP');
817
        $sSeqEvento = str_pad($nSeqEvento, 2, "0", STR_PAD_LEFT);
818
        $eventId = "ID".$tpEvento.$chave.$sSeqEvento;
819
        $cOrgao = UFList::getCodeByUF($uf);
820
        $request = "<evento xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
821
            . "<infEvento Id=\"$eventId\">"
822
            . "<cOrgao>$cOrgao</cOrgao>"
823
            . "<tpAmb>$this->tpAmb</tpAmb>";
824
        if ($this->typePerson === 'J') {
825
            $request .= "<CNPJ>$cnpj</CNPJ>";
826
        } else {
827
            $request .= "<CPF>$cnpj</CPF>";
828
        }
829
        $request .= "<chNFe>$chave</chNFe>"
830
            . "<dhEvento>$dhEvento</dhEvento>"
831
            . "<tpEvento>$tpEvento</tpEvento>"
832
            . "<nSeqEvento>$nSeqEvento</nSeqEvento>"
833
            . "<verEvento>$this->urlVersion</verEvento>"
834
            . "<detEvento versao=\"$this->urlVersion\">"
835
            . "<descEvento>$descEvento</descEvento>"
836
            . "$tagAdic"
837
            . "</detEvento>"
838
            . "</infEvento>"
839
            . "</evento>";
840
        //assinatura dos dados
841
        $request = Signer::sign(
842
            $this->certificate,
843
            $request,
844
            'infEvento',
845
            'Id',
846
            $this->algorithm,
847
            $this->canonical
848
        );
849
        $request = Strings::clearXmlString($request, true);
850
        $lote = $dt->format('YmdHis').rand(0, 9);
851
        $request = "<envEvento xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
852
            . "<idLote>$lote</idLote>"
853
            . $request
854
            . "</envEvento>";
855
        $this->isValid($this->urlVersion, $request, 'envEvento');
856
        $this->lastRequest = $request;
857
        //return $request;
858
        $parameters = ['nfeDadosMsg' => $request];
859
        $body = "<nfeDadosMsg xmlns=\"$this->urlNamespace\">$request</nfeDadosMsg>";
860
        $this->lastResponse = $this->sendRequest($body, $parameters);
861
        return $this->lastResponse;
862
    }
863
864
    /**
865
     * Request the NFe download already manifested by its recipient, by the key
866
     * using new service in NfeDistribuicaoDFe
867
     * NOTA: NfeDownloadNF is deactivated
868
     * @param  string $chave
869
     * @return string
870
     * @throws InvalidArgumentException
871
     */
872
    public function sefazDownload($chave)
873
    {
874
        if (empty($chave)) {
875
            throw new InvalidArgumentException('Download: chave esta vazia!');
876
        }
877
        //carrega serviço
878
        $servico = 'NfeDistribuicaoDFe';
879
        $this->checkContingencyForWebServices($servico);
880
        $this->servico($servico, 'AN', $this->tpAmb, true);
881
        $cUF = UFList::getCodeByUF($this->config->siglaUF);
882
        $tagChave = "<consChNFe><chNFe>$chave</chNFe></consChNFe>";
883
        $cnpj = $this->config->cnpj;
884
        //monta a consulta
885
        $request = "<distDFeInt xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
886
            . "<tpAmb>".$this->tpAmb."</tpAmb>"
887
            . "<cUFAutor>$cUF</cUFAutor>";
888
        if ($this->typePerson === 'J') {
889
            $request .= "<CNPJ>$cnpj</CNPJ>";
890
        } else {
891
            $request .= "<CPF>$cnpj</CPF>";
892
        }
893
        $request .= "$tagChave"
894
            . "</distDFeInt>";
895
        //valida o xml da requisição
896
        $this->isValid($this->urlVersion, $request, 'distDFeInt');
897
        $this->lastRequest = $request;
898
        //montagem dos dados da mensagem SOAP
899
        $request = "<nfeDadosMsg xmlns=\"$this->urlNamespace\">$request</nfeDadosMsg>";
900
        $parameters = ['nfeDistDFeInteresse' => $request];
901
        $body = "<nfeDistDFeInteresse xmlns=\"$this->urlNamespace\">"
902
            . $request
903
            . "</nfeDistDFeInteresse>";
904
        //este webservice não requer cabeçalho
905
        $this->objHeader = null;
906
        $this->lastResponse = $this->sendRequest($body, $parameters);
907
        return $this->lastResponse;
908
    }
909
910
    /**
911
     * Maintenance of the Taxpayer Security Code - CSC (Old Token)
912
     * @param int $indOp Identificador do tipo de operação:
913
     *                   1 - Consulta CSC Ativos;
914
     *                   2 - Solicita novo CSC;
915
     *                   3 - Revoga CSC Ativo
916
     * @return string
917
     * @throws InvalidArgumentException
918
     * @throws RuntimeException
919
     */
920
    public function sefazCsc($indOp)
921
    {
922
        if (empty($indOp) || $indOp < 1 || $indOp > 3) {
923
            throw new InvalidArgumentException('CSC: identificador operacao invalido!');
924
        }
925
        if ($this->modelo != 65) {
926
            throw new RuntimeException('CSC: modelo diferente de 65!');
927
        }
928
        $raizCNPJ = substr($this->config->cnpj, 0, -6);
929
        //carrega serviço
930
        $servico = 'CscNFCe';
931
        $this->checkContingencyForWebServices($servico);
932
        $this->servico($servico, $this->config->siglaUF, $this->tpAmb);
933
        $request = "<admCscNFCe versao=\"$this->urlVersion\" xmlns=\"$this->urlPortal\">"
934
            . "<tpAmb>$this->tpAmb</tpAmb>"
935
            . "<indOp>$indOp</indOp>"
936
            . "<raizCNPJ>$raizCNPJ</raizCNPJ>"
937
            . "</admCscNFCe>";
938
        if ($indOp == 3) {
939
            $request = "<admCscNFCe versao=\"$this->urlVersion\" xmlns=\"$this->urlPortal\">"
940
            . "<tpAmb>$this->tpAmb</tpAmb>"
941
            . "<indOp>$indOp</indOp>"
942
            . "<raizCNPJ>$raizCNPJ</raizCNPJ>"
943
            . "<dadosCsc>"
944
            . "<idCsc>".$this->config->CSCid."</idCsc>"
945
            . "<codigoCsc>".$this->config->CSC."</codigoCsc>"
946
            . "</dadosCsc>"
947
            . "</admCscNFCe>";
948
        }
949
        //o xsd não está disponivel
950
        //$this->isValid($this->urlVersion, $request, 'cscNFCe');
951
        $this->lastRequest = $request;
952
        $parameters = ['nfeDadosMsg' => $request];
953
        $body = "<nfeDadosMsg xmlns=\"$this->urlNamespace\">$request</nfeDadosMsg>";
954
        $this->lastResponse = $this->sendRequest($body, $parameters);
955
        return $this->lastResponse;
956
    }
957
958
    /**
959
     * Checks the validity of an NFe, normally used for received NFe
960
     * @param string $nfe
961
     * @return bool
962
     * @throws InvalidArgumentException
963
     */
964
    public function sefazValidate($nfe)
965
    {
966
        if (empty($nfe)) {
967
            throw new InvalidArgumentException('Validacao NF-e: a string da NF-e esta vazia!');
968
        }
969
        //verifica a assinatura da NFe, exception caso de falha
970
        Signer::isSigned($nfe);
971
        $dom = new \DOMDocument('1.0', 'utf-8');
972
        $dom->formatOutput = false;
973
        $dom->preserveWhiteSpace = false;
974
        $dom->loadXML($nfe);
975
        //verifica a validade no webservice da SEFAZ
976
        $tpAmb = $dom->getElementsByTagName('tpAmb')->item(0)->nodeValue;
977
        $infNFe  = $dom->getElementsByTagName('infNFe')->item(0);
978
        $chNFe = preg_replace('/[^0-9]/', '', $infNFe->getAttribute("Id"));
979
        $protocol = $dom->getElementsByTagName('nProt')->item(0)->nodeValue;
980
        $digval = $dom->getElementsByTagName('DigestValue')->item(0)->nodeValue;
981
        //consulta a NFe
982
        $response = $this->sefazConsultaChave($chNFe, $tpAmb);
983
        $ret = new \DOMDocument('1.0', 'UTF-8');
984
        $ret->preserveWhiteSpace = false;
985
        $ret->formatOutput = false;
986
        $ret->loadXML($response);
987
        $retProt = $ret->getElementsByTagName('protNFe')->item(0);
988
        if (!isset($retProt)) {
989
            $xMotivo = $ret->getElementsByTagName('xMotivo')->item(0);
990
            if (isset($xMotivo)) {
991
                throw new InvalidArgumentException('Validacao NF-e: ' . $xMotivo->nodeValue);
992
            } else {
993
                throw new InvalidArgumentException('O documento de resposta nao contem o node "protNFe".');
994
            }
995
        }
996
        $infProt = $ret->getElementsByTagName('infProt')->item(0);
997
        $dig = $infProt->getElementsByTagName("digVal")->item(0);
998
        $digProt = '000';
999
        if (isset($dig)) {
1000
            $digProt = $dig->nodeValue;
1001
        }
1002
        $chProt = $infProt->getElementsByTagName("chNFe")->item(0)->nodeValue;
1003
        $nProt = $infProt->getElementsByTagName("nProt")->item(0)->nodeValue;
1004
        if ($protocol == $nProt && $digval == $digProt && $chNFe == $chProt) {
1005
            return true;
1006
        }
1007
        return false;
1008
    }
1009
1010
    /**
1011
     * Returns alias and description event from event code.
1012
     * @param  int $tpEvento
1013
     * @return \stdClass
1014
     * @throws \RuntimeException
1015
     */
1016
    private function tpEv($tpEvento)
1017
    {
1018
        $std = new \stdClass();
1019
        $std->alias = '';
1020
        $std->desc = '';
1021
        switch ($tpEvento) {
1022
            case self::EVT_CCE:
1023
                $std->alias = 'CCe';
1024
                $std->desc = 'Carta de Correcao';
1025
                break;
1026
            case self::EVT_CANCELA:
1027
                $std->alias = 'CancNFe';
1028
                $std->desc = 'Cancelamento';
1029
                break;
1030
            case self::EVT_CANCELASUBSTITUICAO:
1031
                $std->alias = 'CancNFe';
1032
                $std->desc = 'Cancelamento por substituicao';
1033
                break;
1034
            case self::EVT_EPEC: // Emissão em contingência EPEC
1035
                $std->alias = 'EPEC';
1036
                $std->desc = 'EPEC';
1037
                break;
1038
            case 111500:
1039
            case 111501:
1040
                //EPP
1041
                //Pedido de prorrogação
1042
                $std->alias = 'EPP';
1043
                $std->desc = 'Pedido de Prorrogacao';
1044
                break;
1045
            case 111502:
1046
            case 111503:
1047
                //ECPP
1048
                //Cancelamento do Pedido de prorrogação
1049
                $std->alias = 'ECPP';
1050
                $std->desc = 'Cancelamento de Pedido de Prorrogacao';
1051
                break;
1052
            case self::EVT_CONFIRMACAO: // Manifestação Confirmacao da Operação
1053
                $std->alias = 'EvConfirma';
1054
                $std->desc = 'Confirmacao da Operacao';
1055
                break;
1056
            case self::EVT_CIENCIA: // Manifestação Ciencia da Operação
1057
                $std->alias = 'EvCiencia';
1058
                $std->desc = 'Ciencia da Operacao';
1059
                $std->tpAutor = 2;
1060
                break;
1061
            case self::EVT_DESCONHECIMENTO: // Manifestação Desconhecimento da Operação
1062
                $std->alias = 'EvDesconh';
1063
                $std->desc = 'Desconhecimento da Operacao';
1064
                break;
1065
            case self::EVT_NAO_REALIZADA: // Manifestação Operacao não Realizada
1066
                $std->alias = 'EvNaoRealizada';
1067
                $std->desc = 'Operacao nao Realizada';
1068
                break;
1069
            case self::EVT_ATORINTERESSADO: //ator interessado
1070
                $std->alias = 'EvAtorInteressado';
1071
                $std->desc = 'Ator interessado na NF-e';
1072
                break;
1073
            default:
1074
                $msg = "O código do tipo de evento informado não corresponde a "
1075
                . "nenhum evento estabelecido.";
1076
                throw new RuntimeException($msg);
1077
        }
1078
        return $std;
1079
    }
1080
}
1081