Completed
Push — master ( 578d73...cb0792 )
by Reginaldo
33:30
created

VendaController::recoverDataToDashboardOneWeek()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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