Completed
Push — master ( 70a7c3...eafc32 )
by Reginaldo
32:10
created

VendaController::imprimir_nota_nao_fiscal()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 61
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 36
nc 2
nop 1
dl 0
loc 61
rs 9.5147
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
include 'ProdutoEstoqueController.php';
4
include 'VendaItensProdutoController.php';
5
include 'LancamentoVendasController.php';
6
include 'ImpressaoFiscalController.php';
7
8
class VendaController extends AppController {
9
10 View Code Duplication
	public function pdv() {
11
		$this->layout = 'wadmin';
12
13
		$this->loadModel('Produto');
14
15
		$this->set('produtos', $this->Produto->find('all',
16
				array('conditions' =>
17
					array('ativo' => 1,
18
						  'id_usuario' => $this->instancia
19
					)
20
				)
21
			)
22
		);
23
24
		$this->loadModel('Cliente');
25
26
		$this->set('clientes', $this->Cliente->find('all',
27
				array('conditions' =>
28
					array('ativo' => 1,
29
						  'id_usuario' => $this->instancia
30
					)
31
				)
32
			)
33
		);
34
	}
35
36
	public function recuperar_dados_venda_ajax() {
37
		$this->layout = 'ajax';
38
39
		$dados = $this->request->data('dados');
40
41
		$this->loadModel('Produto');
42
43
		$produto = $this->Produto->find('all',
44
			array('conditions' =>
45
				array('ativo' => 1,
46
					  'id_alias' => $dados['codigo_produto']
47
				)
48
			)
49
		);
50
51
		if (empty($produto)) {
52
			echo json_encode(false);
53
			return false;
54
		}
55
56
		echo json_encode($produto);
57
	}
58
59
	public function listar_cadastros() {
60
		$this->loadModel('LancamentoVenda');
61
62
		$this->layout = 'wadmin';
63
64
		$vendas = $this->Venda->find('all',
65
			array('conditions' =>
66
				array(
67
					'Venda.ativo' => 1,
68
					'Venda.id_usuario' => $this->instancia,
69
					'Venda.orcamento' => 0
70
				)
71
			)
72
		);
73
74
		foreach ($vendas as $i => $venda) {
75
			$lancamento = $this->LancamentoVenda->find('first', array('conditions' => array('LancamentoVenda.venda_id' => $venda['Venda']['id'])));
76
77
			$vendas[$i]['Lancamento'] = (isset($lancamento['LancamentoVenda'])) ? $lancamento['LancamentoVenda'] : array();
78
		}
79
80
		$this->set('vendas', $vendas);
81
	}
82
83 View Code Duplication
	public function adicionar_cadastro() {
84
		$this->layout = 'wadmin';
85
86
		$this->loadModel('Cliente');
87
88
		$this->set('clientes', $this->Cliente->find('all',
89
				array('conditions' =>
90
					array('ativo' => 1,
91
						  'id_usuario' => $this->instancia
92
					)
93
				)
94
			)
95
		);
96
97
		$this->loadModel('Produto');
98
99
		$this->set('produtos', $this->Produto->find('all',
100
				array('conditions' =>
101
					array('ativo' => 1,
102
						  'id_usuario' => $this->instancia
103
					)
104
				)
105
			)
106
		);
107
	}
108
109
	public function conveter_venda($vendaId) {
110
		$this->layout = 'wadmin';
111
112
		$this->loadModel('Cliente');
113
		
114
		$this->set('clientes', $this->Cliente->find('all',
115
				array('conditions' =>
116
					array('ativo' => 1,
117
						  'id_usuario' => $this->instancia
118
					)
119
				)
120
			)
121
		);
122
123
		$this->loadModel('Produto');
124
125
		$this->set('produtos', $this->Produto->find('all',
126
				array('conditions' =>
127
					array('ativo' => 1,
128
						  'id_usuario' => $this->instancia
129
					)
130
				)
131
			)
132
		);
133
134
		$this->set('venda', $this->Venda->find('all', 
135
				array('conditions' =>
136
					array(
137
						'Venda.ativo' => 1,
138
						'Venda.id' => $vendaId,
139
						'id_usuario' => $this->instancia
140
					)
141
				)
142
			)
143
		);
144
145
		$this->loadModel('VendaItensProduto');
146
147
		$venda_produtos = $this->VendaItensProduto->find('all', 
148
			array('conditions' => 
149
				array(
150
					'VendaItensProduto.ativo' => 1,
151
					'VendaItensProduto.id' => $vendaId
152
				)
153
			)
154
		);
155
156
		$this->loadModel('Produto');
157
158
		$produtos = [];
159
		foreach ($venda_produtos as $i => $venda_produto) 
160
		{
161
			$produto = $this->Produto->find('all',
162
				array('conditions' =>	
163
					array(
164
						'Produto.ativo' => 1,
165
						'Produto.id' => $venda_produto['VendaItensProduto']['produto_id']
166
					)
167
				)
168
			);
169
170 View Code Duplication
			if ($produto[0]['Produto']['estoque'] <= 0)
171
			{
172
				$this->Session->setFlash('O produto (' . $produto[0]['Produto']['nome'] .') não tem mais estoque disponivel!');
173
				continue;
174
			}
175
			
176
			$produtos[$i] = $produto[0]['Produto'];
177
			$produtos[$i]['quantidade'] = $venda_produto['VendaItensProduto']['quantidade_produto'];
178
179
			$total = $produtos[$i]['preco'] * $venda_produto['VendaItensProduto']['quantidade_produto'];
180
181
			$produtos[$i]['preco'] = number_format($produtos[$i]['preco'], 2, ',', '.');
182
			$produtos[$i]['total'] = number_format($total, 2, ',', '.');
183
		}
184
185
		$this->set('venda_produtos', $produtos);
186
	}
187
188
	public function s_adicionar_cadastro() {
189
		$dados_venda 	  = $this->request->data('venda');
190
		$dados_lancamento = $this->request->data('lancamento');
191
		$produtos 	      = $this->request->data('produto');
192
193
		if (!$this->validar_itens_venda($produtos) && !$dados_venda['orcamento']) {
194
			$this->Session->setFlash('Algum produto adicionado não possui estoque disponivel');
195
			$this->redirect('/venda/adicionar_cadastro');
196
		}
197
198
		$dados_venda['valor'] = $this->calcular_valor_venda($produtos);
199
		$dados_venda['custo'] = $this->calcular_custo_venda($produtos);
200
		
201
		$salvar_venda = $this->salvar_venda($produtos, $dados_lancamento, $dados_venda);
0 ignored issues
show
Bug introduced by
The call to salvar_venda() misses a required argument $usuario_id.

This check looks for function calls that miss required arguments.

Loading history...
202
		
203
		if (!$salvar_venda) {
204
			$this->Session->setFlash('Ocorreu um erro ao salvar a venda tente novamento');
205
			$this->redirect('/venda/adicionar_cadastro');
206
		}
207
		
208
		$this->Session->setFlash('Venda salva com sucesso');
209
		$this->redirect('/venda/adicionar_cadastro');
210
	}
211
212 View Code Duplication
	public function calcular_valor_venda($produtos) {
213
		$this->loadModel('Produto');
214
215
		(float) $preco = 0.00;
216
		foreach ($produtos as $indice => $item) {
217
			$produto = $this->Produto->find('all',
218
				array('conditions' =>
219
					array('Produto.id' => $item['id_produto'])
220
				)
221
			);
222
223
			$preco += $produto[0]['Produto']['preco'] * $item['quantidade'];
224
		}
225
226
		return $preco;
227
	}
228
229 View Code Duplication
	public function calcular_custo_venda($produtos) {
230
		$this->loadModel('Produto');
231
232
		(float) $custo = 0.00;
233
		foreach ($produtos as $indice => $item) {
234
			$produto = $this->Produto->find('all',
235
				array('conditions' =>
236
					array('Produto.id' => $item['id_produto'])
237
				)
238
			);
239
240
			$custo += $produto[0]['Produto']['custo'] * $item['quantidade'];
241
		}
242
243
		return $custo;
244
	}
245
246
	public function validar_itens_venda($produtos) {
247
		$this->loadModel('Produto');
248
249
		foreach ($produtos as $indice => $item) {
250
			$produto = $this->Produto->find('all',
251
				array('conditions' =>
252
					array('Produto.id' => $item['id_produto'])
253
				)
254
			);
255
256
			$objProdutoEstoqueController = new ProdutoEstoqueController();
257
258
			if (!$objProdutoEstoqueController->validar_estoque($produto, $item['quantidade'])) {
259
				return false;
260
			}			
261
		}
262
263
		return true;
264
	}
265
266
	public function salvar_venda($produtos, $lancamento, $informacoes, $usuario_id) {
267
		unset($informacoes['id_cliente']);
268
269
		$informacoes['data_venda'] = date('Y-m-d');
270
		$informacoes['id_usuario'] = $this->instancia != 'winners' ? $this->instancia : $usuario_id;
271
		$informacoes['ativo']	   = 1;
272
		$informacoes['desconto']   = (float) $informacoes['desconto'];
273
		$informacoes['valor']	   = $informacoes['valor'] - $informacoes['desconto'];
274
		$informacoes['orcamento']  = $informacoes['orcamento'];
275
276
		if (!$this->Venda->save($informacoes)) {
277
			$this->Session->setFlash('Ocorreu algum erro ao salvar a venda');
278
			return false;
279
		}
280
		
281
		$id_venda = $this->Venda->getLastInsertId();
282
283
		$objVendaItensProdutoController = new VendaItensProdutoController();
284
		if ($objVendaItensProdutoController->adicionar_itens_venda($id_venda, $produtos, $informacoes['orcamento']) === false) {
285
			return false;
286
		}
287
288
		$objLancamentoVendasController = new LancamentoVendasController();
289
		if ($objLancamentoVendasController->salvar_lancamento($id_venda, $lancamento, $informacoes['valor'], $informacoes['id_usuario']) === false) {
290
			return false;
291
		}
292
293
		return array('status' => true, 'id' => $id_venda);
294
	}
295
296
	public function relatorio_diario() {
297
		include(APP . 'Vendor/PHPExcel/PHPExcel.php');
298
		include(APP . 'Vendor/PHPExcel/PHPExcel/IOFactory.php');
299
300
        $objPHPExcel = new PHPExcel();
301
        // Definimos o estilo da fonte
302
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
303
304
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
305
306
        // Criamos as colunas
307
        $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...
308
                    ->setCellValue('A1', "Valor Venda")
309
                    ->setCellValue('B1', "Custo Médio ")
310
                    ->setCellValue("C1", "Valor Lucro")
311
                    ->setCellValue('D1', "ID Venda" );
312
313
314
        $vendas = $this->Venda->find('all',
315
        	array('conditions' => array(
316
        			'AND' => array(
317
        				'Venda.ativo' => 1,
318
        				'Venda.id_usuario' => $this->instancia,
319
        				'Venda.data_venda' => date('Y-m-d')
320
        			)
321
        		)
322
        	)
323
        );
324
325
        $i = 2;
326
        foreach ($vendas as $key => $venda) {
327
        	$objPHPExcel->setActiveSheetIndex(0)
328
        				->setCellValue('A'.$i, 'R$ ' . $venda['Venda']['valor'])
329
        				->setCellValue('B'.$i, 'R$ ' . $venda['Venda']['custo'])
330
        				->setCellValue('C'.$i, 'R$ ' . $venda['Venda']['valor'] - $venda['Venda']['custo'])
331
        				->setCellValue('D'.$i, $venda['Venda']['id']);
332
        	$i++;
333
        }
334
335
        // Podemos renomear o nome das planilha atual, lembrando que um único arquivo pode ter várias planilhas
336
        $objPHPExcel->getActiveSheet()->setTitle('Listagem de vendas');
337
338
        // Cabeçalho do arquivo para ele baixar
339
        header('Content-Type: application/vnd.ms-excel');
340
        header('Content-Disposition: attachment;filename="relatorio_vendas_'.date('d-m-Y').'.xls"');
341
        header('Cache-Control: max-age=0');
342
        // Se for o IE9, isso talvez seja necessário
343
        header('Cache-Control: max-age=1');
344
345
        // Acessamos o 'Writer' para poder salvar o arquivo
346
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
347
348
        // Salva diretamente no output, poderíamos mudar arqui para um nome de arquivo em um diretório ,caso não quisessemos jogar na tela
349
        $objWriter->save('php://output'); 
350
351
        exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method relatorio_diario() 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...
352
	}
353
354
	public function recoverDataToDashboardOneWeek($id_usuario){
355
		$vendas = $this->Venda->find('all',
356
			array('conditions' =>
357
				array(
358
					'Venda.ativo' => 1,
359
					'Venda.id_usuario' => $id_usuario,
360
				),
361
				'limit' => 6
362
			)
363
		);
364
		
365
		$resposta = [];
366
		foreach ($vendas as $i => $venda) {
367
			$resposta[] = (float) number_format($venda['Venda']['valor'], 2, '.', ',');
368
		}
369
370
		$resposta = [
371
			'name' => 'Valor',
372
			'data' => $resposta
373
		];
374
375
		return json_encode($resposta);
376
	}
377
378 View Code Duplication
	public function excluir_cadastro() {
379
		$this->layout = 'ajax';
380
381
		$id = $this->request->data('id');
382
383
		$dados = array('ativo' => '0');
384
		$parametros = array('id' => $id);
385
386
		if ($this->Venda->updateAll($dados, $parametros)) {
387
			echo json_encode(true);
388
		} else {
389
			echo json_encode(false);
390
		}
391
	}
392
393
	public function imprimir_nota_nao_fiscal($id) {
394
		$this->loadModel('LancamentoVenda');
395
		$this->loadModel('VendaItensProduto');
396
		$this->loadModel('Produto');
397
398
		$ImpressaoFiscalController = new ImpressaoFiscalController;
399
400
		$dados_venda = $this->Venda->find('first',
401
			array('conditions' =>
402
				array(
403
					'Venda.ativo' => 1,
404
					'Venda.id' => $id
405
				)
406
			)
407
		);
408
409
		$ImpressaoFiscalController->corpoTxt .= "Valor: " . $dados_venda['Venda']['valor'] . "\n\n";
0 ignored issues
show
Documentation introduced by
The property corpoTxt does not exist on object<ImpressaoFiscalController>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
410
		
411
		$dados_lancamento = $this->LancamentoVenda->find('first',
412
			array('conditions' => 
413
				array(
414
					'LancamentoVenda.ativo' => 1,
415
					'LancamentoVenda.venda_id' => $id
416
				)
417
			)
418
		);
419
420
		$ImpressaoFiscalController->corpoTxt .= "Forma de Pagamento: " . $dados_lancamento['LancamentoVenda']['forma_pagamento'] . "\n\n";
0 ignored issues
show
Documentation introduced by
The property corpoTxt does not exist on object<ImpressaoFiscalController>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
421
		
422
		$produtos = $this->VendaItensProduto->find('all', 
423
			array('conditions' =>
424
				array(
425
					'VendaItensProduto.venda_id' => $id
426
				)
427
			)
428
		);
429
430
		$itens = array();
431
		foreach ($produtos as $i => $item) {
432
			$produto = $this->Produto->find('first',
433
				array('conditions' =>
434
					array('Produto.id' => $item['VendaItensProduto']['produto_id'])
435
				)
436
			);	
437
438
			$total = $produto['Produto']['preco'] * $item['VendaItensProduto']['quantidade_produto'];
439
440
			$ImpressaoFiscalController->corpoTxt .= ""
0 ignored issues
show
Documentation introduced by
The property corpoTxt does not exist on object<ImpressaoFiscalController>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
441
						   . "Produto: " . $produto['Produto']['nome'] . " Quantidade: "
442
						   . $item['VendaItensProduto']['quantidade_produto'] 
443
						   . "\nPreço: " . $produto['Produto']['preco']
444
						   . "\nTotal: " . number_format($total, 2, ',', '.')
445
						   . "\n----------------------------------------------\n";
446
		}
447
448
		$file = $ImpressaoFiscalController->gerar_arquivo();
449
		
450
		echo json_encode(array('file' => $file));
451
452
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method imprimir_nota_nao_fiscal() 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...
453
	}
454
455
}
456