Completed
Push — master ( f57dd5...55db64 )
by Reginaldo
40:24
created

LojaController::paymentPagSeguro()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 19
rs 9.4285
cc 1
eloc 10
nc 1
nop 6
1
<?php
2
3
App::uses('AppController', 'Controller');
4
5
require 'PagamentoController.php';
6
require 'CupomController.php';
7
require 'NewsletterController.php';
8
require 'VendaController.php';
9
10
require_once(ROOT . DS . 'vendor' . DS . 'autoload.php');
11
use FastShipping\Lib\Tracking;
12
use FastShipping\Lib\Shipping;
13
14
class LojaController extends AppController {
15
	public $layout = 'lojaexemplo';	
16
17
	public function beforeFilter(){
18
	   return true;
19
	}
20
21
	public function loadProducts($id_categoria = null, $id_produto = null) {
22
		$this->loadModel('Produto');
23
24
      $params = array('conditions' => 
25
         array(
26
            'Produto.ativo' => 1,
27
            'Produto.id_usuario' => $this->Session->read('Usuario.id')
28
         )
29
      );
30
31
      if ($id_categoria != null) {
32
         $params['conditions']['Produto.categoria_id'] = $id_categoria;
33
      }
34
35
      if ($id_produto != null) {
36
         $params['conditions']['Produto.id'] = $id_produto;
37
      }
38
39
		$produtos = $this->Produto->find('all', $params);
40
41
	   return $produtos;
42
	}
43
44 View Code Duplication
   public function loadBanners($id_banner = null) {
0 ignored issues
show
Unused Code introduced by
The parameter $id_banner 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...
45
      $this->loadModel('Banner');
46
47
      $params = array('conditions' => 
48
         array('ativo' => 1,
49
              'usuario_id' => $this->Session->read('Usuario.id')
50
         )
51
      );
52
53
      $banners = $this->Banner->find('all', $params);
54
55
      return $banners;
56
   } 
57
58
	public function addCart() {
59
		$produto = $this->request->data('produto');
60
		
61
		if (empty($produto)) {
62
			$this->redirect('/');
63
		}
64
65
      if (!$this->validateProduct($produto)) {
66
         $this->Session->setFlash('Quantidade de produtos escolhidas é maior do que a disponivel!');
67
         $this->redirect('/');
68
      }
69
70
		$cont = count($this->Session->read('Produto'));
71
72
		$this->Session->write('Produto.'.$produto['id'].'.id' , $produto['id']);
73
      $this->Session->write('Produto.'.$produto['id'].'.quantidade' , $produto['quantidade']);
74
      $this->Session->write('Produto.'.$produto['id'].'.variacao', $produto['variacao']);
75
76
		$this->redirect('/cart');
77
	}
78
79
   public function removeProductCart() {
80
      if ( ($this->Session->read('Produto.' . $this->params['id'])) !== null ) {
81
         $this->Session->delete( 'Produto.' . $this->params['id'] );
82
      }
83
84
      $this->redirect('/cart');
85
   }
86
87
	public function clearCart() {
88
		$this->Session->delete('Produto');
89
	}
90
91
   public function loadProductsAndValuesCart() {
92
      $this->loadModel('Produto');
93
      $this->loadModel('Variacao');
94
95
      $productsSession = $this->Session->read('Produto');
96
97
      (float) $total = 0.00;
98
      $produtos      = array();
99
      foreach ($productsSession as $indice => $item) {
100
         $produto =  $this->Produto->find('all', 
101
            array('conditions' => 
102
               array('Produto.ativo' => 1,
103
                    'Produto.id' => $item['id']
104
               )
105
            )
106
         );
107
108
         $total     += $produto[0]['Produto']['preco'] * $item['quantidade'];
109
110
         $produto[0]['Produto']['quantidade'] = $item['quantidade'];
111
112
         $variacao = $this->Variacao->find('all', 
113
            array('conditions' =>
114
               array('Variacao.id' => $item['variacao'])
115
            ),
116
            array('fields' => 
117
               array('Variacao.nome_variacao')
118
            )
119
         );
120
121
         $produto[0]['Produto']['variacao'] = $variacao[0]['Variacao']['nome_variacao'];
122
123
         $produtos[] = $produto[0];
124
      }
125
126
      return array('products_cart' => $produtos, 'total' => $total);
127
   }
128
129 View Code Duplication
   public function loadCategoriesProducts($id_categoria = null) {
0 ignored issues
show
Unused Code introduced by
The parameter $id_categoria 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...
130
      $this->loadModel('Categoria');
131
132
      $params = array('conditions' => 
133
         array('ativo' => 1,
134
              'usuario_id' => $this->Session->read('Usuario.id')
135
         )
136
      );
137
138
      $categorias = $this->Categoria->find('all', $params);
139
140
      return $categorias;
141
   }
142
143
   public function payment() {
144
      $andress = $this->request->data('endereco');
145
     
146
      $client  = $this->request->data('cliente');
147
148
      $products = $this->loadProductsAndValuesCart();
149
150
      (float) $valor_frete = number_format($this->Session->read('Frete.valor'), 2, '.', ',');
151
152
      $objVenda = new VendaController();
153
     
154
      $productsSale = $this->prepareProductsSale($products['products_cart']);
155
     
156
      $usuario_id = $this->Session->read('Usuario.id');
157
158
      $retorno_venda = $objVenda->salvar_venda($productsSale, array('forma_pagamento' => 'pagseguro'), array('valor' => $valor_frete + $products['total']), $usuario_id);
159
      
160
      $this->paymentPagSeguro($products['products_cart'], $andress, $client, $products['total'], $valor_frete, $retorno_venda['id']);
161
   }
162
163
   public function paymentPagSeguro($products, $andress, $client, $total, $shipping, $id) {
0 ignored issues
show
Unused Code introduced by
The parameter $client 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...
Unused Code introduced by
The parameter $total 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...
164
      $pagamento = new PagamentoController('PagseguroController');   
165
166
      $pagamento->setToken('0C063416737542A28219A50736AD363E');
167
      
168
      $pagamento->setEmail('[email protected]');
169
170
      $pagamento->setProdutos($products);
171
      
172
      $pagamento->adicionarProdutosGateway();
173
174
      $pagamento->setEndereco($andress);
175
176
      $pagamento->setReference('#' . $id);
177
      
178
      $pagamento->setValorFrete($shipping);
179
180
      return $this->redirect($pagamento->finalizarPedido());
181
   }
182
183
   public function prepareProductsSale($products) {
184
      $retorno = array();
185
     
186
      foreach ($products as $i => $product) {
187
         $retorno[$i]['id_produto'] = $product['Produto']['id'];
188
         $retorno[$i]['quantidade'] = $product['Produto']['quantidade'];
189
         $retorno[$i]['variacao']   = $product['Produto']['variacao'];
190
      }
191
192
      return $retorno;
193
   }
194
195
   public function searchAndressByCep($cep) {
196
      $this->layout = 'ajax';
197
198
      $curl = curl_init('http://cep.correiocontrol.com.br/'.$cep.'.js');
199
200
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
201
      $resultado = curl_exec($curl);
202
203
      echo $resultado;
204
      exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method searchAndressByCep() 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...
205
   }
206
207
   public function calcTransportAjax() {
208
      $this->layout = 'ajax';
209
210
      $cep_destino = $this->request->data('cep_destino');
211
      $cep_origem  = $this->request->data('cep_origem');
212
213
      $dataProducts = $this->loadProductsAndValuesCart();
214
      $fretes = $this->transport($cep_destino, $cep_origem, $dataProducts['products_cart']);
215
216
      $disponiveis = array();
217
      $cont = 0;
218
      foreach ($fretes as $i => $frete) {
219
         $disponiveis[$cont]['valor']  = $frete->price;
220
         $disponiveis[$cont]['prazo']  = $frete->estimate;
221
         $disponiveis[$cont]['codigo'] = $frete->method;
222
         $cont++;
223
      }
224
225
      $this->Session->write('Frete.valor', $disponiveis[$cont - 1]['valor']);
226
227
      (float) $total = $disponiveis[$cont - 1]['valor'] + $dataProducts['total'];
228
      $total = number_format($total, 2, ',', '.');
229
230
      $retorno = array('frete' => $disponiveis[$cont - 1]['valor'], 'total' => $total);
231
232
      echo json_encode($retorno);   
233
      exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method calcTransportAjax() 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...
234
   }
235
   
236
   public function transport($cep_destino, $cep_origem, $data) {
237
      $products = [];
238
      foreach ($data as $key => $item) {
239
         $products[] = [
240
           "weight" => (float) $item['Produto']['peso_bruto'],
241
           "height" => (float) '',
242
           "length" =>(float)  '',
243
           "width" => (float) '',
244
           "unit_price" => (float) $item['Produto']['preco'],
245
           "quantity" => (integer) $item['Produto']['quantidade'],
246
           "sku" => $item['Produto']['id_alias'],
247
           "id" => $item['Produto']['id']
248
         ];
249
      }
250
251
      $shipping = new Shipping(
252
          (string) $cep_destino,
253
          'BR',
254
          'GUARULHOS',
255
          (string) $cep_origem,
256
          '',
257
          '',
258
          '',
259
          $products
260
      );
261
262
      $response = $shipping->getPricesShipping();
263
264
      return $response;
265
   }
266
267
   public function saveEmailNewsletter() {
268
      $nome  = $this->request->data('nome');
269
      $email = $this->request->data('email');
270
271
      $objNewsletter = new NewsletterController();
272
273
      if ($objNewsletter->newsletter_cadastro($nome, $email, $this->Session->read('Usuario.id')))
274
      {
275
         echo json_encode(true);
276
         exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method saveEmailNewsletter() 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...
277
      } 
278
279
      echo json_encode(false);
280
      exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method saveEmailNewsletter() 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...
281
   }
282
283
   public function useCoupon() {
284
      $this->layout = 'ajax';
285
286
      $cupom = $this->request->data('cupom');
287
      $valor  = $this->request->data('valor');
288
         
289
      $objCupom = new CupomController();
290
      $novo_valor = $objCupom->utilizar_cupom($cupom, $valor, $this->Session->read('Usuario.id'));
291
292
      if (!$novo_valor)
293
      {
294
         echo json_encode(false);
295
         exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method useCoupon() 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...
296
      }
297
298
      echo json_encode($novo_valor);
299
      exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method useCoupon() 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...
300
   }
301
302
   public function validateProduct($data) {
303
      $this->loadModel('Variacao');
304
305
      $params = array('conditions' => 
306
         array(
307
            'Variacao.id' => $data['variacao']
308
         )
309
      );
310
311
      $variacao = $this->Variacao->find('all', $params);
312
313
      if ($variacao[0]['Variacao']['estoque'] <= 0 || $data['quantidade'] > $variacao[0]['Variacao']['estoque'])
314
      {
315
         return false;
316
      }
317
318
      return true;   
319
   }
320
321
   public function saveClientFromEcommerce($data) {
322
      $this->loadModel('Cliente');
323
324
      $data['senha'] = sha1($data['senha']);
325
326
      $this->Cliente->set($data);
327
328
      if (!$this->Cliente->validates())
329
      {
330
         return false;
331
      }
332
333
      if (!$this->Cliente->save())
334
      {
335
         return false;
336
      }
337
338
      return $this->Cliente->getLastInsertId();
339
   }
340
341
   public function saveAndressClientFromEcommerce($data) {
342
      $this->loadModel('EnderecoClienteCadastro');
343
344
      $this->EnderecoClienteCadastro->set($data);
345
346
      if (!$this->EnderecoClienteCadastro->validates())
347
      {
348
         return false;
349
      }
350
351
      return $this->EnderecoClienteCadastro->save();
352
   }
353
354
	/**
355
	* Views
356
	*/
357
	public function index() {
358
      $this->set('banners', $this->loadBanners());
359
      $this->set('categorias', $this->loadCategoriesProducts());
360
		$this->set('produtos', $this->loadProducts());
361
	}
362
363 View Code Duplication
   public function cart() {
364
      $this->set('categorias', $this->loadCategoriesProducts());
365
      $products = $this->loadProductsAndValuesCart();
366
367
      $this->set('products', $products['products_cart']);
368
      $this->set('total', $products['total']);
369
   }
370
371 View Code Duplication
   public function checkout() {
372
      $this->set('categorias', $this->loadCategoriesProducts());  
373
      $products = $this->loadProductsAndValuesCart();
374
375
      $this->set('products', $products['products_cart']);
376
      $this->set('total', $products['total']);
377
   }
378
379
   public function category() {
380
      $id   = $this->params['id'];
381
      $nome = $this->params['nome'];
382
383
      $products = $this->loadProducts($id);
384
385
      $this->set('categorias', $this->loadCategoriesProducts());
386
      $this->set('produtos', $products);
387
      $this->set('nameCategory', $nome);
388
   }
389
390
   public function product() {
391
      $this->loadModel('Produto');
392
393
      $id = $this->params['id'];
394
395
      $this->set('categorias', $this->loadCategoriesProducts());
396
      
397
      $produto = $this->loadProducts(null, $id)[0];
398
399
      $this->loadModel('Variacao');
400
401
      $query = array (
402
         'joins' => array(
403
                array(
404
                    'table' => 'produtos',
405
                    'alias' => 'Produto',
406
                    'type' => 'LEFT',
407
                    'conditions' => array(
408
                        'Variacao.produto_id = Produto.id',
409
                    ),
410
                )
411
            ),
412
           'conditions' => array('Variacao.produto_id' => $id, 'Variacao.ativo' => 1),
413
           'fields' => array('Produto.id, Variacao.*'),
414
      );
415
416
      $variacoes = $this->Variacao->find('all', $query);
417
      $this->set('variacoes', $variacoes);
418
419
      $this->set('produto', $produto);
420
   }
421
422
}