Completed
Push — master ( ec6e99...35fe67 )
by Reginaldo
37:05
created

VendaController::excluir_cadastro()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 14
Ratio 100 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 0
dl 14
loc 14
rs 9.4285
c 0
b 0
f 0
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
	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
	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
		$this->set('vendaId', $this->Session->read('UltimoIdVendaSalvo'));
109
	}
110
111
	public function conveter_venda($vendaId) {
112
		$this->layout = 'wadmin';
113
114
		$this->loadModel('Cliente');
115
		
116
		$this->set('clientes', $this->Cliente->find('all',
117
				array('conditions' =>
118
					array('ativo' => 1,
119
						  'id_usuario' => $this->instancia
120
					)
121
				)
122
			)
123
		);
124
125
		$this->loadModel('Produto');
126
127
		$this->set('produtos', $this->Produto->find('all',
128
				array('conditions' =>
129
					array('ativo' => 1,
130
						  'id_usuario' => $this->instancia
131
					)
132
				)
133
			)
134
		);
135
136
		$this->set('venda', $this->Venda->find('all', 
137
				array('conditions' =>
138
					array(
139
						'Venda.ativo' => 1,
140
						'Venda.id' => $vendaId,
141
						'id_usuario' => $this->instancia
142
					)
143
				)
144
			)
145
		);
146
147
		$this->loadModel('VendaItensProduto');
148
149
		$venda_produtos = $this->VendaItensProduto->find('all', 
150
			array('conditions' => 
151
				array(
152
					'VendaItensProduto.ativo' => 1,
153
					'VendaItensProduto.id' => $vendaId
154
				)
155
			)
156
		);
157
158
		$this->loadModel('Produto');
159
160
		$produtos = [];
161
		foreach ($venda_produtos as $i => $venda_produto) 
162
		{
163
			$produto = $this->Produto->find('all',
164
				array('conditions' =>	
165
					array(
166
						'Produto.ativo' => 1,
167
						'Produto.id' => $venda_produto['VendaItensProduto']['produto_id']
168
					)
169
				)
170
			);
171
172 View Code Duplication
			if ($produto[0]['Produto']['estoque'] <= 0)
173
			{
174
				$this->Session->setFlash('O produto (' . $produto[0]['Produto']['nome'] .') não tem mais estoque disponivel!');
175
				continue;
176
			}
177
			
178
			$produtos[$i] = $produto[0]['Produto'];
179
			$produtos[$i]['quantidade'] = $venda_produto['VendaItensProduto']['quantidade_produto'];
180
181
			$total = $produtos[$i]['preco'] * $venda_produto['VendaItensProduto']['quantidade_produto'];
182
183
			$produtos[$i]['preco'] = number_format($produtos[$i]['preco'], 2, ',', '.');
184
			$produtos[$i]['total'] = number_format($total, 2, ',', '.');
185
		}
186
187
		$this->set('venda_produtos', $produtos);
188
	}
189
190
	public function s_adicionar_cadastro() {
191
		$dados_venda 	  = $this->request->data('venda');
192
		$dados_lancamento = $this->request->data('lancamento');
193
		$produtos 	      = $this->request->data('produto');
194
195
		if (!$this->validar_itens_venda($produtos) && !$dados_venda['orcamento']) {
196
			$this->Session->setFlash('Algum produto adicionado não possui estoque disponivel');
197
			$this->redirect('/venda/adicionar_cadastro');
198
		}
199
200
		$dados_venda['valor'] = $this->calcular_valor_venda($produtos);
201
		$dados_venda['custo'] = $this->calcular_custo_venda($produtos);
202
		
203
		$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...
204
		
205
		if (!$salvar_venda) {
206
			$this->Session->setFlash('Ocorreu um erro ao salvar a venda tente novamento');
207
			$this->redirect('/venda/adicionar_cadastro');
208
		}
209
210
		$this->Session->write('UltimoIdVendaSalvo', $salvar_venda['id']);
211
		
212
		$this->Session->setFlash('Venda salva com sucesso');
213
		$this->redirect('/venda/adicionar_cadastro');
214
	}
215
216 View Code Duplication
	public function calcular_valor_venda($produtos) {
217
		$this->loadModel('Produto');
218
219
		(float) $preco = 0.00;
220
		foreach ($produtos as $indice => $item) {
221
			$produto = $this->Produto->find('all',
222
				array('conditions' =>
223
					array('Produto.id' => $item['id_produto'])
224
				)
225
			);
226
227
			$preco += $produto[0]['Produto']['preco'] * $item['quantidade'];
228
		}
229
230
		return $preco;
231
	}
232
233 View Code Duplication
	public function calcular_custo_venda($produtos) {
234
		$this->loadModel('Produto');
235
236
		(float) $custo = 0.00;
237
		foreach ($produtos as $indice => $item) {
238
			$produto = $this->Produto->find('all',
239
				array('conditions' =>
240
					array('Produto.id' => $item['id_produto'])
241
				)
242
			);
243
244
			$custo += $produto[0]['Produto']['custo'] * $item['quantidade'];
245
		}
246
247
		return $custo;
248
	}
249
250
	public function validar_itens_venda($produtos) {
251
		$this->loadModel('Produto');
252
253
		foreach ($produtos as $indice => $item) {
254
			$produto = $this->Produto->find('all',
255
				array('conditions' =>
256
					array('Produto.id' => $item['id_produto'])
257
				)
258
			);
259
260
			$objProdutoEstoqueController = new ProdutoEstoqueController();
261
262
			if (!$objProdutoEstoqueController->validar_estoque($produto, $item['quantidade'])) {
263
				return false;
264
			}			
265
		}
266
267
		return true;
268
	}
269
270
	public function salvar_venda($produtos, $lancamento, $informacoes, $usuario_id) {
271
		unset($informacoes['id_cliente']);
272
273
		$informacoes['data_venda'] = date('Y-m-d');
274
		$informacoes['id_usuario'] = $this->instancia != 'winners' ? $this->instancia : $usuario_id;
275
		$informacoes['ativo']	   = 1;
276
		$informacoes['desconto']   = (float) $informacoes['desconto'];
277
		$informacoes['valor']	   = $informacoes['valor'] - $informacoes['desconto'];
278
		$informacoes['orcamento']  = $informacoes['orcamento'];
279
280
		if (!$this->Venda->save($informacoes)) {
281
			$this->Session->setFlash('Ocorreu algum erro ao salvar a venda');
282
			return false;
283
		}
284
		
285
		$id_venda = $this->Venda->getLastInsertId();
286
287
		$objVendaItensProdutoController = new VendaItensProdutoController();
288
289
		if ($objVendaItensProdutoController->adicionar_itens_venda($id_venda, $produtos, $informacoes['orcamento']) === false) {
290
			return false;
291
		}
292
293
		$objLancamentoVendasController = new LancamentoVendasController();
294
295
		if ($objLancamentoVendasController->salvar_lancamento($id_venda, $lancamento, $informacoes['valor'], $informacoes['id_usuario']) === false) {
296
			return false;
297
		}
298
299
		return array('status' => true, 'id' => $id_venda);
300
	}
301
302
	public function relatorio_diario() {
303
		include(APP . 'Vendor/PHPExcel/PHPExcel.php');
304
		include(APP . 'Vendor/PHPExcel/PHPExcel/IOFactory.php');
305
306
        $objPHPExcel = new PHPExcel();
307
        // Definimos o estilo da fonte
308
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
309
310
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
311
312
        // Criamos as colunas
313
        $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...
314
                    ->setCellValue('A1', "Valor Venda")
315
                    ->setCellValue('B1', "Custo Médio ")
316
                    ->setCellValue("C1", "Valor Lucro")
317
                    ->setCellValue('D1', "ID Venda" );
318
319
320
        $vendas = $this->Venda->find('all',
321
        	array('conditions' => array(
322
        			'AND' => array(
323
        				'Venda.ativo' => 1,
324
        				'Venda.id_usuario' => $this->instancia,
325
        				'Venda.data_venda' => date('Y-m-d')
326
        			)
327
        		)
328
        	)
329
        );
330
331
        $i = 2;
332
        foreach ($vendas as $key => $venda) {
333
        	$objPHPExcel->setActiveSheetIndex(0)
334
        				->setCellValue('A'.$i, 'R$ ' . $venda['Venda']['valor'])
335
        				->setCellValue('B'.$i, 'R$ ' . $venda['Venda']['custo'])
336
        				->setCellValue('C'.$i, 'R$ ' . $venda['Venda']['valor'] - $venda['Venda']['custo'])
337
        				->setCellValue('D'.$i, $venda['Venda']['id']);
338
        	$i++;
339
        }
340
341
        // Podemos renomear o nome das planilha atual, lembrando que um único arquivo pode ter várias planilhas
342
        $objPHPExcel->getActiveSheet()->setTitle('Listagem de vendas');
343
344
        // Cabeçalho do arquivo para ele baixar
345
        header('Content-Type: application/vnd.ms-excel');
346
        header('Content-Disposition: attachment;filename="relatorio_vendas_'.date('d-m-Y').'.xls"');
347
        header('Cache-Control: max-age=0');
348
        // Se for o IE9, isso talvez seja necessário
349
        header('Cache-Control: max-age=1');
350
351
        // Acessamos o 'Writer' para poder salvar o arquivo
352
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
353
354
        // Salva diretamente no output, poderíamos mudar arqui para um nome de arquivo em um diretório ,caso não quisessemos jogar na tela
355
        $objWriter->save('php://output'); 
356
357
        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...
358
	}
359
360
	public function recoverDataToDashboardOneWeek($id_usuario){
361
		$vendas = $this->Venda->find('all',
362
			array('conditions' =>
363
				array(
364
					'Venda.ativo' => 1,
365
					'Venda.id_usuario' => $id_usuario,
366
				),
367
				'limit' => 6
368
			)
369
		);
370
		
371
		$resposta = [];
372
		foreach ($vendas as $i => $venda) {
373
			$resposta[] = (float) number_format($venda['Venda']['valor'], 2, '.', ',');
374
		}
375
376
		$resposta = [
377
			'name' => 'Valor',
378
			'data' => $resposta
379
		];
380
381
		return json_encode($resposta);
382
	}
383
384 View Code Duplication
	public function excluir_cadastro() {
385
		$this->layout = 'ajax';
386
387
		$id = $this->request->data('id');
388
389
		$dados = array('ativo' => '0');
390
		$parametros = array('id' => $id);
391
392
		if ($this->Venda->updateAll($dados, $parametros)) {
393
			echo json_encode(true);
394
		} else {
395
			echo json_encode(false);
396
		}
397
	}
398
399
	public function imprimir_nota_nao_fiscal($id) {
400
		$this->loadModel('LancamentoVenda');
401
		$this->loadModel('VendaItensProduto');
402
		$this->loadModel('Produto');
403
		$this->loadModel('Usuario');
404
405
		$ImpressaoFiscalController = new ImpressaoFiscalController;
406
407
		$dados_venda = $this->Venda->find('first',
408
			array('conditions' =>
409
				array(
410
					'Venda.ativo' => 1,
411
					'Venda.id' => $id
412
				)
413
			)
414
		);
415
416
		$usuario = $this->Usuario->find('first',
417
			array('conditions' =>
418
				array(
419
					'Usuario.id' => $dados_venda['Venda']['id_usuario']
420
				)
421
			)
422
		);
423
		
424
		$ImpressaoFiscalController->userName = $usuario['Usuario']['nome'];
0 ignored issues
show
Documentation introduced by
The property $userName is declared protected in ImpressaoFiscalController. Since you implemented __set(), maybe consider adding a @property or @property-write annotation. This makes it easier for IDEs to provide auto-completion.

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...
425
426
		$ImpressaoFiscalController->corpoTxt .= "Valor: R$ " . number_format($dados_venda['Venda']['valor'], 2, ',', '.') . "\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...
427
		
428
		$dados_lancamento = $this->LancamentoVenda->find('first',
429
			array('conditions' => 
430
				array(
431
					'LancamentoVenda.ativo' => 1,
432
					'LancamentoVenda.venda_id' => $id
433
				)
434
			)
435
		);
436
437
		$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...
438
		
439
		$produtos = $this->VendaItensProduto->find('all', 
440
			array('conditions' =>
441
				array(
442
					'VendaItensProduto.venda_id' => $id
443
				)
444
			)
445
		);
446
447
		$itens = array();
448
		foreach ($produtos as $i => $item) {
449
			$produto = $this->Produto->find('first',
450
				array('conditions' =>
451
					array('Produto.id' => $item['VendaItensProduto']['produto_id'])
452
				)
453
			);	
454
455
			$total = $produto['Produto']['preco'] * $item['VendaItensProduto']['quantidade_produto'];
456
457
			$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...
458
						   . "Produto: " . $produto['Produto']['nome']
459
						   . "\nQuantidade: " . $item['VendaItensProduto']['quantidade_produto'] 
460
						   . "\nPreço: R$ " . number_format($produto['Produto']['preco'], 2, ',', '.')
461
						   . "\nTotal: R$ " . number_format($total, 2, ',', '.')
462
						   . "\n--------------------------\n";
463
		}
464
465
		$file = $ImpressaoFiscalController->gerar_arquivo();
466
		
467
		echo json_encode(array('file' => $file));
468
469
		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...
470
	}
471
472
	public function clear_session_venda($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
473
	{
474
		$this->Session->write('UltimoIdVendaSalvo', null);
475
	}
476
477
}
478