Completed
Push — master ( 76fc12...b1e5fa )
by Reginaldo
40:11 queued 20:37
created

FinanceiroController::adicionar_categoria()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 11

Duplication

Lines 19
Ratio 100 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 0
dl 19
loc 19
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
class FinanceiroController extends AppController 
4
{
5
6
	public function listar_cadastros()
7
	{
8
		$this->loadModel('LancamentoVenda');
9
10
		$this->layout = 'wadmin';
11
12
		$this->set('lancamentos', $this->carregar_lancamentos_periodo());
13
	}
14
15
	public function carregar_lancamentos_periodo()
16
	{
17
		$this->loadModel('LancamentoVenda');
18
		$this->loadModel('LancamentoCategoria');
19
20
		$conditions = array('conditions' =>
21
			array(
22
				'LancamentoVenda.ativo' => 1,
23
				'LancamentoVenda.usuario_id' => $this->instancia
24
			),
25
		);
26
27
		$lancamentos = $this->LancamentoVenda->find('all', $conditions);
28
		
29
		$a_receber = 0;
30
		$a_pagar = 0;
31
		$pago = 0;
32
		$total = 0;
33
		$total_entradas = 0;
34
		$total_saidas = 0;
35
		foreach ($lancamentos as $i => $lancamento)
36
		{
37
			$categoria = $this->LancamentoCategoria->find('first', array('conditions' =>
38
					array(
39
						'LancamentoCategoria.ativo' => 1,
40
						'LancamentoCategoria.usuario_id' => $this->instancia,
41
						'LancamentoCategoria.id' => $lancamento['LancamentoVenda']['lancamento_categoria_id']
42
					)
43
				)
44
			);
45
46
			$lancamentos[$i]['Categoria'] = isset($categoria['LancamentoCategoria']) ? $categoria['LancamentoCategoria'] : array();
47
48
			if (empty($categoria) || $categoria['LancamentoCategoria']['tipo'] == "receita") {
49 View Code Duplication
				if ($lancamento['LancamentoVenda']['valor'] > $lancamento['LancamentoVenda']['valor_pago']) {
50
					$a_receber += $lancamento['LancamentoVenda']['valor'] - $lancamento['LancamentoVenda']['valor_pago'];
51
				}
52
53
				if ($lancamento['LancamentoVenda']['valor'] >= $lancamento['LancamentoVenda']['valor_pago']) {
54
					$total_entradas += $lancamento['LancamentoVenda']['valor'];
55
				}
56
			}
57
58
			if (empty($categoria))
59
				continue;
60
61
			if ($categoria['LancamentoCategoria']['tipo'] == "despesa") {
62
				if ($lancamento['LancamentoVenda']['valor'] > $lancamento['LancamentoVenda']['valor_pago']) {
63
					$a_pagar += $lancamento['LancamentoVenda']['valor'] - $lancamento['LancamentoVenda']['valor_pago'];
64
				} else {
65
					$pago += $lancamento['LancamentoVenda']['valor'];
66
					$total_saidas += $lancamento['LancamentoVenda']['valor'];
67
				}
68
			}
69
70
		}
71
		
72
		$data = [
73
			'lancamentos' => $lancamentos,
74
			'a_receber' => $a_receber,
75
			'a_pagar' => $a_pagar,
76
			'pago' => $pago,
77
			'total' => $total_entradas,
78
			'total_saidas' => $total_saidas
79
		];
80
81
		return $data;
82
	}
83
84 View Code Duplication
	public function carregar_categorias($id = null)
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...
85
	{
86
		$this->loadModel('LancamentoCategoria');
87
88
		$filter = $this->request->query('term');
89
90
		$conditions = array('conditions' => array(
91
				'LancamentoCategoria.usuario_id' => $this->instancia,
92
				'LancamentoCategoria.ativo' => 1
93
			)
94
		);
95
96
		if (!empty($filter['term'])) {
97
			$conditions['conditions']['LancamentoCategoria.nome LIKE '] = '%' . $filter['term'] . '%';
98
		}
99
100
		$conditions['limit'] = $this->request->query('page_limit');
101
102
		$categorias = $this->LancamentoCategoria->find('all', $conditions);
103
104
		$response = [];
105
106
		$response['results'][0]['id'] = -1;
107
		$response['results'][0]['text'] = 'Todos';
108
109
		$response['results'][1]['id'] = 0;
110
		$response['results'][1]['text'] = 'Sem categoria';
111
112
		$i = 1;
113
		foreach ($categorias as $categoria) {
114
			$i++; 
115
116
			$response['results'][$i]['id'] = $categoria['LancamentoCategoria']['id'];
117
			$response['results'][$i]['text'] = $categoria['LancamentoCategoria']['nome'];
118
		}
119
120
		echo json_encode($response);
121
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method carregar_categorias() 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...
122
	}
123
124 View Code Duplication
	public function carregar_fornecedores($id = null)
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...
125
	{
126
		$this->loadModel('Fornecedore');
127
128
		$filter = $this->request->query('term');
129
130
		$conditions = array('conditions' => array(
131
				'Fornecedore.usuario_id' => $this->instancia,
132
				'Fornecedore.ativo' => 1
133
			)
134
		);
135
136
		if (!empty($filter['term'])) {
137
			$conditions['conditions']['Fornecedore.nome LIKE '] = '%' . $filter['term'] . '%';
138
		}
139
140
		$conditions['limit'] = $this->request->query('page_limit');
141
142
		$fornecedores = $this->Fornecedore->find('all', $conditions);
143
144
		$response = [];
145
146
		$response['results'][0]['id'] = -1;
147
		$response['results'][0]['text'] = 'Todos';
148
149
		$response['results'][1]['id'] = 0;
150
		$response['results'][1]['text'] = 'Sem Fornecedor';
151
152
		$i = 1;
153
		foreach ($fornecedores as $fornecedor) {
154
			$i++; 
155
156
			$response['results'][$i]['id'] = $fornecedor['Fornecedore']['id'];
157
			$response['results'][$i]['text'] = $fornecedor['Fornecedore']['nome'];
158
		}
159
160
		echo json_encode($response);
161
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method carregar_fornecedores() 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...
162
	}
163
164
	public function listar_cadastros_ajax()
0 ignored issues
show
Coding Style introduced by
listar_cadastros_ajax 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...
165
	{
166
		$this->layout = 'ajax';
167
168
		$this->loadModel('LancamentoVenda');
169
		$this->loadModel('LancamentoCategoria');
170
171
		$aColumns = array( 'id', 'venda_id', 'data_vencimento', 'valor', 'lancamento_categoria_id' );
172
173
		$conditions = array(
174
			'conditions' => array(
175
				'LancamentoVenda.ativo' => 1,
176
				'LancamentoVenda.usuario_id' => $this->instancia
177
			),
178
			'joins' => array(
179
			    array(
180
			        'table' => 'lancamento_categorias',
181
			        'alias' => 'LancamentoCategoria',
182
			        'type' => 'LEFT',
183
			        'conditions' => array(
184
			            'LancamentoVenda.lancamento_categoria_id = LancamentoCategoria.id',
185
			        ),
186
			    ),
187
			    array(
188
			        'table' => 'fornecedores',
189
			        'alias' => 'Fornecedore',
190
			        'type' => 'LEFT',
191
			        'conditions' => array(
192
			            'LancamentoVenda.fornecedore_id = Fornecedore.id',
193
			        ),
194
			    )
195
			),
196
			'fields' => array(
197
				'LancamentoCategoria.*', 'LancamentoVenda.*', 'Fornecedore.*'
198
			)
199
		);
200
201 View Code Duplication
		if ( isset( $_GET['iSortCol_0'] ) )
202
		{
203
			for ( $i=0 ; $i < intval( $_GET['iSortingCols'] ) ; $i++ )
204
			{
205
				if ( $_GET[ 'bSortable_' . intval($_GET['iSortCol_' . $i]) ] == "true" )
206
				{
207
					$conditions['order'] = array(
208
						'LancamentoVenda.' . $aColumns[intval($_GET['iSortCol_' . $i])] => $_GET['sSortDir_' . $i]);
209
				}
210
			}
211
		}
212
		
213
		if ( isset( $_GET['sSearch'] ) && !empty( $_GET['sSearch'] ) )
214
		{
215
			$search = explode(':', $_GET['sSearch']);
216
217
			if ($search[0] == "lancamento_categoria_id" && $search[1] != -1) {
218
				$conditions['conditions']['LancamentoCategoria.id'] = empty($search[1]) ? "" : $search[1];
219
			}
220
221
			if ($search[0] == "tipo" && $search[1] != -1) {
222
				$conditions['conditions']['LancamentoCategoria.tipo'] = $search[1];
223
			}
224
225
			if ($search[0] == "pagamento" && $search[1] != -1) {
226
				$conditions['conditions']['LancamentoVenda.data_pgt'] = $search[1];
227
			}
228
229
			if ($search[0] == "fornecedor" && $search[1] != -1) {
230
				$conditions['conditions']['Fornecedore.id'] = $search[1];
231
			}
232
		}
233
		// pr($conditions);
234
		$allLancamentos = $this->LancamentoVenda->find('count', $conditions);
235
236 View Code Duplication
		if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
237
		{
238
			$conditions['offset'] = $_GET['iDisplayStart'];
239
			$conditions['limit'] = $_GET['iDisplayLength'];
240
		}
241
242
		$lancamentos = $this->LancamentoVenda->find('all', $conditions);
243
		// pr($lancamentos,1);
244
		$output = array(
245
			"sEcho" => intval($_GET['sEcho']),
246
			"iTotalDisplayRecords" => $allLancamentos,
247
			"iTotalRecords" => count($lancamentos),
248
			"aaData" => array()
249
		);
250
251
		foreach ( $lancamentos as $i => $lancamento )
252
		{
253
			$row = array();
254
255
			$btPaid = '';
256
			for ( $i=0 ; $i < count($aColumns) ; $i++ )
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
257
			{
258
				if ($aColumns[$i] == "lancamento_categoria_id") {
259
260
					$conditions = array('conditions' =>
261
						array(
262
							'LancamentoCategoria.id' => $lancamento['LancamentoVenda'][$aColumns[$i]],
263
							'LancamentoCategoria.usuario_id' => $this->instancia,
264
							'LancamentoCategoria.ativo' => 1
265
						)
266
					);
267
268
					$categoria_lancamento = $this->LancamentoCategoria->find('first', $conditions);
269
270
					if (!empty($categoria_lancamento)) {
271
						if ($categoria_lancamento['LancamentoCategoria']['tipo'] == "receita") {
272
							$value = '<span class="label label-success">' . $categoria_lancamento['LancamentoCategoria']['nome'] . '</span>';
273
274
							$btPaid = '<a class="btn btn-primary" href="javascript:alert(\'Não é uma despesa.\');"><i class="fa fa-child"></i></a>';
275
						} else {
276
							$value = '<span class="label label-danger">' . $categoria_lancamento['LancamentoCategoria']['nome'] . '</span>';
277
278
							if ($lancamento['LancamentoVenda']['valor_pago'] < $lancamento['LancamentoVenda']['valor']) {
279
								$btPaid = '<a class="btn btn-success" href="/produto/imagens/' . $lancamento['LancamentoVenda']['id'] . '"><i class="fa fa-check"></i></a>';
280
							} else {
281
								$btPaid = '<a class="btn btn-default" href="javascript:alert(\'Lançamento já foi pago\');"><i class="fa fa-money"></i></a>';
282
							}
283
						}
284
					} else {
285
						$value = '<span class="label label-default">Sem Categoria</span>';
286
					}
287
288
				} else {
289
					$value = $lancamento['LancamentoVenda'][$aColumns[$i]];
290
				}
291
292
				if ($aColumns[$i] == "venda_id" && empty($lancamento['LancamentoVenda'][$aColumns[$i]])) {
293
					$value = '<b>Não é uma venda</b>';
294
				} elseif ($aColumns[$i] == "venda_id" && !empty($lancamento['LancamentoVenda'][$aColumns[$i]])) {
295
					$value = '<a href="http://www.ciawn.com.br/venda/listar_cadastros?venda_id=' . $lancamento['LancamentoVenda'][$aColumns[$i]] . '">Ver Pedido</a>';
296
				}
297
298
				if ($aColumns[$i] == "valor") {
299
					$value = 'R$ ' . number_format($lancamento['LancamentoVenda'][$aColumns[$i]], 2, ',', '.');
300
				}
301
302
				if ($aColumns[$i] == "data_vencimento" && $lancamento['LancamentoVenda'][$aColumns[$i]] != "") {
303
					$date = new \DateTime($lancamento['LancamentoVenda'][$aColumns[$i]]);
304
					$value = $date->format('d/m/Y');
305
				} else if ($aColumns[$i] == "data_vencimento" && empty($lancamento['LancamentoVenda'][$aColumns[$i]])) {
306
					$value = "Não informado";
307
				}
308
				
309
				$row[] = $value;
310
			}
311
312
			$row[] = isset($btPaid) ? $btPaid : '';
313
314
			$output['aaData'][] = $row;
315
		}
316
317
		echo json_encode($output);
318
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method listar_cadastros_ajax() 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...
319
	}
320
321 View Code Duplication
	public function adicionar_categoria()
322
	{
323
		$data = $this->request->data('categoria');
324
325
		$data['usuario_id'] = $this->instancia;
326
		$data['ativo'] = 1;
327
328
		$this->loadModel('LancamentoCategoria');
329
330
		$retorno = $this->LancamentoCategoria->save($data);
331
		
332
		if (!$retorno) {
333
			$this->Session->setFlash('Ocorreu um erro ao salvar a categoria tente novamente');
334
			return $this->redirect('/financeiro/listar_cadastros');
335
		}
336
337
		$this->Session->setFlash('Categoria salva com sucesso');
338
		return $this->redirect('/financeiro/listar_cadastros');
339
	}
340
341 View Code Duplication
	public function adicionar_fornecedor()
342
	{
343
		$data = $this->request->data('fornecedor');
344
345
		$this->loadModel('Fornecedore');
346
347
		$data['usuario_id'] = $this->instancia;
348
		$data['ativo'] = 1;
349
		
350
		if (!$this->Fornecedore->save($data)) {
351
			$this->Session->setFlash('Ocorreu um erro ao inserir o fornecedor');
352
			return $this->redirect('/financeiro/listar_cadastros');
353
		}
354
355
		$this->Session->setFlash('Fornecedor inserido com sucesso!');
356
		return $this->redirect('/financeiro/listar_cadastros');		
357
	}
358
359 View Code Duplication
	public function adicionar_transacao()
360
	{
361
		$transacao = $this->request->data('transacao');
362
363
		$transacao['valor_pago'] = 0;
364
		$transacao['ativo'] = 1;
365
		$transacao['usuario_id'] = $this->instancia;
366
367
		$this->loadModel('LancamentoVenda');
368
369
		if (!$this->LancamentoVenda->save($transacao)) {
370
			$this->Session->setFlash('Ocorreu um erro ao cadastrar o lançamento');
371
			return $this->redirect('/financeiro/listar_cadastros');
372
		}
373
374
		$this->Session->setFlash('Lançamento inserido com sucesso!');
375
		return $this->redirect('/financeiro/listar_cadastros');
376
	}
377
378
}