Completed
Push — master ( c55a69...d34eef )
by Reginaldo
32:38
created

ProdutoController::validar_estoque()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 6
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 11
rs 9.2
1
<?php
2
3
class ProdutoController extends AppController{		
4
5
	public function listar_cadastros() {
6
		$this->layout = 'wadmin';
7
8
		$this->set('produtos', $this->Produto->find('all', 
9
				array('conditions' => 
10
					array('ativo' => 1,
11
						  'id_usuario' => $this->instancia
12
					)
13
				)
14
			)
15
		);
16
	}
17
18 View Code Duplication
	public function adicionar_cadastro() {
19
		$this->loadModel('Categoria');
20
21
		$this->set('categorias', $this->Categoria->find('all', 
22
				array('conditions' => 
23
					array('ativo' => 1,
24
						  'usuario_id' => $this->instancia
25
					)
26
				)
27
			)
28
		);	
29
30
		$this->layout = 'wadmin';
31
	}
32
33
	public function s_adicionar_cadastro() {
0 ignored issues
show
Coding Style introduced by
s_adicionar_cadastro uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
34
		$dados  = $this->request->data('dados');
35
36
		$variacoes = $this->request->data('variacao');
37
38
		$image  = $_FILES['imagem'];
39
40
		$retorno = $this->uploadImage($image);
41
42
		if (!$retorno['status']) 
43
			$this->Session->setFlash('Não foi possivel salvar a imagem tente novamente');
44
45
		$dados['imagem'] = $retorno['nome'];
46
		$dados['id_usuario'] = $this->instancia;
47
		$dados['ativo'] = 1;
48
		$dados['id_alias'] = $this->id_alias();
49
50
		if($this->Produto->save($dados)) {
51
			$produto_id = $this->Produto->getLastInsertId();
52
			require 'VariacaoController.php';
53
			$objVariacaoController = new VariacaoController();
54
55
			$objVariacaoController->s_adicionar_variacao($variacoes, $produto_id, $this->instancia);			
56
57
			$this->Session->setFlash('Produto salvo com sucesso!');
58
            return $this->redirect('/produto/listar_cadastros');
59
		} else {
60
			$this->Session->setFlash('Ocorreu um erro ao salva o produto!');
61
            return $this->redirect('/produto/listar_cadastros');
62
		}
63
	}
64
65
	public function editar_cadastro($id) {
66
		$this->layout = 'wadmin';
67
68
		$this->loadModel('Variacao');
69
70
		$query = array (
71
			'joins' => array(
72
				    array(
73
				        'table' => 'produtos',
74
				        'alias' => 'Produto',
75
				        'type' => 'LEFT',
76
				        'conditions' => array(
77
				            'Variacao.produto_id = Produto.id',
78
				        ),
79
				    )
80
				),
81
	        'conditions' => array('Variacao.produto_id' => $id, 'Variacao.ativo' => 1),
82
	        'fields' => array('Produto.id, Variacao.*'),
83
		);
84
85
		$variacoes = $this->set('variacoes', $this->Variacao->find('all', $query));
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $variacoes is correct as $this->set('variacoes', ...o->find('all', $query)) (which targets Controller::set()) 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...
86
87
		$this->set('produto', $this->Produto->find('all', 
88
				array('conditions' => 
89
					array('ativo' => 1,
90
						  'id' => $id
91
					)
92
				)
93
			)[0]
94
		);
95
96
		$this->loadModel('Categoria');
97
98
		$this->set('categorias', $this->Categoria->find('all', 
99
				array('conditions' => 
100
					array('ativo' => 1,
101
						  'usuario_id' => $this->instancia
102
					)
103
				)
104
			)
105
		);	
106
	}
107
108
	public function s_editar_cadastro($id) {
0 ignored issues
show
Coding Style introduced by
s_editar_cadastro uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
109
		$dados = $this->request->data('dados');
110
111
		$variacoes = $this->request->data('variacao');
112
113
		$image  = $_FILES['imagem'];
114
		
115 View Code Duplication
		if (!empty($image['name'])) {
116
			$retorno = $this->uploadImage($image);
117
			
118
			if (!$retorno['status']) 
119
				$this->Session->setFlash('Não foi possivel salvar a imagem tente novamente');
120
			
121
			$dados['imagem'] = $retorno['nome'];
122
		}
123
124
125
		$dados['id_usuario'] = $this->instancia;
126
		$dados['ativo'] = 1;
127
		$dados['id_alias'] = $this->id_alias();
128
129
		$this->Produto->id = $id;
130
		
131
		if ($this->Produto->save($dados)) {
132
133
			require 'VariacaoController.php';
134
			$objVariacaoController = new VariacaoController();
135
			$objVariacaoController->desativar_variacoes($id);
136
			$objVariacaoController->s_adicionar_variacao($variacoes, $id, $this->instancia);	
137
138
			$this->Session->setFlash('Produto editado com sucesso!','default','good');
139
            return $this->redirect('/produto/listar_cadastros');
140
		} else {
141
			$this->Session->setFlash('Ocorreu um erro ao editar o produto!','default','good');
142
            return $this->redirect('/produto/listar_cadastros');
143
		}
144
	}
145
146 View Code Duplication
	public function excluir_cadastro() {
147
		$this->layout = 'ajax';
148
149
		$id = $this->request->data('id');
150
151
		$dados = array ('ativo' => '0');
152
		$parametros = array ('id' => $id);
153
154
		if ($this->Produto->updateAll($dados,$parametros)) {
155
			echo json_encode(true);
156
		} else {
157
			echo json_encode(false);
158
		}
159
	}
160
161
	public function id_alias() {
162
		$id_alias = $this->Produto->find('first', array(
163
				'conditions' => array('Produto.ativo' => 1),
164
				'order' => array('Produto.id' => 'desc')
165
			)
166
		);
167
168
		return $id_alias['Produto']['id_alias'] + 1;
169
	}
170
171
	public function carregar_dados_venda_ajax() {
172
		$this->layout = 'ajax';
173
174
		$retorno = $this->Produto->find('first', 
175
			array('conditions' => 
176
				array('Produto.ativo' => 1,
177
					  'Produto.id_usuario' => $this->instancia,
178
					  'Produto.id' => $this->request->data('id')
179
				)
180
			)
181
		);
182
183
		if (!$this->validar_estoque($retorno)) {
184
			return false;
185
		}
186
187
		$retorno['Produto']['total'] = $this->calcular_preco_produto_venda($retorno['Produto']['preco'], $this->request->data('qnt'));
188
189
		$retorno['Produto']['preco'] = number_format($retorno['Produto']['preco'], 2, ',', '.');
190
		
191
		echo json_encode($retorno);
192
	}
193
194
	public function validar_estoque($produto) {
195
		if (empty($produto) && !isset($produto)) {
196
			return false;
197
		}
198
		
199
		if ($produto['Produto']['estoque'] <= 0) {
200
			return false;
201
		}
202
203
		return true;
204
	}
205
206
	public function calcular_preco_produto_venda($preco, $qnt) {
207
		if (empty($preco) || !isset($preco)) {
208
			return false;
209
		}
210
211
		if (!is_numeric($qnt)) {
212
			return false;
213
		}
214
215
		$retorno = $preco * $qnt;
216
217
		return number_format($retorno, 2, ',', '.');
218
	}
219
220 View Code Duplication
	public function uploadImage(&$image) {
221
		$type = substr($image['name'], -4);
222
		$nameImage = uniqid() . md5($image['name']) . $type;
223
		$dir = APP . 'webroot/uploads/produto/imagens/';
224
		
225
		$returnUpload = move_uploaded_file($image['tmp_name'], $dir . $nameImage);
226
227
		if (!$returnUpload)
228
			return array('nome' => null, 'status' => false);
229
230
		return array('nome' => $nameImage, 'status' => true);
231
	}
232
233
	public function visualizar_cadastro($id) {
234
		$this->layout = 'wadmin';
235
236
		$produto = $this->Produto->find('all', 
237
			array('conditions' => 
238
				array('ativo' => 1,
239
					  'id' => $id
240
				)
241
			)
242
		);
243
244
		if (empty($produto)) {
245
			$this->Session->setFlash("Produto não encotrado, tente novamente");
246
			$this->redirect("/produto/listar_cadastros");
247
		}
248
249
		$this->set('produto', $produto[0]);
250
	}
251
252
	public function exportar_excel_exemplo() {
253
		include(APP . 'Vendor/PHPExcel/PHPExcel.php');
254
		include(APP . 'Vendor/PHPExcel/PHPExcel/IOFactory.php');
255
256
        $objPHPExcel = new PHPExcel();
257
        // Definimos o estilo da fonte
258
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
259
260
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
261
262
        // Criamos as colunas
263
        $objPHPExcel->setActiveSheetIndex(0)
0 ignored issues
show
Bug introduced by
The method setCellValue does only exist in PHPExcel_Worksheet, but not in PHPExcel_Cell.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
264
                    ->setCellValue('A1', "Nome do Produto")
265
                    ->setCellValue('B1', "Preço ")
266
                    ->setCellValue("C1", "Peso Bruto")
267
                    ->setCellValue("D1", "Peso Liquido")
268
                    ->setCellValue("E1", "Estoque")
269
                    ->setCellValue("F1", "Descrição");
270
271
        // Podemos renomear o nome das planilha atual, lembrando que um único arquivo pode ter várias planilhas
272
        $objPHPExcel->getActiveSheet()->setTitle('Listagem de produtos');
273
274
        // Cabeçalho do arquivo para ele baixar
275
        header('Content-Type: application/vnd.ms-excel');
276
        header('Content-Disposition: attachment;filename="planilha_importacao_exemplo.xls"');
277
        header('Cache-Control: max-age=0');
278
        // Se for o IE9, isso talvez seja necessário
279
        header('Cache-Control: max-age=1');
280
281
        // Acessamos o 'Writer' para poder salvar o arquivo
282
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
283
284
        // Salva diretamente no output, poderíamos mudar arqui para um nome de arquivo em um diretório ,caso não quisessemos jogar na tela
285
        $objWriter->save('php://output'); 
286
287
        exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method exportar_excel_exemplo() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
288
    }
289
290
    public function importar_produtos_planilha() {
0 ignored issues
show
Coding Style introduced by
importar_produtos_planilha uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
291
	include(APP . 'Vendor/PHPExcel/PHPExcel.php');
292
	include(APP . 'Vendor/PHPExcel/PHPExcel/IOFactory.php');
293
    	
294
        $objPHPExcel = new PHPExcel();
295
296
        if (!isset($_FILES['arquivo']['tmp_name']) && empty($_FILES['arquivo']['tmp_name']))
297
        {
298
			$this->Session->setFlash("Erro ao subir a planilha, tente novamente.");
299
			$this->redirect("/produto/listar_cadastros");        	
300
        }
301
302
        $typesPermissions = ['application/vnd.ms-excel'];
303
304
        if (!in_array($_FILES['arquivo']['type'], $typesPermissions))
305
        {
306
			$this->Session->setFlash("O arquivo deve ser no formato .xls.");
307
			$this->redirect("/produto/listar_cadastros");                	
308
        }
309
310
        $caminho = APP . 'webroot/uploads/produto/planilhas/' . uniqid() . '.xls';
311
312
        $inputFileName = $_FILES['arquivo']['tmp_name'];
313
314
        move_uploaded_file($inputFileName, $caminho);
315
316
        $data = [
317
        	'caminho' => $caminho,
318
        	'usuario_id' => $this->instancia,
319
        	'processado' => 0,
320
        	'ativo' => 1
321
        ];
322
323
        if ($this->QueueProducts->save($data))
324
        {
325
			$this->Session->setFlash("O arquivo está na fila para ser importado, iremos enviar um e-mail quando terminar.");
326
			$this->redirect("/produto/listar_cadastros");  
327
        }
328
        else 
329
        {
330
			$this->Session->setFlash("Ocorreu um erro, tente novamente.");
331
			$this->redirect("/produto/listar_cadastros");          	
332
        }
333
    }
334
335
    public function processar_planilhas_na_fila() {
336
    	$planilhas = [
337
	    	[
338
	    		'file' => 'teste.xls',
339
	    		'user_id' => 1
340
	    	]
341
    	];
342
343
    	$response = [];
344
    	foreach ($planilhas as $planilha) {
345
    		$response[] = $this->processar_planilhas();
0 ignored issues
show
Bug introduced by
The call to processar_planilhas() misses a required argument $inputFileName.

This check looks for function calls that miss required arguments.

Loading history...
Bug introduced by
Are you sure the assignment to $response[] is correct as $this->processar_planilhas() (which targets ProdutoController::processar_planilhas()) 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...
346
    	}
347
348
    	return $response;
349
    }
350
351
    public function processar_planilhas($inputFileName) {
352
		try {
353
		    $inputFileType 	= PHPExcel_IOFactory::identify($inputFileName);
354
		    $objReader 		= PHPExcel_IOFactory::createReader($inputFileType);
355
		    $objPHPExcel 	= $objReader->load($inputFileName);
356
		} catch(Exception $e) {
357
		    die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
0 ignored issues
show
Coding Style Compatibility introduced by
The method processar_planilhas() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
358
		}
359
360
		$dados = [];
361
362
		$rows = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
363
364
		for ($row = 2; $row <= $rows; $row++) {
365
			$rowInterator = $objPHPExcel->getActiveSheet()->getRowIterator($row)->current();
366
367
			$cellIterator = $rowInterator->getCellIterator();
368
			$cellIterator->setIterateOnlyExistingCells(false);
369
370
			foreach ($cellIterator as $i => $cell) {
371
				switch ($i) {
372
					case 0: //Codigo/SKU
373
						$dados[$row]['sku'] = $cell->getValue();
374
					break; 
375
					case 1: // Nome/Descrição 
376
						$dados[$row]['nome'] = $cell->getValue();						
377
					break;
378
					case 2: // QtdAtual
379
						//$dados[$row]['sku'] = $cell->getValue();						
380
					break;
381
					case 3: // QtdMinima  
382
						$dados[$row]['quantidade_minima'] = $cell->getValue();						
383
					break;
384
					case 4: // QtdTotal
385
						$dados[$row]['estoque'] = $cell->getValue();						
386
					break;
387
					case 5: // ValCusto
388
						$dados[$row]['custo'] = $cell->getValue();						
389
					break;
390
					case 6:  // ValVenda
391
						$dados[$row]['preco'] = $cell->getValue();						
392
					break;
393
				}
394
			}
395
		}
396
397
		pr($dados);
398
    }
399
400
}
401