Completed
Push — master ( 36dc74...cba49e )
by Reginaldo
33:17
created

ProdutoController   B

Complexity

Total Complexity 53

Size/Duplication

Total Lines 447
Duplicated Lines 10.74 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 48
loc 447
rs 7.4757
wmc 53
lcom 1
cbo 12

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ProdutoController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ProdutoController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
ini_set('max_execution_time', 300);
4
5
class ProdutoController extends AppController{		
6
7
	public function listar_cadastros() {
8
		$this->layout = 'wadmin';
9
10
		$this->set('produtos', $this->Produto->find('all', 
11
				array('conditions' => 
12
					array('ativo' => 1,
13
						  'id_usuario' => $this->instancia
14
					)
15
				)
16
			)
17
		);
18
	}
19
20
	public function adicionar_cadastro() {
21
		$this->loadModel('Categoria');
22
23
		$this->set('categorias', $this->Categoria->find('all', 
24
				array('conditions' => 
25
					array('ativo' => 1,
26
						  'usuario_id' => $this->instancia
27
					)
28
				)
29
			)
30
		);	
31
32
		$this->layout = 'wadmin';
33
	}
34
35
	public function s_adicionar_cadastro() {
36
		$dados  = $this->request->data('dados');
37
38
		$variacoes = $this->request->data('variacao');
39
40
		$image  = $_FILES['imagem'];
41
42
		$retorno = $this->uploadImage($image);
43
44
		if (!$retorno['status']) 
45
			$this->Session->setFlash('Não foi possivel salvar a imagem tente novamente');
46
47
		$dados['imagem'] = $retorno['nome'];
48
		$dados['id_usuario'] = $this->instancia;
49
		$dados['ativo'] = 1;
50
		$dados['id_alias'] = $this->id_alias();
51
52
		if($this->Produto->save($dados)) {
53
			$produto_id = $this->Produto->getLastInsertId();
54
			
55
			require 'VariacaoController.php';
56
57
			$objVariacaoController = new VariacaoController();
58
59
			$objVariacaoController->s_adicionar_variacao($variacoes, $produto_id, $this->instancia);			
60
61
			$this->Session->setFlash('Produto salvo com sucesso!');
62
            
63
            return $this->redirect('/produto/listar_cadastros');
64
		} else {
65
			$this->Session->setFlash('Ocorreu um erro ao salva o produto!');
66
            
67
            return $this->redirect('/produto/listar_cadastros');
68
		}
69
	}
70
71
	public function editar_cadastro($id) {
72
		$this->layout = 'wadmin';
73
74
		$this->loadModel('Variacao');
75
76
		$query = array (
77
			'joins' => array(
78
				    array(
79
				        'table' => 'produtos',
80
				        'alias' => 'Produto',
81
				        'type' => 'LEFT',
82
				        'conditions' => array(
83
				            'Variacao.produto_id = Produto.id',
84
				        ),
85
				    )
86
				),
87
	        'conditions' => array('Variacao.produto_id' => $id, 'Variacao.ativo' => 1),
88
	        'fields' => array('Produto.id, Variacao.*'),
89
		);
90
91
		$variacoes = $this->set('variacoes', $this->Variacao->find('all', $query));
92
93
		$this->set('produto', $this->Produto->find('all', 
94
				array('conditions' => 
95
					array('ativo' => 1,
96
						  'id' => $id
97
					)
98
				)
99
			)[0]
100
		);
101
102
		$this->loadModel('Categoria');
103
104
		$this->set('categorias', $this->Categoria->find('all', 
105
				array('conditions' => 
106
					array('ativo' => 1,
107
						  'usuario_id' => $this->instancia
108
					)
109
				)
110
			)
111
		);	
112
	}
113
114
	public function s_editar_cadastro($id) {
115
		$dados = $this->request->data('dados');
116
117
		$variacoes = $this->request->data('variacao');
118
119
		$image  = $_FILES['imagem'];
120
		
121
		if (!empty($image['name'])) {
122
			$retorno = $this->uploadImage($image);
123
			
124
			if (!$retorno['status']) 
125
				$this->Session->setFlash('Não foi possivel salvar a imagem tente novamente');
126
			
127
			$dados['imagem'] = $retorno['nome'];
128
		}
129
130
131
		$dados['id_usuario'] = $this->instancia;
132
		$dados['ativo'] = 1;
133
		$dados['id_alias'] = $this->id_alias();
134
135
		$this->Produto->id = $id;
136
		
137
		if ($this->Produto->save($dados)) {
138
139
			require 'VariacaoController.php';
140
			$objVariacaoController = new VariacaoController();
141
			$objVariacaoController->desativar_variacoes($id);
142
			$objVariacaoController->s_adicionar_variacao($variacoes, $id, $this->instancia);	
143
144
			$this->Session->setFlash('Produto editado com sucesso!','default','good');
145
            return $this->redirect('/produto/listar_cadastros');
146
		} else {
147
			$this->Session->setFlash('Ocorreu um erro ao editar o produto!','default','good');
148
            return $this->redirect('/produto/listar_cadastros');
149
		}
150
	}
151
152
	public function excluir_cadastro() {
153
		$this->layout = 'ajax';
154
155
		$id = $this->request->data('id');
156
157
		$dados = array('ativo' => '0');
158
		$parametros = array('id' => $id);
159
160
		if ($this->Produto->updateAll($dados, $parametros)) {
161
			echo json_encode(true);
162
		} else {
163
			echo json_encode(false);
164
		}
165
	}
166
167
	public function id_alias() {
168
		$id_alias = $this->Produto->find('first', array(
169
				'conditions' => array('Produto.ativo' => 1),
170
				'order' => array('Produto.id' => 'desc')
171
			)
172
		);
173
174
		return $id_alias['Produto']['id_alias'] + 1;
175
	}
176
177
	public function carregar_dados_venda_ajax() {
178
		$this->layout = 'ajax';
179
180
		$retorno = $this->Produto->find('first', 
181
			array('conditions' => 
182
				array('Produto.ativo' => 1,
183
					  'Produto.id_usuario' => $this->instancia,
184
					  'Produto.id' => $this->request->data('id')
185
				)
186
			)
187
		);
188
189
		if (!$this->validar_estoque($retorno)) {
190
			return false;
191
		}
192
193
		$retorno['Produto']['total'] = $this->calcular_preco_produto_venda($retorno['Produto']['preco'], $this->request->data('qnt'));
194
195
		$retorno['Produto']['preco'] = number_format($retorno['Produto']['preco'], 2, ',', '.');
196
		
197
		echo json_encode($retorno);
198
	}
199
200
	public function validar_estoque($produto) {
201
		if (empty($produto) && !isset($produto)) {
202
			return false;
203
		}
204
		
205
		if ($produto['Produto']['estoque'] <= 0) {
206
			return false;
207
		}
208
209
		return true;
210
	}
211
212
	public function calcular_preco_produto_venda($preco, $qnt) {
213
		if (empty($preco) || !isset($preco)) {
214
			return false;
215
		}
216
217
		if (!is_numeric($qnt)) {
218
			return false;
219
		}
220
221
		$retorno = $preco * $qnt;
222
223
		return number_format($retorno, 2, ',', '.');
224
	}
225
226
	public function uploadImage(&$image) {
227
		$type = substr($image['name'], -4);
228
		$nameImage = uniqid() . md5($image['name']) . $type;
229
		$dir = APP . 'webroot/uploads/produto/imagens/';
230
		
231
		$returnUpload = move_uploaded_file($image['tmp_name'], $dir . $nameImage);
232
233
		if (!$returnUpload)
234
			return array('nome' => null, 'status' => false);
235
236
		return array('nome' => $nameImage, 'status' => true);
237
	}
238
239
	public function visualizar_cadastro($id) {
240
		$this->layout = 'wadmin';
241
242
		$produto = $this->Produto->find('all', 
243
			array('conditions' => 
244
				array('ativo' => 1,
245
					  'id' => $id
246
				)
247
			)
248
		);
249
250
		if (empty($produto)) {
251
			$this->Session->setFlash("Produto não encotrado, tente novamente");
252
			$this->redirect("/produto/listar_cadastros");
253
		}
254
255
		$this->set('produto', $produto[0]);
256
	}
257
258
	public function exportar_excel_exemplo() {
259
		include(APP . 'Vendor/PHPExcel/PHPExcel.php');
260
		include(APP . 'Vendor/PHPExcel/PHPExcel/IOFactory.php');
261
262
        $objPHPExcel = new PHPExcel();
263
        // Definimos o estilo da fonte
264
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
265
266
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
267
268
        // Criamos as colunas
269
        $objPHPExcel->setActiveSheetIndex(0)
270
                    ->setCellValue('A1', "Nome do Produto")
271
                    ->setCellValue('B1', "Preço ")
272
                    ->setCellValue("C1", "Peso Bruto")
273
                    ->setCellValue("D1", "Peso Liquido")
274
                    ->setCellValue("E1", "Estoque")
275
                    ->setCellValue("F1", "Descrição");
276
277
        // Podemos renomear o nome das planilha atual, lembrando que um único arquivo pode ter várias planilhas
278
        $objPHPExcel->getActiveSheet()->setTitle('Listagem de produtos');
279
280
        // Cabeçalho do arquivo para ele baixar
281
        header('Content-Type: application/vnd.ms-excel');
282
        header('Content-Disposition: attachment;filename="planilha_importacao_exemplo.xls"');
283
        header('Cache-Control: max-age=0');
284
        // Se for o IE9, isso talvez seja necessário
285
        header('Cache-Control: max-age=1');
286
287
        // Acessamos o 'Writer' para poder salvar o arquivo
288
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
289
290
        // Salva diretamente no output, poderíamos mudar arqui para um nome de arquivo em um diretório ,caso não quisessemos jogar na tela
291
        $objWriter->save('php://output'); 
292
293
        exit;
294
    }
295
296
    public function importar_produtos_planilha() {
297
        if (!isset($_FILES['arquivo']['tmp_name']) && empty($_FILES['arquivo']['tmp_name']))
298
        {
299
			$this->Session->setFlash("Erro ao subir a planilha, tente novamente.");
300
			$this->redirect("/produto/listar_cadastros");        	
301
        }
302
303
        $typesPermissions = ['application/vnd.ms-excel'];
304
305
        if (!in_array($_FILES['arquivo']['type'], $typesPermissions))
306
        {
307
			$this->Session->setFlash("O arquivo deve ser no formato .xls.");
308
			$this->redirect("/produto/listar_cadastros");                	
309
        }
310
311
        $caminho = APP . 'webroot/uploads/produto/planilhas/' . uniqid() . '.xls';
312
313
        $inputFileName = $_FILES['arquivo']['tmp_name'];
314
315
        move_uploaded_file($inputFileName, $caminho);
316
317
        $data = [
318
        	'caminho' => $caminho,
319
        	'usuario_id' => $this->instancia,
320
        	'processado' => 0,
321
        	'ativo' => 1
322
        ];
323
324
        $this->loadModel('QueueProduct');
325
326
        if ($this->QueueProduct->save($data))
327
        {
328
			$this->Session->setFlash("O arquivo está na fila para ser importado, iremos enviar um e-mail quando terminar.");
329
			$this->redirect("/produto/listar_cadastros");  
330
        }
331
        else 
332
        {
333
			$this->Session->setFlash("Ocorreu um erro, tente novamente.");
334
			$this->redirect("/produto/listar_cadastros");          	
335
        }
336
    }
337
338
    public function importar_produtos_planilha() {
339
		include(APP . 'Vendor/PHPExcel/PHPExcel.php');
340
		include(APP . 'Vendor/PHPExcel/PHPExcel/IOFactory.php');
341
    	
342
        $objPHPExcel = new PHPExcel();
343
344
        if (!isset($_FILES['arquivo']['tmp_name']) && empty($_FILES['arquivo']['tmp_name']))
345
        {
346
			$this->Session->setFlash("Erro ao subir a planilha, tente novamente.");
347
			$this->redirect("/produto/listar_cadastros");        	
348
        }
349
350
        $typesPermissions = ['application/vnd.ms-excel'];
351
352
        if (!in_array($_FILES['arquivo']['type'], $typesPermissions))
353
        {
354
			$this->Session->setFlash("O arquivo deve ser no formato .xls.");
355
			$this->redirect("/produto/listar_cadastros");                	
356
        }
357
358
        $caminho = APP . 'webroot/uploads/produto/planilhas/' . uniqid() . '.xls';
359
360
        $inputFileName = $_FILES['arquivo']['tmp_name'];
361
362
        move_uploaded_file($inputFileName, $caminho);
363
364
        $data = [
365
        	'caminho' => $caminho,
366
        	'usuario_id' => $this->instancia,
367
        	'processado' => 0,
368
        	'ativo' => 1
369
        ];
370
371
        if ($this->QueueProducts->save($data))
372
        {
373
			$this->Session->setFlash("O arquivo está na fila para ser importado, iremos enviar um e-mail quando terminar.");
374
			$this->redirect("/produto/listar_cadastros");  
375
        }
376
        else 
377
        {
378
			$this->Session->setFlash("Ocorreu um erro, tente novamente.");
379
			$this->redirect("/produto/listar_cadastros");          	
380
        }
381
    }
382
383
    public function processar_planilhas_na_fila() {
384
    	$this->loadModel('QueueProduct');
385
386
    	$planilhas = $this->QueueProduct->loadPlanilhasNotProcesseds();
387
388
    	$response = [];
389
    	foreach ($planilhas as $planilha) {
390
    		$response[] = $this->processar_planilhas($planilha['caminho'], $planilha['usuario_id'], $planilha['id']);
391
    	}
392
393
    	return $response;
394
    }
395
396
    public function processar_planilhas($inputFileName, $usuarioId, $planilhaId) {
397
		include(APP . 'Vendor/PHPExcel/PHPExcel.php');
398
		include(APP . 'Vendor/PHPExcel/PHPExcel/IOFactory.php');
399
    	
400
        $objPHPExcel = new PHPExcel();
401
402
		try {
403
		    $inputFileType 	= PHPExcel_IOFactory::identify($inputFileName);
404
		    $objReader 		= PHPExcel_IOFactory::createReader($inputFileType);
405
		    $objPHPExcel 	= $objReader->load($inputFileName);
406
		} catch(Exception $e) {
407
		    die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
408
		}
409
410
		$dados = [];
411
412
		$rows = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
413
414
		for ($row = 2; $row <= $rows; $row++) {
415
			
416
			$rowInterator = $objPHPExcel->getActiveSheet()->getRowIterator($row)->current();
417
418
			$cellIterator = $rowInterator->getCellIterator();
419
			$cellIterator->setIterateOnlyExistingCells(false);
420
421
			foreach ($cellIterator as $i => $cell) {
422
				switch ($i) {
423
					case 0: //Codigo/SKU
424
						$dados[$row]['sku'] = $cell->getValue();
425
					break; 
426
					case 1: // Nome/Descrição 
427
						$dados[$row]['nome'] = $cell->getValue();						
428
					break;
429
					case 2: // QtdAtual
430
						//$dados[$row]['sku'] = $cell->getValue();						
431
					break;
432
					case 3: // QtdMinima  
433
						$dados[$row]['quantidade_minima'] = $cell->getValue();						
434
					break;
435
					case 4: // QtdTotal
436
						$dados[$row]['estoque'] = $cell->getValue();						
437
					break;
438
					case 5: // ValCusto
439
						$dados[$row]['custo'] = $cell->getValue();						
440
					break;
441
					case 6:  // ValVenda
442
						$dados[$row]['preco'] = $cell->getValue();						
443
					break;
444
				}
445
			}
446
447
			$dados[$row]['id_usuario'] = $usuarioId;	
448
			$dados[$row]['ativo'] = 1;
449
450
		}
451
452
		$errors = $this->processar_lista_produtos($dados);
453
454
		if (isset($errors) && !empty($errors))
455
		{
456
			$this->QueueProduct->planilhaProcessedIncomplete($planilhaId);
457
		}
458
459
		$this->QueueProduct->planilhaProcessedComplete($planilhaId);
460
461
		echo json_encode(array('sucess' => true));
462
		exit;
463
    }
464
465
    public function processar_lista_produtos($dados) {
466
    	$errors = [];
467
468
    	foreach ($dados as $dado) {
469
    		$this->loadModel('Produto');
470
    		
471
    		$existProduto = $this->Produto->find('all',
472
    			array(
473
    				'conditions' => array(
474
    					'Produto.sku' => $dado['sku'],
475
    					'Produto.ativo' => 1
476
    				)
477
    			)
478
    		);
479
480
    		if (isset($existProduto) && !empty($existProduto))
481
    		{
482
    			$this->Produto->id = $existProduto[0]['Produto']['id'];
483
    			$this->Produto->save($dado);
484
    			continue;
485
    		}
486
487
			$this->Produto->create();
488
489
    		if (!$this->Produto->save($dado))
490
    		{
491
    			$errors[] = $dado;
492
    		}
493
    	}
494
495
    	return $errors;
496
>>>>>>> 36dc74c7f7a4a9679dceb6b9594a56aa51a0ed1a
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_SR
Loading history...
497
    }
498
499
}
500