Completed
Push — master ( 3c651b...a8e8b7 )
by Reginaldo
18:03
created

VendaController::relatorio()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 47
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 29
nc 3
nop 0
dl 0
loc 47
rs 9.0303
c 0
b 0
f 0
1
<?php
2
3
require_once(ROOT . DS . 'vendor' . DS . 'autoload.php');
4
5
use Dompdf\Dompdf;
6
7
include 'ProdutoEstoqueController.php';
8
include 'VendaItensProdutoController.php';
9
include 'LancamentoVendasController.php';
10
include 'ImpressaoFiscalController.php';
11
12
class VendaController extends AppController {
13
14
	public function pdv() {
15
		$this->layout = 'wadmin';
16
17
		$this->loadModel('Produto');
18
19
		$this->set('produtos', $this->Produto->find('all',
20
				array('conditions' =>
21
					array('ativo' => 1,
22
						  'id_usuario' => $this->instancia
23
					)
24
				)
25
			)
26
		);
27
28
		$this->loadModel('Cliente');
29
30
		$this->set('clientes', $this->Cliente->find('all',
31
				array('conditions' =>
32
					array('ativo' => 1,
33
						  'id_usuario' => $this->instancia
34
					)
35
				)
36
			)
37
		);
38
	}
39
40
	public function recuperar_dados_venda_ajax() {
41
		$this->layout = 'ajax';
42
43
		$dados = $this->request->data('dados');
44
45
		$this->loadModel('Produto');
46
47
		$produto = $this->Produto->find('all',
48
			array('conditions' =>
49
				array('ativo' => 1,
50
					  'id_alias' => $dados['codigo_produto']
51
				)
52
			)
53
		);
54
55
		if (empty($produto)) {
56
			echo json_encode(false);
57
			return false;
58
		}
59
60
		echo json_encode($produto);
61
	}
62
63
	public function listar_cadastros() {
64
		$this->loadModel('LancamentoVenda');
65
66
		$this->layout = 'wadmin';
67
68
		$vendas = $this->Venda->find('all',
69
			array('conditions' =>
70
				array(
71
					'Venda.ativo' => 1,
72
					'Venda.id_usuario' => $this->instancia,
73
					'Venda.orcamento' => 0
74
				)
75
			)
76
		);
77
78
		foreach ($vendas as $i => $venda) {
79
			$lancamento = $this->LancamentoVenda->find('first', array('conditions' => array('LancamentoVenda.venda_id' => $venda['Venda']['id'])));
80
81
			$vendas[$i]['Lancamento'] = (isset($lancamento['LancamentoVenda'])) ? $lancamento['LancamentoVenda'] : array();
82
		}
83
84
		$this->set('vendas', $vendas);
85
	}
86
87
	public function adicionar_cadastro() {
88
		$this->layout = 'wadmin';
89
90
		$this->loadModel('Cliente');
91
92
		$this->set('clientes', $this->Cliente->find('all',
93
				array('conditions' =>
94
					array('ativo' => 1,
95
						  'id_usuario' => $this->instancia
96
					)
97
				)
98
			)
99
		);
100
101
		$this->loadModel('Produto');
102
103
		$this->set('produtos', $this->Produto->find('all',
104
				array('conditions' =>
105
					array('ativo' => 1,
106
						  'id_usuario' => $this->instancia
107
					)
108
				)
109
			)
110
		);
111
112
		$this->set('vendaId', $this->Session->read('UltimoIdVendaSalvo'));
113
	}
114
115
	public function conveter_venda($vendaId) {
116
		$this->layout = 'wadmin';
117
118
		$this->loadModel('Cliente');
119
		
120
		$this->set('clientes', $this->Cliente->find('all',
121
				array('conditions' =>
122
					array('ativo' => 1,
123
						  'id_usuario' => $this->instancia
124
					)
125
				)
126
			)
127
		);
128
129
		$this->loadModel('Produto');
130
131
		$this->set('produtos', $this->Produto->find('all',
132
				array('conditions' =>
133
					array('ativo' => 1,
134
						  'id_usuario' => $this->instancia
135
					)
136
				)
137
			)
138
		);
139
140
		$this->set('venda', $this->Venda->find('all', 
141
				array('conditions' =>
142
					array(
143
						'Venda.ativo' => 1,
144
						'Venda.id' => $vendaId,
145
						'id_usuario' => $this->instancia
146
					)
147
				)
148
			)
149
		);
150
151
		$this->loadModel('VendaItensProduto');
152
153
		$venda_produtos = $this->VendaItensProduto->find('all', 
154
			array('conditions' => 
155
				array(
156
					'VendaItensProduto.ativo' => 1,
157
					'VendaItensProduto.id' => $vendaId
158
				)
159
			)
160
		);
161
162
		$this->loadModel('Produto');
163
164
		$produtos = [];
165
		foreach ($venda_produtos as $i => $venda_produto) 
166
		{
167
			$produto = $this->Produto->find('all',
168
				array('conditions' =>	
169
					array(
170
						'Produto.ativo' => 1,
171
						'Produto.id' => $venda_produto['VendaItensProduto']['produto_id']
172
					)
173
				)
174
			);
175
176 View Code Duplication
			if ($produto[0]['Produto']['estoque'] <= 0)
177
			{
178
				$this->Session->setFlash('O produto (' . $produto[0]['Produto']['nome'] .') não tem mais estoque disponivel!');
179
				continue;
180
			}
181
			
182
			$produtos[$i] = $produto[0]['Produto'];
183
			$produtos[$i]['quantidade'] = $venda_produto['VendaItensProduto']['quantidade_produto'];
184
185
			$total = $produtos[$i]['preco'] * $venda_produto['VendaItensProduto']['quantidade_produto'];
186
187
			$produtos[$i]['preco'] = number_format($produtos[$i]['preco'], 2, ',', '.');
188
			$produtos[$i]['total'] = number_format($total, 2, ',', '.');
189
		}
190
191
		$this->set('venda_produtos', $produtos);
192
	}
193
194
	public function s_adicionar_cadastro() {
195
		$dados_venda 	  = $this->request->data('venda');
196
		$dados_lancamento = $this->request->data('lancamento');
197
		$produtos 	      = $this->request->data('produto');
198
199
		if (!$this->validar_itens_venda($produtos) && !$dados_venda['orcamento']) {
200
			$this->Session->setFlash('Algum produto adicionado não possui estoque disponivel');
201
			$this->redirect('/venda/adicionar_cadastro');
202
		}
203
204
		$dados_venda['valor'] = $this->calcular_valor_venda($produtos);
205
		$dados_venda['custo'] = $this->calcular_custo_venda($produtos);
206
		
207
		$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...
208
		
209
		if (!$salvar_venda) {
210
			$this->Session->setFlash('Ocorreu um erro ao salvar a venda tente novamento');
211
			$this->redirect('/venda/adicionar_cadastro');
212
		}
213
214
		$this->Session->write('UltimoIdVendaSalvo', $salvar_venda['id']);
215
		
216
		$this->Session->setFlash('Venda salva com sucesso');
217
		$this->redirect('/venda/adicionar_cadastro');
218
	}
219
220 View Code Duplication
	public function calcular_valor_venda($produtos) {
221
		$this->loadModel('Produto');
222
223
		(float) $preco = 0.00;
224
		foreach ($produtos as $indice => $item) {
225
			$produto = $this->Produto->find('all',
226
				array('conditions' =>
227
					array('Produto.id' => $item['id_produto'])
228
				)
229
			);
230
231
			$preco += $produto[0]['Produto']['preco'] * $item['quantidade'];
232
		}
233
234
		return $preco;
235
	}
236
237 View Code Duplication
	public function calcular_custo_venda($produtos) {
238
		$this->loadModel('Produto');
239
240
		(float) $custo = 0.00;
241
		foreach ($produtos as $indice => $item) {
242
			$produto = $this->Produto->find('all',
243
				array('conditions' =>
244
					array('Produto.id' => $item['id_produto'])
245
				)
246
			);
247
248
			$custo += $produto[0]['Produto']['custo'] * $item['quantidade'];
249
		}
250
251
		return $custo;
252
	}
253
254
	public function validar_itens_venda($produtos) {
255
		$this->loadModel('Produto');
256
257
		foreach ($produtos as $indice => $item) {
258
			$produto = $this->Produto->find('all',
259
				array('conditions' =>
260
					array('Produto.id' => $item['id_produto'])
261
				)
262
			);
263
264
			$objProdutoEstoqueController = new ProdutoEstoqueController();
265
266
			if (!$objProdutoEstoqueController->validar_estoque($produto, $item['quantidade'])) {
267
				return false;
268
			}			
269
		}
270
271
		return true;
272
	}
273
274
	public function salvar_venda($produtos, $lancamento, $informacoes, $usuario_id) {
275
		unset($informacoes['id_cliente']);
276
277
		$informacoes['data_venda'] = date('Y-m-d');
278
		$informacoes['id_usuario'] = $this->instancia != 'winners' ? $this->instancia : $usuario_id;
279
		$informacoes['ativo']	   = 1;
280
		$informacoes['desconto']   = (float) $informacoes['desconto'];
281
		$informacoes['valor']	   = $informacoes['valor'] - $informacoes['desconto'];
282
		$informacoes['orcamento']  = $informacoes['orcamento'];
283
284
		if (!$this->Venda->save($informacoes)) {
285
			$this->Session->setFlash('Ocorreu algum erro ao salvar a venda');
286
			return false;
287
		}
288
		
289
		$id_venda = $this->Venda->getLastInsertId();
290
291
		$objVendaItensProdutoController = new VendaItensProdutoController();
292
293
		if ($objVendaItensProdutoController->adicionar_itens_venda($id_venda, $produtos, $informacoes['orcamento']) === false) {
294
			return false;
295
		}
296
297
		$objLancamentoVendasController = new LancamentoVendasController();
298
299
		if ($objLancamentoVendasController->salvar_lancamento($id_venda, $lancamento, $informacoes['valor'], $informacoes['id_usuario']) === false) {
300
			return false;
301
		}
302
303
		return array('status' => true, 'id' => $id_venda);
304
	}
305
306
	public function relatorio_diario() {
307
		include(APP . 'Vendor/PHPExcel/PHPExcel.php');
308
		include(APP . 'Vendor/PHPExcel/PHPExcel/IOFactory.php');
309
310
        $objPHPExcel = new PHPExcel();
311
        // Definimos o estilo da fonte
312
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
313
314
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
315
316
        // Criamos as colunas
317
        $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...
318
                    ->setCellValue('A1', "Valor Venda")
319
                    ->setCellValue('B1', "Custo Médio ")
320
                    ->setCellValue("C1", "Valor Lucro")
321
                    ->setCellValue('D1', "ID Venda" );
322
323
324
        $vendas = $this->Venda->find('all',
325
        	array('conditions' => array(
326
        			'AND' => array(
327
        				'Venda.ativo' => 1,
328
        				'Venda.id_usuario' => $this->instancia,
329
        				'Venda.data_venda' => date('Y-m-d')
330
        			)
331
        		)
332
        	)
333
        );
334
335
        $i = 2;
336
        foreach ($vendas as $key => $venda) {
337
        	$objPHPExcel->setActiveSheetIndex(0)
338
        				->setCellValue('A'.$i, 'R$ ' . $venda['Venda']['valor'])
339
        				->setCellValue('B'.$i, 'R$ ' . $venda['Venda']['custo'])
340
        				->setCellValue('C'.$i, 'R$ ' . $venda['Venda']['valor'] - $venda['Venda']['custo'])
341
        				->setCellValue('D'.$i, $venda['Venda']['id']);
342
        	$i++;
343
        }
344
345
        // Podemos renomear o nome das planilha atual, lembrando que um único arquivo pode ter várias planilhas
346
        $objPHPExcel->getActiveSheet()->setTitle('Listagem de vendas');
347
348
        // Cabeçalho do arquivo para ele baixar
349
        header('Content-Type: application/vnd.ms-excel');
350
        header('Content-Disposition: attachment;filename="relatorio_vendas_'.date('d-m-Y').'.xls"');
351
        header('Cache-Control: max-age=0');
352
        // Se for o IE9, isso talvez seja necessário
353
        header('Cache-Control: max-age=1');
354
355
        // Acessamos o 'Writer' para poder salvar o arquivo
356
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
357
358
        // Salva diretamente no output, poderíamos mudar arqui para um nome de arquivo em um diretório ,caso não quisessemos jogar na tela
359
        $objWriter->save('php://output'); 
360
361
        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...
362
	}
363
364
	public function recoverDataToDashboardOneWeek($id_usuario){
365
		$vendas = $this->Venda->find('all',
366
			array('conditions' =>
367
				array(
368
					'Venda.ativo' => 1,
369
					'Venda.id_usuario' => $id_usuario,
370
				),
371
				'limit' => 6
372
			)
373
		);
374
		
375
		$resposta = [];
376
		foreach ($vendas as $i => $venda) {
377
			$resposta[] = (float) number_format($venda['Venda']['valor'], 2, '.', ',');
378
		}
379
380
		$resposta = [
381
			'name' => 'Valor',
382
			'data' => $resposta
383
		];
384
385
		return json_encode($resposta);
386
	}
387
388 View Code Duplication
	public function excluir_cadastro() {
389
		$this->layout = 'ajax';
390
391
		$id = $this->request->data('id');
392
393
		$dados = array('ativo' => '0');
394
		$parametros = array('id' => $id);
395
396
		if ($this->Venda->updateAll($dados, $parametros)) {
397
			echo json_encode(true);
398
		} else {
399
			echo json_encode(false);
400
		}
401
	}
402
403
	public function imprimir_nota_nao_fiscal($id) {
404
		$this->loadModel('LancamentoVenda');
405
		$this->loadModel('VendaItensProduto');
406
		$this->loadModel('Produto');
407
		$this->loadModel('Usuario');
408
409
		$ImpressaoFiscalController = new ImpressaoFiscalController;
410
411
		$dados_venda = $this->Venda->find('first',
412
			array('conditions' =>
413
				array(
414
					'Venda.ativo' => 1,
415
					'Venda.id' => $id
416
				)
417
			)
418
		);
419
420
		$usuario = $this->Usuario->find('first',
421
			array('conditions' =>
422
				array(
423
					'Usuario.id' => $dados_venda['Venda']['id_usuario']
424
				)
425
			)
426
		);
427
		
428
		$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...
429
430
		$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...
431
		
432
		$dados_lancamento = $this->LancamentoVenda->find('first',
433
			array('conditions' => 
434
				array(
435
					'LancamentoVenda.ativo' => 1,
436
					'LancamentoVenda.venda_id' => $id
437
				)
438
			)
439
		);
440
441
		$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...
442
		
443
		$produtos = $this->VendaItensProduto->find('all', 
444
			array('conditions' =>
445
				array(
446
					'VendaItensProduto.venda_id' => $id
447
				)
448
			)
449
		);
450
451
		$itens = array();
452
		foreach ($produtos as $i => $item) {
453
			$produto = $this->Produto->find('first',
454
				array('conditions' =>
455
					array('Produto.id' => $item['VendaItensProduto']['produto_id'])
456
				)
457
			);	
458
459
			$total = $produto['Produto']['preco'] * $item['VendaItensProduto']['quantidade_produto'];
460
461
			$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...
462
						   . "Produto: " . $produto['Produto']['nome']
463
						   . "\nQuantidade: " . $item['VendaItensProduto']['quantidade_produto'] 
464
						   . "\nPreço: R$ " . number_format($produto['Produto']['preco'], 2, ',', '.')
465
						   . "\nTotal: R$ " . number_format($total, 2, ',', '.')
466
						   . "\n--------------------------\n";
467
		}
468
469
		$file = $ImpressaoFiscalController->gerar_arquivo();
470
		
471
		echo json_encode(array('file' => $file));
472
473
		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...
474
	}
475
476
	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...
477
	{
478
		$this->Session->write('UltimoIdVendaSalvo', null);
479
	}
480
481
	public function relatorio() {
0 ignored issues
show
Coding Style introduced by
relatorio 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...
482
		$this->layout = 'wadmin';
483
484
		$from = $_GET['from'];
485
		$to   = $_GET['to'];
486
487
		$this->loadModel('Venda');
488
		$this->loadModel('LancamentoVenda');
489
490
		$conditions = array(
491
			'conditions' => array(
492
				'Venda.id_usuario' => $this->instancia,
493
				'Venda.data_venda >=' => $from,
494
				'Venda.data_venda <=' => $to,
495
				'Venda.orcamento <>' => 1
496
			)
497
		);
498
499
		$vendas = $this->Venda->find('all', $conditions);
500
501
		$valorTotalVendasPeriodo = $this->calcularValorTotalVendas($vendas);
502
503
		$totalCustoPeriodo = $this->calcularTotalCustoProdutosPeriodo($vendas);
504
505
		$lancamentos = array();
506
507
		foreach ($vendas as $i => $venda) {
508
			$lancamento =  $this->LancamentoVenda->find('first', array(
509
					'conditions' => array(
510
						'LancamentoVenda.venda_id' => $venda['Venda']['id']
511
					)
512
				)
513
			);
514
515
			if (!empty($lancamento))
516
				$lancamentos[] = $lancamento;
517
		}
518
519
		$valorTotalPgt = $this->calcularTotalVendas($lancamentos);
520
521
		$this->set('dinheiro', $valorTotalPgt['dinheiro']);
522
		$this->set('cartao_credito', $valorTotalPgt['cartao_credito']);
523
		$this->set('cartao_debito', $valorTotalPgt['cartao_debito']);
524
		$this->set('valorTotalVendasPeriodo', $valorTotalVendasPeriodo);
525
		$this->set('totalCustoPeriodo', $totalCustoPeriodo);
526
		$this->set('totalLucro', $valorTotalVendasPeriodo - $totalCustoPeriodo);
527
	}
528
529
	public function calcularTotalVendas($lancamentos)
530
	{
531
		$response = array();
532
		foreach ($lancamentos as $i => $lancamento) {
533
			@$response[$lancamento['LancamentoVenda']['forma_pagamento']] += $lancamento['LancamentoVenda']['valor_pago'];
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
534
		}
535
536
		return $response;
537
	}
538
539 View Code Duplication
	public function calcularTotalCustoProdutosPeriodo($vendas)
540
	{
541
		$valor = 0.00;
542
543
		foreach ($vendas as $i => $venda) {
544
			$valor += $venda['Venda']['custo'];
545
		}
546
547
		return $valor;
548
	}
549
550 View Code Duplication
	public function calcularValorTotalVendas($vendas)
551
	{
552
		$valor = 0.00;
553
554
		foreach ($vendas as $i => $venda) {
555
			$valor += $venda['Venda']['valor'];
556
		}
557
558
		return $valor;
559
	}
560
561
}
562