Completed
Push — master ( 67d6bf...156008 )
by Reginaldo
39:41
created

VendaController::calcular_custo_venda()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 16
Ratio 100 %
Metric Value
dl 16
loc 16
rs 9.4285
cc 2
eloc 9
nc 2
nop 1
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
					)
67
				)
68
			)
69
		);
70
	}
71
72 View Code Duplication
	public function adicionar_cadastro() {
73
		$this->layout = 'wadmin';
74
75
		$this->loadModel('Cliente');
76
77
		$this->set('clientes', $this->Cliente->find('all',
78
				array('conditions' =>
79
					array('ativo' => 1,
80
						  'id_usuario' => $this->instancia
81
					)
82
				)
83
			)
84
		);
85
86
		$this->loadModel('Produto');
87
88
		$this->set('produtos', $this->Produto->find('all',
89
				array('conditions' =>
90
					array('ativo' => 1,
91
						  'id_usuario' => $this->instancia
92
					)
93
				)
94
			)
95
		);
96
	}
97
98
	public function s_adicionar_cadastro() {
99
		$dados_venda 	  = $this->request->data('venda');
100
		$dados_lancamento = $this->request->data('lancamento');
101
		$produtos 	      = $this->request->data('produto');
102
103
		if (!$this->validar_itens_venda($produtos)) {
104
			$this->Session->setFlash('Algum produto adicionado não possui estoque disponivel');
105
			$this->redirect('/venda/adicionar_cadastro');
106
		}
107
108
		$dados_venda['valor'] = $this->calcular_valor_venda($produtos);
109
		$dados_venda['custo'] = $this->calcular_custo_venda($produtos);
110
		
111
		$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...
112
		
113
		if (!$salvar_venda) {
114
			$this->Session->setFlash('Ocorreu um erro ao salvar a venda tente novamento');
115
			$this->redirect('/venda/adicionar_cadastro');
116
		}
117
		
118
		$this->Session->setFlash('Venda salva com sucesso');
119
		$this->redirect('/venda/adicionar_cadastro');
120
	}
121
122 View Code Duplication
	public function calcular_valor_venda($produtos) {
123
		$this->loadModel('Produto');
124
125
		(float) $preco = 0.00;
126
		foreach ($produtos as $indice => $item) {
127
			$produto = $this->Produto->find('all',
128
				array('conditions' =>
129
					array('Produto.id' => $item['id_produto'])
130
				)
131
			);
132
133
			$preco += $produto[0]['Produto']['preco'] * $item['quantidade'];
134
		}
135
136
		return $preco;
137
	}
138
139 View Code Duplication
	public function calcular_custo_venda($produtos) {
140
		$this->loadModel('Produto');
141
142
		(float) $custo = 0.00;
143
		foreach ($produtos as $indice => $item) {
144
			$produto = $this->Produto->find('all',
145
				array('conditions' =>
146
					array('Produto.id' => $item['id_produto'])
147
				)
148
			);
149
150
			$custo += $produto[0]['Produto']['custo'] * $item['quantidade'];
151
		}
152
153
		return $custo;
154
	}
155
156
	public function validar_itens_venda($produtos) {
157
		$this->loadModel('Produto');
158
159
		foreach ($produtos as $indice => $item) {
160
			$produto = $this->Produto->find('all',
161
				array('conditions' =>
162
					array('Produto.id' => $item['id_produto'])
163
				)
164
			);
165
166
			$objProdutoEstoqueController = new ProdutoEstoqueController();
167
168
			if (!$objProdutoEstoqueController->validar_estoque($produto, $item['quantidade'])) {
169
				return false;
170
			}			
171
		}
172
173
		return true;
174
	}
175
176
	public function salvar_venda($produtos, $lancamento, $informacoes, $usuario_id) {
177
		unset($informacoes['id_cliente']);
178
179
		$informacoes['data_venda'] = date('Y-m-d');
180
		$informacoes['id_usuario'] = $this->instancia != 'winners' ? $this->instancia : $usuario_id;
181
		$informacoes['ativo']	   = 1;
182
		$informacoes['desconto']   = (float) $informacoes['desconto'];
183
		$informacoes['valor']	   = $informacoes['valor'] - $informacoes['desconto'];
184
185
		if (!$this->Venda->save($informacoes)) {
186
			$this->Session->setFlash('Ocorreu algum erro ao salvar a venda');
187
			return false;
188
		}
189
		
190
		$id_venda = $this->Venda->getLastInsertId();
191
192
		$objVendaItensProdutoController = new VendaItensProdutoController();
193
		if ($objVendaItensProdutoController->adicionar_itens_venda($id_venda, $produtos) === false) {
194
			return false;
195
		}
196
197
		$objLancamentoVendasController = new LancamentoVendasController();
198
		if ($objLancamentoVendasController->salvar_lancamento($id_venda, $lancamento, $informacoes['valor']) === false) {
199
			return false;
200
		}
201
202
		return array('status' => true, 'id' => $id_venda);
203
	}
204
205
	public function relatorio_diario() {
206
		include(APP . 'Vendor/PHPExcel/PHPExcel.php');
207
		include(APP . 'Vendor/PHPExcel/PHPExcel/IOFactory.php');
208
209
        $objPHPExcel = new PHPExcel();
210
        // Definimos o estilo da fonte
211
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
212
213
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
214
215
        // Criamos as colunas
216
        $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...
217
                    ->setCellValue('A1', "Valor Venda")
218
                    ->setCellValue('B1', "Custo Médio ")
219
                    ->setCellValue("C1", "Valor Lucro")
220
                    ->setCellValue('D1', "ID Venda" );
221
222
223
        $vendas = $this->Venda->find('all',
224
        	array('conditions' => array(
225
        			'AND' => array(
226
        				'Venda.ativo' => 1,
227
        				'Venda.id_usuario' => $this->instancia,
228
        				'Venda.data_venda' => date('Y-m-d')
229
        			)
230
        		)
231
        	)
232
        );
233
234
        $i = 2;
235
        foreach ($vendas as $key => $venda) {
236
        	$objPHPExcel->setActiveSheetIndex(0)
237
        				->setCellValue('A'.$i, 'R$ ' . $venda['Venda']['valor'])
238
        				->setCellValue('B'.$i, 'R$ ' . $venda['Venda']['custo'])
239
        				->setCellValue('C'.$i, 'R$ ' . $venda['Venda']['valor'] - $venda['Venda']['custo'])
240
        				->setCellValue('D'.$i, $venda['Venda']['id']);
241
        	$i++;
242
        }
243
244
        // Podemos renomear o nome das planilha atual, lembrando que um único arquivo pode ter várias planilhas
245
        $objPHPExcel->getActiveSheet()->setTitle('Listagem de vendas');
246
247
        // Cabeçalho do arquivo para ele baixar
248
        header('Content-Type: application/vnd.ms-excel');
249
        header('Content-Disposition: attachment;filename="relatorio_vendas_'.date('d-m-Y').'.xls"');
250
        header('Cache-Control: max-age=0');
251
        // Se for o IE9, isso talvez seja necessário
252
        header('Cache-Control: max-age=1');
253
254
        // Acessamos o 'Writer' para poder salvar o arquivo
255
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
256
257
        // Salva diretamente no output, poderíamos mudar arqui para um nome de arquivo em um diretório ,caso não quisessemos jogar na tela
258
        $objWriter->save('php://output'); 
259
260
        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...
261
	}
262
263
	public function recoverDataToDashboardOneWeek(){
264
		$vendas = $this->Venda->find('all',
265
			array('conditions' =>
266
				array(
267
					'ativo' => 1,
268
					'id_usuario' => $this->instancia,
269
				),
270
				'limit' => 6
271
			)
272
		);
273
274
		$resposta = [];
275
		foreach ($vendas as $i => $venda) {
276
			$resposta[] = (float) number_format($venda['Venda']['valor'], 2, '.', ',');
277
		}
278
279
		$resposta = [
280
			'name' => 'Valor',
281
			'data' => $resposta
282
		];
283
284
		return json_encode($resposta);
285
	}
286
287
}
288