Completed
Push — master ( f167ad...c55a69 )
by Reginaldo
31:05
created

VendaController   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 362
Duplicated Lines 26.52 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 5
Bugs 2 Features 0
Metric Value
c 5
b 2
f 0
dl 96
loc 362
rs 10
wmc 28
lcom 1
cbo 13

12 Methods

Rating   Name   Duplication   Size   Complexity  
B pdv() 25 25 1
A recuperar_dados_venda_ajax() 0 22 2
A listar_cadastros() 14 14 1
B adicionar_cadastro() 25 25 1
B conveter_venda() 0 78 3
B s_adicionar_cadastro() 0 23 4
A calcular_valor_venda() 16 16 2
A calcular_custo_venda() 16 16 2
A validar_itens_venda() 0 19 3
B salvar_venda() 0 29 5
A relatorio_diario() 0 57 2
A recoverDataToDashboardOneWeek() 0 23 2

How to fix   Duplicated Code   

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:

1
<?php
2
3
include 'ProdutoEstoqueController.php';
4
include 'VendaItensProdutoController.php';
5
include 'LancamentoVendasController.php';
6
7
class VendaController extends AppController {
8
9 View Code Duplication
	public function pdv() {
10
		$this->layout = 'wadmin';
11
12
		$this->loadModel('Produto');
13
14
		$this->set('produtos', $this->Produto->find('all',
15
				array('conditions' =>
16
					array('ativo' => 1,
17
						  'id_usuario' => $this->instancia
18
					)
19
				)
20
			)
21
		);
22
23
		$this->loadModel('Cliente');
24
25
		$this->set('clientes', $this->Cliente->find('all',
26
				array('conditions' =>
27
					array('ativo' => 1,
28
						  'id_usuario' => $this->instancia
29
					)
30
				)
31
			)
32
		);
33
	}
34
35
	public function recuperar_dados_venda_ajax() {
36
		$this->layout = 'ajax';
37
38
		$dados = $this->request->data('dados');
39
40
		$this->loadModel('Produto');
41
42
		$produto = $this->Produto->find('all',
43
			array('conditions' =>
44
				array('ativo' => 1,
45
					  'id_alias' => $dados['codigo_produto']
46
				)
47
			)
48
		);
49
50
		if (empty($produto)) {
51
			echo json_encode(false);
52
			return false;
53
		}
54
55
		echo json_encode($produto);
56
	}
57
58 View Code Duplication
	public function listar_cadastros() {
59
		$this->layout = 'wadmin';
60
61
		$this->set('vendas', $this->Venda->find('all',
62
				array('conditions' =>
63
					array(
64
						'ativo' => 1,
65
						'id_usuario' => $this->instancia,
66
						'orcamento' => 0
67
					)
68
				)
69
			)
70
		);
71
	}
72
73 View Code Duplication
	public function adicionar_cadastro() {
74
		$this->layout = 'wadmin';
75
76
		$this->loadModel('Cliente');
77
78
		$this->set('clientes', $this->Cliente->find('all',
79
				array('conditions' =>
80
					array('ativo' => 1,
81
						  'id_usuario' => $this->instancia
82
					)
83
				)
84
			)
85
		);
86
87
		$this->loadModel('Produto');
88
89
		$this->set('produtos', $this->Produto->find('all',
90
				array('conditions' =>
91
					array('ativo' => 1,
92
						  'id_usuario' => $this->instancia
93
					)
94
				)
95
			)
96
		);
97
	}
98
99
	public function conveter_venda($vendaId) {
100
		$this->layout = 'wadmin';
101
102
		$this->loadModel('Cliente');
103
		
104
		$this->set('clientes', $this->Cliente->find('all',
105
				array('conditions' =>
106
					array('ativo' => 1,
107
						  'id_usuario' => $this->instancia
108
					)
109
				)
110
			)
111
		);
112
113
		$this->loadModel('Produto');
114
115
		$this->set('produtos', $this->Produto->find('all',
116
				array('conditions' =>
117
					array('ativo' => 1,
118
						  'id_usuario' => $this->instancia
119
					)
120
				)
121
			)
122
		);
123
124
		$this->set('venda', $this->Venda->find('all', 
125
				array('conditions' =>
126
					array(
127
						'Venda.ativo' => 1,
128
						'Venda.id' => $vendaId,
129
						'id_usuario' => $this->instancia
130
					)
131
				)
132
			)
133
		);
134
135
		$this->loadModel('VendaItensProduto');
136
137
		$venda_produtos = $this->VendaItensProduto->find('all', 
138
			array('conditions' => 
139
				array(
140
					'VendaItensProduto.ativo' => 1,
141
					'VendaItensProduto.id' => $vendaId
142
				)
143
			)
144
		);
145
146
		$this->loadModel('Produto');
147
148
		$produtos = [];
149
		foreach ($venda_produtos as $i => $venda_produto) 
150
		{
151
			$produto = $this->Produto->find('all',
152
				array('conditions' =>	
153
					array(
154
						'Produto.ativo' => 1,
155
						'Produto.id' => $venda_produto['VendaItensProduto']['produto_id']
156
					)
157
				)
158
			);
159
160
			if ($produto[0]['Produto']['estoque'] <= 0)
161
			{
162
				$this->Session->setFlash('O produto (' . $produto[0]['Produto']['nome'] .') não tem mais estoque disponivel!');
163
				continue;
164
			}
165
			
166
			$produtos[$i] = $produto[0]['Produto'];
167
			$produtos[$i]['quantidade'] = $venda_produto['VendaItensProduto']['quantidade_produto'];
168
169
			$total = $produtos[$i]['preco'] * $venda_produto['VendaItensProduto']['quantidade_produto'];
170
171
			$produtos[$i]['preco'] = number_format($produtos[$i]['preco'], 2, ',', '.');
172
			$produtos[$i]['total'] = number_format($total, 2, ',', '.');
173
		}
174
175
		$this->set('venda_produtos', $produtos);
176
	}
177
178
	public function s_adicionar_cadastro() {
179
		$dados_venda 	  = $this->request->data('venda');
180
		$dados_lancamento = $this->request->data('lancamento');
181
		$produtos 	      = $this->request->data('produto');
182
183
		if (!$this->validar_itens_venda($produtos) && !$dados_venda['orcamento']) {
184
			$this->Session->setFlash('Algum produto adicionado não possui estoque disponivel');
185
			$this->redirect('/venda/adicionar_cadastro');
186
		}
187
188
		$dados_venda['valor'] = $this->calcular_valor_venda($produtos);
189
		$dados_venda['custo'] = $this->calcular_custo_venda($produtos);
190
		
191
		$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...
192
		
193
		if (!$salvar_venda) {
194
			$this->Session->setFlash('Ocorreu um erro ao salvar a venda tente novamento');
195
			$this->redirect('/venda/adicionar_cadastro');
196
		}
197
		
198
		$this->Session->setFlash('Venda salva com sucesso');
199
		$this->redirect('/venda/adicionar_cadastro');
200
	}
201
202 View Code Duplication
	public function calcular_valor_venda($produtos) {
203
		$this->loadModel('Produto');
204
205
		(float) $preco = 0.00;
206
		foreach ($produtos as $indice => $item) {
207
			$produto = $this->Produto->find('all',
208
				array('conditions' =>
209
					array('Produto.id' => $item['id_produto'])
210
				)
211
			);
212
213
			$preco += $produto[0]['Produto']['preco'] * $item['quantidade'];
214
		}
215
216
		return $preco;
217
	}
218
219 View Code Duplication
	public function calcular_custo_venda($produtos) {
220
		$this->loadModel('Produto');
221
222
		(float) $custo = 0.00;
223
		foreach ($produtos as $indice => $item) {
224
			$produto = $this->Produto->find('all',
225
				array('conditions' =>
226
					array('Produto.id' => $item['id_produto'])
227
				)
228
			);
229
230
			$custo += $produto[0]['Produto']['custo'] * $item['quantidade'];
231
		}
232
233
		return $custo;
234
	}
235
236
	public function validar_itens_venda($produtos) {
237
		$this->loadModel('Produto');
238
239
		foreach ($produtos as $indice => $item) {
240
			$produto = $this->Produto->find('all',
241
				array('conditions' =>
242
					array('Produto.id' => $item['id_produto'])
243
				)
244
			);
245
246
			$objProdutoEstoqueController = new ProdutoEstoqueController();
247
248
			if (!$objProdutoEstoqueController->validar_estoque($produto, $item['quantidade'])) {
249
				return false;
250
			}			
251
		}
252
253
		return true;
254
	}
255
256
	public function salvar_venda($produtos, $lancamento, $informacoes, $usuario_id) {
257
		unset($informacoes['id_cliente']);
258
259
		$informacoes['data_venda'] = date('Y-m-d');
260
		$informacoes['id_usuario'] = $this->instancia != 'winners' ? $this->instancia : $usuario_id;
261
		$informacoes['ativo']	   = 1;
262
		$informacoes['desconto']   = (float) $informacoes['desconto'];
263
		$informacoes['valor']	   = $informacoes['valor'] - $informacoes['desconto'];
264
		$informacoes['orcamento']  = $informacoes['orcamento'];
265
266
		if (!$this->Venda->save($informacoes)) {
267
			$this->Session->setFlash('Ocorreu algum erro ao salvar a venda');
268
			return false;
269
		}
270
		
271
		$id_venda = $this->Venda->getLastInsertId();
272
273
		$objVendaItensProdutoController = new VendaItensProdutoController();
274
		if ($objVendaItensProdutoController->adicionar_itens_venda($id_venda, $produtos, $informacoes['orcamento']) === false) {
275
			return false;
276
		}
277
278
		$objLancamentoVendasController = new LancamentoVendasController();
279
		if ($objLancamentoVendasController->salvar_lancamento($id_venda, $lancamento, $informacoes['valor']) === false) {
280
			return false;
281
		}
282
283
		return array('status' => true, 'id' => $id_venda);
284
	}
285
286
	public function relatorio_diario() {
287
		include(APP . 'Vendor/PHPExcel/PHPExcel.php');
288
		include(APP . 'Vendor/PHPExcel/PHPExcel/IOFactory.php');
289
290
        $objPHPExcel = new PHPExcel();
291
        // Definimos o estilo da fonte
292
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
293
294
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
295
296
        // Criamos as colunas
297
        $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...
298
                    ->setCellValue('A1', "Valor Venda")
299
                    ->setCellValue('B1', "Custo Médio ")
300
                    ->setCellValue("C1", "Valor Lucro")
301
                    ->setCellValue('D1', "ID Venda" );
302
303
304
        $vendas = $this->Venda->find('all',
305
        	array('conditions' => array(
306
        			'AND' => array(
307
        				'Venda.ativo' => 1,
308
        				'Venda.id_usuario' => $this->instancia,
309
        				'Venda.data_venda' => date('Y-m-d')
310
        			)
311
        		)
312
        	)
313
        );
314
315
        $i = 2;
316
        foreach ($vendas as $key => $venda) {
317
        	$objPHPExcel->setActiveSheetIndex(0)
318
        				->setCellValue('A'.$i, 'R$ ' . $venda['Venda']['valor'])
319
        				->setCellValue('B'.$i, 'R$ ' . $venda['Venda']['custo'])
320
        				->setCellValue('C'.$i, 'R$ ' . $venda['Venda']['valor'] - $venda['Venda']['custo'])
321
        				->setCellValue('D'.$i, $venda['Venda']['id']);
322
        	$i++;
323
        }
324
325
        // Podemos renomear o nome das planilha atual, lembrando que um único arquivo pode ter várias planilhas
326
        $objPHPExcel->getActiveSheet()->setTitle('Listagem de vendas');
327
328
        // Cabeçalho do arquivo para ele baixar
329
        header('Content-Type: application/vnd.ms-excel');
330
        header('Content-Disposition: attachment;filename="relatorio_vendas_'.date('d-m-Y').'.xls"');
331
        header('Cache-Control: max-age=0');
332
        // Se for o IE9, isso talvez seja necessário
333
        header('Cache-Control: max-age=1');
334
335
        // Acessamos o 'Writer' para poder salvar o arquivo
336
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
337
338
        // Salva diretamente no output, poderíamos mudar arqui para um nome de arquivo em um diretório ,caso não quisessemos jogar na tela
339
        $objWriter->save('php://output'); 
340
341
        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...
342
	}
343
344
	public function recoverDataToDashboardOneWeek(){
345
		$vendas = $this->Venda->find('all',
346
			array('conditions' =>
347
				array(
348
					'ativo' => 1,
349
					'id_usuario' => $this->instancia,
350
				),
351
				'limit' => 6
352
			)
353
		);
354
355
		$resposta = [];
356
		foreach ($vendas as $i => $venda) {
357
			$resposta[] = (float) number_format($venda['Venda']['valor'], 2, '.', ',');
358
		}
359
360
		$resposta = [
361
			'name' => 'Valor',
362
			'data' => $resposta
363
		];
364
365
		return json_encode($resposta);
366
	}
367
368
}
369