Completed
Push — master ( 74e083...761efc )
by Reginaldo
32:50
created

ProdutoController::visualizar_cadastro()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 10
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 18
rs 9.4285
1
<?php
2
3
ini_set('max_execution_time', 300);
4
5
class ProdutoController extends AppController{		
6
7 View Code Duplication
	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 listar_cadastros_ajax() {
0 ignored issues
show
Coding Style introduced by
listar_cadastros_ajax uses the super-global variable $_GET 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...
21
		$this->layout = 'ajax';
22
23
		$aColumns = array( 'sku', 'imagem', 'nome', 'preco', 'estoque' );
24
		
25
		$conditions = array('conditions' =>
26
			array(
27
				'ativo' => 1,
28
				'id_usuario' => $this->instancia
29
			)
30
		);
31
32
		$allProdutos = $this->Produto->find('all', $conditions);
33
		
34
		if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
35
		{
36
			$conditions['offset'] = $_GET['iDisplayStart'];
37
			$conditions['limit'] = $_GET['iDisplayLength'];
38
		}
39
40
		if ( isset( $_GET['iSortCol_0'] ) )
41
		{
42
			for ( $i=0 ; $i < intval( $_GET['iSortingCols'] ) ; $i++ )
43
			{
44
				if ( $_GET[ 'bSortable_' . intval($_GET['iSortCol_' . $i]) ] == "true" )
45
				{
46
					$conditions['order'] = array('Produto.' . $aColumns[intval($_GET['iSortCol_' . $i])] => $_GET['sSortDir_'.$i]);
47
				}
48
			}
49
		}
50
51
		if ( isset( $_GET['sSearch'] ) && !empty( $_GET['sSearch'] ) )
52
		{
53
			$conditions['conditions']['Produto.nome LIKE '] = '%' . $_GET['sSearch'] . '%';
54
		}
55
		
56
		$produtos = $this->Produto->find('all', $conditions);
57
58
		$output = array(
59
			"sEcho" => intval($_GET['sEcho']),
60
			"iTotalDisplayRecords" => count($allProdutos),
61
			"iTotalRecords" => count($produtos),
62
			"aaData" => array()
63
		);
64
65
		foreach ( $produtos as $i => $produto )
66
		{
67
			$row = array();
68
69
			for ( $i=0 ; $i < count($aColumns) ; $i++ )
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

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