Passed
Push — master ( a1e314...1d4724 )
by Luiz Kim
01:33
created

CreateDacteAction::montaChave()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 15
nc 2
nop 9
dl 0
loc 19
rs 9.7666
c 1
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
namespace ControleOnline\Controller;
4
5
6
use Symfony\Component\HttpFoundation\Request;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpFoundation\Request was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Doctrine\ORM\EntityManagerInterface;
0 ignored issues
show
Bug introduced by
The type Doctrine\ORM\EntityManagerInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Symfony\Component\HttpFoundation\JsonResponse;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpFoundation\JsonResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use ControleOnline\Entity\SalesOrder as Order;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\SalesOrder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use ControleOnline\Entity\SalesInvoiceTax;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\SalesInvoiceTax was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use ControleOnline\Entity\SalesOrderInvoiceTax;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\SalesOrderInvoiceTax was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use ControleOnline\Entity\Config;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\Config was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use NFePHP\CTe\Tools;
0 ignored issues
show
Bug introduced by
The type NFePHP\CTe\Tools was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use NFePHP\CTe\Common\Standardize;
0 ignored issues
show
Bug introduced by
The type NFePHP\CTe\Common\Standardize was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
use NFePHP\Common\Certificate;
0 ignored issues
show
Bug introduced by
The type NFePHP\Common\Certificate was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
use NFePHP\CTe\MakeCTe;
0 ignored issues
show
Bug introduced by
The type NFePHP\CTe\MakeCTe was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
17
use Symfony\Component\HttpKernel\KernelInterface;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpKernel\KernelInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
19
class CreateDacteAction
20
{
21
    /**
22
     * Entity Manager
23
     *
24
     * @var EntityManagerInterface
25
     */
26
    private $manager = null;
27
    private $tools;
28
    private $appKernel;
29
30
    public function __construct(EntityManagerInterface $entityManager, KernelInterface $appKernel)
31
    {
32
        $this->manager = $entityManager;
33
        $this->appKernel = $appKernel;
34
    }
35
36
37
38
    public function __invoke(Order $data, Request $request): JsonResponse
39
    {
40
        try {
41
42
            //tanto o config.json como o certificado.pfx podem estar
43
            //armazenados em uma base de dados, então não é necessário
44
            ///trabalhar com arquivos, este script abaixo serve apenas como
45
            //exemplo durante a fase de desenvolvimento e testes.
46
47
            $provider = $data->getProvider();
48
            $document = $provider->getOneDocument();
49
50
            $dacteKey = $this->manager->getRepository(Config::class)->findOneBy([
51
                'people'  => $provider,
52
                'config_key' => 'dacte-key'
53
            ]);
54
55
            $dacteKeyPass = $this->manager->getRepository(Config::class)->findOneBy([
56
                'people'  => $provider,
57
                'config_key' => 'dacte-key-pass'
58
            ]);
59
            if (!$dacteKey || !$dacteKeyPass)
60
                throw new \Exception("DACTE key cert is required", 1);
61
62
63
64
            $certPath = $this->appKernel->getProjectDir() . $dacteKey->getConfigValue();
65
            if (!is_file($certPath))
66
                throw new \Exception("DACTE key cert path is invalid", 1);
67
68
69
            /**
70
             * @var \ControleOnline\Entity\Address $providerAddress
71
             */
72
            $providerAddress = $provider->getAddress()[0];
73
74
75
            //carrega o conteudo do certificado.
76
            $content = file_get_contents($certPath);
77
            $arr = [
78
                "atualizacao" => date('Y-m-d H:m:i'),
79
                "tpAmb" => 2, //2 - Homologação / 1 - Produção
80
                "razaosocial" => $provider->getName(),
81
                "cnpj" => $document->getDocument(),
82
                //"cpf" => "00000000000",
83
                "siglaUF" => $providerAddress->getStreet()->getDistrict()->getCity()->getState()->getUf(),
84
                "schemes" => "PL_CTe_300",
85
                "versao" => '3.00',
86
                "proxyConf" => [
87
                    "proxyIp" => "",
88
                    "proxyPort" => "",
89
                    "proxyUser" => "",
90
                    "proxyPass" => ""
91
                ]
92
            ];
93
            //monta o config.json
94
            $configJson = json_encode($arr);
95
96
97
            //intancia a classe tools
98
            $this->tools = new Tools($configJson, Certificate::readPfx($content, $dacteKeyPass->getConfigValue()));
99
100
            $this->tools->model('57');
101
102
            $cte = new MakeCTe();
103
104
            //$dhEmi = date("Y-m-d\TH:i:s-03:00"); Para obter a data com diferença de fuso usar 'P'
105
            $dhEmi = date("Y-m-d\TH:i:sP");
106
107
            $numeroCTE = $this->getLastDacte();
108
109
            // CUIDADO: Observe que mesmo os parâmetros fixados abaixo devem ser preenchidos conforme os dados do CT-e, estude a composição da CHAVE para saber o que vai em cada campo
110
            $chave = $this->montaChave(
111
                '43',
112
                date('y', strtotime($dhEmi)),
113
                date('m', strtotime($dhEmi)),
114
                $arr['cnpj'],
115
                $this->tools->model(),
116
                '1',
117
                $numeroCTE,
118
                '1',
119
                '10'
120
            );
121
122
            $infCte = new \stdClass();
123
            $infCte->Id = "";
124
            $infCte->versao = "3.00";
125
            $cte->taginfCTe($infCte);
126
127
            $cDV = substr($chave, -1);      //Digito Verificador
128
129
130
            /**
131
             * @todo
132
             */
133
            $ide = new \stdClass();
134
            $ide->cUF = '43'; // Codigo da UF da tabela do IBGE
135
            $ide->cCT = '99999999'; // Codigo numerico que compoe a chave de acesso
136
            $ide->CFOP = '6932'; // Codigo fiscal de operacoes e prestacoes
137
            $ide->natOp = 'PRESTACAO DE SERVICO DE TRANSPORTE A ESTABELECIMENTO FORA DO ESTADO DE ORIGEM'; // Natureza da operacao
138
139
            /**
140
             * @todo
141
             */
142
143
            //$ide->forPag = '';              // 0-Pago; 1-A pagar; 2-Outros
144
            $ide->mod = '57'; // Modelo do documento fiscal: 57 para identificação do CT-e
145
            $ide->serie = '1'; // Serie do CTe
146
            $ide->nCT = $numeroCTE; // Numero do CTe
147
            $ide->dhEmi = $dhEmi; // Data e hora de emissão do CT-e: Formato AAAA-MM-DDTHH:MM:DD
148
            $ide->tpImp = '1'; // Formato de impressao do DACTE: 1-Retrato; 2-Paisagem.
149
            $ide->tpEmis = '1'; // Forma de emissao do CTe: 1-Normal; 4-EPEC pela SVC; 5-Contingência
150
            $ide->cDV = $cDV; // Codigo verificador
151
            $ide->tpAmb = '2'; // 1- Producao; 2-homologacao
152
            $ide->tpCTe = '0'; // 0- CT-e Normal; 1 - CT-e de Complemento de Valores;
153
            // 2 -CT-e de Anulação; 3 - CT-e Substituto
154
            $ide->procEmi = '0'; // Descricao no comentario acima
155
            $ide->verProc = '3.0'; // versao do aplicativo emissor
156
            $ide->indGlobalizado = '';
157
            //$ide->refCTE = '';             // Chave de acesso do CT-e referenciado            
158
            $ide->xMunEnv = 'FOZ DO IGUACU'; // Informar PAIS/Municipio para as operações com o exterior.
159
            $ide->UFEnv = 'RS'; // Informar 'EX' para operações com o exterior.
160
            $ide->modal = '01'; // Preencher com:01-Rodoviário; 02-Aéreo; 03-Aquaviário;04-
161
            $ide->tpServ = '0'; // 0- Normal; 1- Subcontratação; 2- Redespacho;
162
            $ide->cMunEnv = $this->getCodMunicipio($ide->xMunEnv, $ide->UFEnv); // Código do município (utilizar a tabela do IBGE)
163
164
165
            /**
166
             * @todo
167
             */
168
            // 3- Redespacho Intermediário; 4- Serviço Vinculado a Multimodal            
169
            $ide->xMunIni = 'FOZ DO IGUACU'; // Informar 'EXTERIOR' para operações com o exterior.
170
            $ide->UFIni = 'RS'; // Informar 'EX' para operações com o exterior.
171
            $ide->cMunFim = '3523909'; // Utilizar a tabela do IBGE. Informar 9999999 para operações com o exterior.
172
            $ide->cMunFim = $this->getCodMunicipio($ide->xMunIni, $ide->UFIni); // Código do município (utilizar a tabela do IBGE)
173
174
175
            /**
176
             * @todo
177
             */
178
            $ide->xMunFim = 'ITU'; // Informar 'EXTERIOR' para operações com o exterior.
179
            $ide->UFFim = 'SP'; // Informar 'EX' para operações com o exterior.
180
            $ide->cMunIni = $this->getCodMunicipio($ide->xMunFim, $ide->UFFim); // Código do município (utilizar a tabela do IBGE)
181
182
            $ide->retira = '1'; // Indicador se o Recebedor retira no Aeroporto; Filial,
183
            // Porto ou Estação de Destino? 0-sim; 1-não
184
            $ide->xDetRetira = ''; // Detalhes do retira
185
            $ide->indIEToma = '1';
186
            $ide->dhCont = ''; // Data e Hora da entrada em contingência; no formato AAAAMM-DDTHH:MM:SS
187
            $ide->xJust = '';                 // Justificativa da entrada em contingência
188
189
            $cte->tagide($ide);
190
191
            // Indica o "papel" do tomador: 0-Remetente; 1-Expedidor; 2-Recebedor; 3-Destinatário
192
            $toma3 = new \stdClass();
193
            $toma3->toma = '3';
194
            $cte->tagtoma3($toma3);
195
            //
196
            //$toma4 = new stdClass();
197
            //$toma4->toma = '4'; // 4-Outros; informar os dados cadastrais do tomador quando ele for outros
198
            //$toma4->CNPJ = '11509962000197'; // CNPJ
199
            //$toma4->CPF = ''; // CPF
200
            //$toma4->IE = 'ISENTO'; // Iscricao estadual
201
            //$toma4->xNome = 'RAZAO SOCIAL'; // Razao social ou Nome
202
            //$toma4->xFant = 'NOME FANTASIA'; // Nome fantasia
203
            //$toma4->fone = '5532128202'; // Telefone
204
            //$toma4->email = '[email protected]';   // email
205
            //$cte->tagtoma4($toma4);
206
207
208
209
210
            /**
211
             * @todo
212
             */
213
            $enderToma = new \stdClass();
214
            $enderToma->xLgr = 'Avenida Independência'; // Logradouro
215
            $enderToma->nro = '482'; // Numero
216
            $enderToma->xCpl = ''; // COmplemento
217
            $enderToma->xBairro = 'Centro'; // Bairro
218
            $enderToma->cMun = '4308607'; // Codigo do municipio do IBEGE Informar 9999999 para operações com o exterior
219
            $enderToma->xMun = 'Garibaldi'; // Nome do município (Informar EXTERIOR para operações com o exterior.
220
            $enderToma->CEP = '95720000'; // CEP
221
            $enderToma->UF = $arr['siglaUF']; // Sigla UF (Informar EX para operações com o exterior.)
222
            $enderToma->cPais = '1058'; // Codigo do país ( Utilizar a tabela do BACEN )
223
            $enderToma->xPais = 'Brasil';                   // Nome do pais
224
            $cte->tagenderToma($enderToma);
225
226
227
            $emit = new \stdClass();
228
            $emit->CNPJ = $arr['cnpj']; // CNPJ do emitente
229
            //$emit->IE = '0100072968'; // Inscricao estadual
230
            //$emit->IEST = ""; // Inscricao estadual
231
            $emit->xNome = $provider->getName(); // Razao social
232
            $emit->xFant = $provider->getAlias(); // Nome fantasia
233
            $cte->tagemit($emit);
234
235
236
237
            $enderEmit = new \stdClass();
238
            $enderEmit->xLgr = $providerAddress->getStreet()->getStreet(); // Logradouro
239
            $enderEmit->nro = $providerAddress->getNumber(); // Numero
240
            $enderEmit->xCpl = $providerAddress->getComplement(); // Complemento
241
            $enderEmit->xBairro = $providerAddress->getStreet()->getDistrict()->getDistrict(); // Bairro
242
            $enderEmit->xMun = $providerAddress->getStreet()->getDistrict()->getCity()->getCity(); // Nome do municipio            
243
            $enderEmit->CEP = $providerAddress->getStreet()->getCep()->getCep(); // CEP
244
            $enderEmit->UF =  $providerAddress->getStreet()->getDistrict()->getCity()->getState()->getUf(); // Sigla UF
245
            $enderEmit->cMun = $this->getCodMunicipio($enderEmit->xMun, $enderEmit->UF); // Código do município (utilizar a tabela do IBGE)
246
            $enderEmit->fone = $provider->getPhone()[0]->getDdd() . $provider->getPhone()[0]->getPhone(); // Fone
247
            $cte->tagenderEmit($enderEmit);
248
249
250
            $retrieve = $data->getRetrievePeople();
251
            $retrieveDocument = $retrieve->getOneDocument();
252
253
            $rem = new \stdClass();
254
            $rem->CNPJ = $retrieveDocument->getDocument(); // CNPJ
255
            $rem->CPF = ''; // CPF
256
            //$rem->IE = '9057800426'; // Inscricao estadual
257
            $rem->xNome = $retrieve->getName();
258
            $rem->xFant = $retrieve->getAlias(); // Nome fantasia
259
            $rem->fone = ''; // Fone
260
            $rem->email = ''; // Email
261
            $cte->tagrem($rem);
262
263
264
            /**
265
             * @var \ControleOnline\Entity\Address $providerAddress
266
             */
267
            $retrieveAddress = $data->getAddressDestination();
268
269
            $enderReme = new \stdClass();
270
            $enderReme->xLgr = $retrieveAddress->getStreet()->getStreet(); // Logradouro
271
            $enderReme->nro = $retrieveAddress->getNumber(); // Numero
272
            $enderReme->xCpl = $retrieveAddress->getComplement(); // Complemento
273
            $enderReme->xBairro = $retrieveAddress->getStreet()->getDistrict()->getDistrict(); // Bairro
274
            $enderReme->xMun = $retrieveAddress->getStreet()->getDistrict()->getCity()->getCity(); // Nome do municipio (Informar EXTERIOR para operações com o exterior.)
275
            $enderReme->CEP = $retrieveAddress->getStreet()->getCep()->getCep(); // CEP
276
            $enderReme->UF = $retrieveAddress->getStreet()->getDistrict()->getCity()->getState()->getUf(); // Sigla UF (Informar EX para operações com o exterior.)
277
            $enderReme->cPais = '1058'; // Codigo do pais ( Utilizar a tabela do BACEN )             
278
            $enderReme->cMun = $this->getCodMunicipio($enderReme->xMun, $enderReme->UF); // Codigo Municipal (Informar 9999999 para operações com o exterior.)
279
            $enderReme->xPais = $retrieveAddress->getStreet()->getDistrict()->getCity()->getState()->getCountry()->getCountryname(); // Nome do pais
280
            $cte->tagenderReme($enderReme);
281
282
283
284
285
            $delivery = $data->getDeliveryPeople();
286
            $deliveryDocument = $delivery->getOneDocument();
287
288
            $dest = new \stdClass();
289
            $dest->CNPJ = $deliveryDocument->getDocument(); // CNPJ
290
            $dest->CPF = ''; // CPF
291
            //$rem->IE = '9057800426'; // Inscricao estadual
292
            $dest->xNome = $delivery->getName();
293
            $dest->xFant = $delivery->getAlias(); // Nome fantasia
294
            $dest->fone = ''; // Fone
295
            $dest->email = ''; // Email
296
            $dest->ISUF = ''; // Inscrição na SUFRAMA
297
            $cte->tagdest($dest);
298
299
300
            /**
301
             * @var \ControleOnline\Entity\Address $providerAddress
302
             */
303
            $destinationAddress = $data->getAddressDestination();
304
305
306
            $enderDest = new \stdClass();
307
            $enderDest->xLgr = $destinationAddress->getStreet()->getStreet(); // Logradouro
308
            $enderDest->nro = $destinationAddress->getNumber(); // Numero
309
            $enderDest->xCpl = $destinationAddress->getComplement(); // Complemento
310
            $enderDest->xBairro = $destinationAddress->getStreet()->getDistrict()->getDistrict(); // Bairro                        
311
            $enderDest->xMun = $destinationAddress->getStreet()->getDistrict()->getCity()->getCity(); // Nome do municipio (Informar EXTERIOR para operações com o exterior.)
312
            $enderDest->CEP = $destinationAddress->getStreet()->getCep()->getCep(); // CEP
313
            $enderDest->UF = $destinationAddress->getStreet()->getDistrict()->getCity()->getState()->getUf(); // Sigla UF (Informar EX para operações com o exterior.)
314
            $enderDest->cPais = '1058'; // Codigo do pais ( Utilizar a tabela do BACEN ) 
315
            $enderDest->xPais = $destinationAddress->getStreet()->getDistrict()->getCity()->getState()->getCountry()->getCountryname(); // Nome do pais
316
            $enderDest->cMun = $this->getCodMunicipio($enderDest->xMun, $enderDest->UF); // Código do município (utilizar a tabela do IBGE)
317
            $cte->tagenderDest($enderDest);
318
319
320
            $vPrest = new \stdClass();
321
            $vPrest->vTPrest = $data->getPrice(); // Valor total da prestacao do servico
322
            $vPrest->vRec = $data->getPrice();      // Valor a receber
323
            $cte->tagvPrest($vPrest);
324
325
326
            $comp = new \stdClass();
327
            $comp->xNome = 'FRETE VALOR'; // Nome do componente
328
            $comp->vComp = '3334.32';  // Valor do componente
329
            $cte->tagComp($comp);
330
331
            $icms = new \stdClass();
332
            $icms->cst = '00'; // 00 - Tributacao normal ICMS
333
            $icms->pRedBC = ''; // Percentual de redução da BC (3 inteiros e 2 decimais)
334
            $icms->vBC = 3334.32; // Valor da BC do ICMS
335
            $icms->pICMS = 12; // Alícota do ICMS
336
            $icms->vICMS = 400.12; // Valor do ICMS
337
            $icms->vBCSTRet = ''; // Valor da BC do ICMS ST retido
338
            $icms->vICMSSTRet = ''; // Valor do ICMS ST retido
339
            $icms->pICMSSTRet = ''; // Alíquota do ICMS
340
            $icms->vCred = ''; // Valor do Crédito Outorgado/Presumido
341
            $icms->vTotTrib = 754.38; // Valor de tributos federais; estaduais e municipais
342
            $icms->outraUF = false;    // ICMS devido à UF de origem da prestação; quando diferente da UF do emitente
343
            $icms->vICMSUFIni = 0;
344
            $icms->vICMSUFFim = 0;
345
            $icms->infAdFisco = 'Informações ao fisco';
346
            $cte->tagicms($icms);
347
348
349
            $cte->taginfCTeNorm();              // Grupo de informações do CT-e Normal e Substituto
350
351
352
            $infCarga = new \stdClass();
353
            $infCarga->vCarga = 130333.31; // Valor total da carga
354
            $infCarga->proPred = 'TUBOS PLASTICOS'; // Produto predominante
355
            $infCarga->xOutCat = 6.00; // Outras caracteristicas da carga
356
            $infCarga->vCargaAverb = 1.99;
357
            $cte->taginfCarga($infCarga);
358
359
            $infQ = new \stdClass();
360
            $infQ->cUnid = '01'; // Código da Unidade de Medida: ( 00-M3; 01-KG; 02-TON; 03-UNIDADE; 04-LITROS; 05-MMBTU
361
            $infQ->tpMed = 'ESTRADO'; // Tipo de Medida
362
            // ( PESO BRUTO; PESO DECLARADO; PESO CUBADO; PESO AFORADO; PESO AFERIDO; LITRAGEM; CAIXAS e etc)
363
            $infQ->qCarga = 18145.0000;  // Quantidade (15 posições; sendo 11 inteiras e 4 decimais.)
364
            $cte->taginfQ($infQ);
365
            $infQ->cUnid = '02'; // Código da Unidade de Medida: ( 00-M3; 01-KG; 02-TON; 03-UNIDADE; 04-LITROS; 05-MMBTU
366
            $infQ->tpMed = 'OUTROS'; // Tipo de Medida
367
            // ( PESO BRUTO; PESO DECLARADO; PESO CUBADO; PESO AFORADO; PESO AFERIDO; LITRAGEM; CAIXAS e etc)
368
            $infQ->qCarga = 31145.0000;  // Quantidade (15 posições; sendo 11 inteiras e 4 decimais.)
369
            $cte->taginfQ($infQ);
370
371
            $infNFe = new \stdClass();
372
            $infNFe->chave = '43160472202112000136550000000010571048440722'; // Chave de acesso da NF-e
373
            $infNFe->PIN = ''; // PIN SUFRAMA
374
            $infNFe->dPrev = '2016-10-30';                                       // Data prevista de entrega
375
            $cte->taginfNFe($infNFe);
376
377
            $infModal = new \stdClass();
378
            $infModal->versaoModal = '3.00';
379
            $cte->taginfModal($infModal);
380
381
            $rodo = new \stdClass();
382
            $rodo->RNTRC = '00739357';
383
            $cte->tagrodo($rodo);
384
385
            $aereo = new \stdClass();
386
            $aereo->nMinu = '123'; // Número Minuta
387
            $aereo->nOCA = ''; // Número Operacional do Conhecimento Aéreo
388
            $aereo->dPrevAereo = date('Y-m-d');
389
            $aereo->natCarga_xDime = ''; // Dimensões 1234x1234x1234 em cm
390
            $aereo->natCarga_cInfManu = []; // Informação de manuseio, com dois dígitos, pode ter mais de uma ocorrência.
391
            $aereo->tarifa_CL = 'G'; // M - Tarifa Mínima / G - Tarifa Geral / E - Tarifa Específica
392
            $aereo->tarifa_cTar = ''; // código da tarifa, deverão ser incluídos os códigos de três digítos correspondentes à tarifa
393
            $aereo->tarifa_vTar = 100.00; // valor da tarifa. 15 posições, sendo 13 inteiras e 2 decimais. Valor da tarifa por kg quando for o caso
394
            $cte->tagaereo($aereo);
395
396
            $autXML = new \stdClass();
397
            $autXML->CPF = '59195248471'; // CPF ou CNPJ dos autorizados para download do XML
398
            $cte->tagautXML($autXML);
399
400
            //Monta CT-e
401
            $cte->montaCTe();
402
            $chave = $cte->chCTe;
0 ignored issues
show
Unused Code introduced by
The assignment to $chave is dead and can be removed.
Loading history...
403
404
            $xml = $cte->getXML();
405
            $xml = $this->sign($xml);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $xml is correct as $this->sign($xml) targeting ControleOnline\Controlle...eateDacteAction::sign() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
406
407
            $invoiceTax = new SalesInvoiceTax();
408
            $invoiceTax->setInvoice($xml);
409
            $invoiceTax->setInvoiceNumber($numeroCTE);
410
            $this->manager->persist($invoiceTax);
411
            $this->manager->flush();
412
413
414
            $orderInvoiceTax = new SalesOrderInvoiceTax();
415
            $orderInvoiceTax->setOrder($data);
416
            $orderInvoiceTax->setInvoiceType(57);
417
            $orderInvoiceTax->setInvoiceTax($invoiceTax);
418
            $orderInvoiceTax->setIssuer($provider);
419
420
            $this->manager->persist($orderInvoiceTax);
421
            $this->manager->flush();
422
423
            return new JsonResponse([
424
                'response' => [
425
                    'data'    => $data->getId(),
426
                    'invoice_tax' => $invoiceTax->getId(),
427
                    'xml' => $xml,
428
                    'count'   => 1,
429
                    'error'   => '',
430
                    'success' => true,
431
                ],
432
            ]);
433
        } catch (\Throwable $th) {
434
            return new JsonResponse([
435
                'response' => [
436
                    'count'   => 0,
437
                    'error'   => $th->getMessage(),
438
                    'success' => false,
439
                ],
440
            ]);
441
        }
442
    }
443
    protected function getCodMunicipio($mun, $uf)
444
    {
445
446
        /**
447
         * @todo
448
         */
449
        $cod['sp'] = [
0 ignored issues
show
Comprehensibility Best Practice introduced by
$cod was never initialized. Although not strictly required by PHP, it is generally a good practice to add $cod = array(); before regardless.
Loading history...
450
            'Guarulhos' => '4108304',
451
            'São Paulo' => '4108304'
452
        ];
453
454
        return $cod[$uf][$mun];
455
    }
456
    protected function getLastDacte()
457
    {
458
        return '127'; //@todo
459
    }
460
461
    protected function montaChave($cUF, $ano, $mes, $cnpj, $mod, $serie, $numero, $tpEmis, $codigo = '')
462
    {
463
        if ($codigo == '') {
464
            $codigo = $numero;
465
        }
466
        $forma = "%02d%02d%02d%s%02d%03d%09d%01d%08d";
467
        $chave = sprintf(
468
            $forma,
469
            $cUF,
470
            $ano,
471
            $mes,
472
            $cnpj,
473
            $mod,
474
            $serie,
475
            $numero,
476
            $tpEmis,
477
            $codigo
478
        );
479
        return $chave . $this->calculaDV($chave);
480
    }
481
482
    protected function sign($xml)
483
    {
484
        //Assina
485
        $xml = $this->tools->signCTe($xml);
0 ignored issues
show
Unused Code introduced by
The assignment to $xml is dead and can be removed.
Loading history...
486
    }
487
    protected function sendData($xml)
488
    {
489
490
        //Envia lote e autoriza
491
        $axmls[] = $xml;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$axmls was never initialized. Although not strictly required by PHP, it is generally a good practice to add $axmls = array(); before regardless.
Loading history...
492
        $lote = substr(str_replace(',', '', number_format(microtime(true) * 1000000, 0)), 0, 15);
493
        $res = $this->tools->sefazEnviaLote($axmls, $lote);
494
495
        //Converte resposta
496
        $stdCl = new Standardize($res);
497
        //Output array
498
        $arr = $stdCl->toArray();
499
        //print_r($arr);
500
        //Output object
501
        $std = $stdCl->toStd();
502
503
        if ($std->cStat != 103) { //103 - Lote recebido com Sucesso
504
            //processa erros
505
            print_r($arr);
506
        }
507
508
        //Consulta Recibo
509
        $res = $this->tools->sefazConsultaRecibo($std->infRec->nRec);
510
        $stdCl = new Standardize($res);
511
        $arr = $stdCl->toArray();
512
        $std = $stdCl->toStd();
513
        if ($std->protCTe->infProt->cStat == 100) { //Autorizado o uso do CT-e
514
            //adicionar protocolo
515
        }
516
        echo '<pre>';
517
        print_r($arr);
518
    }
519
520
    protected function calculaDV($chave43)
521
    {
522
        $multiplicadores = array(2, 3, 4, 5, 6, 7, 8, 9);
523
        $iCount = 42;
524
        $somaPonderada = 0;
525
        while ($iCount >= 0) {
526
            for ($mCount = 0; $mCount < count($multiplicadores) && $iCount >= 0; $mCount++) {
527
                $num = (int) substr($chave43, $iCount, 1);
528
                $peso = (int) $multiplicadores[$mCount];
529
                $somaPonderada += $num * $peso;
530
                $iCount--;
531
            }
532
        }
533
        $resto = $somaPonderada % 11;
534
        if ($resto == '0' || $resto == '1') {
535
            $cDV = 0;
536
        } else {
537
            $cDV = 11 - $resto;
538
        }
539
        return (string) $cDV;
540
    }
541
}
542