Completed
Push — master ( a8e8b7...373ce5 )
by Reginaldo
19:01
created

LojaController::loadBanners()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 15
nc 1
nop 1
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
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
12
use FastShipping\Lib\Tracking;
13
use FastShipping\Lib\Shipping;
14
15
class LojaController extends AppController {
16
	public $layout = 'lojaexemplo';	
17
18
  protected $usuario;
19
20
	public function beforeFilter(){
21
    $lojaSession = $this->Session->read('Usuario.loja');
22
    
23
    if (isset($lojaSession))
24
    {
25
      if (isset($this->params['loja']))
26
      {
27
        if ($this->params['loja'] != $lojaSession)
28
        {
29
          $loja = $this->params['loja'];
30
        }
31
        else 
32
        {
33
          $loja = $lojaSession;
34
        }
35
      }
36
      else 
37
      {
38
        $loja = $lojaSession;
39
      }
40
    }
41
    else
42
    {
43
      $loja = $this->params['loja'];
44
    }
45
    
46
    if (!isset($loja)) 
47
    {
48
      echo 'Loja não existe';    
49
      exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method beforeFilter() 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...
50
    }
51
    else
52
    {
53
      $this->loadModel('Usuario');
54
55
      $this->usuario = $this->Usuario->find('first', array(
56
          'conditions' => array(
57
            'Usuario.loja' => $loja
58
          )
59
        )
60
      );
61
62
      if (empty($this->usuario))
63
      {
64
        echo 'Loja não existe';
65
        exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method beforeFilter() 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...
66
      }
67
68
      $this->Session->write('Usuario.id', $this->usuario['Usuario']['id']);//gambi temporaria
69
      $this->Session->write('Usuario.loja', $this->usuario['Usuario']['loja']);//gambi temporaria
70
71
      $this->layout = $this->usuario['Usuario']['layout_loja'];
72
    }
73
74
	  return true;
75
	}
76
77
	public function loadProducts($id_categoria = null, $id_produto = null) {
78
		$this->loadModel('Produto');
79
80
      $params = array('conditions' => 
81
         array(
82
            'Produto.ativo' => 1,
83
            'Produto.id_usuario' => $this->Session->read('Usuario.id')
84
         ),
85
         'limit' => 8
86
      );
87
88
      if ($id_categoria != null) {
89
         $params['conditions']['Produto.categoria_id'] = $id_categoria;
90
      }
91
92
      if ($id_produto != null) {
93
         $params['conditions']['Produto.id'] = $id_produto;
94
      }
95
96
		  $produtos = $this->Produto->find('all', $params);
97
98
	   return $produtos;
99
	}
100
101
   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...
102
      $this->loadModel('Banner');
103
104
      $params = array(
105
         'joins' => array(
106
             array(
107
                 'table' => 'categoria_banners',
108
                 'alias' => 'CategoriaBanner',
109
                 'type' => 'LEFT',
110
                 'conditions' => array(
111
                     'Banner.categoria_banner_id = CategoriaBanner.id',
112
                 ),
113
             )
114
         ),
115
         'conditions' => array(
116
            'Banner.ativo' => 1,
117
            'Banner.usuario_id' => $this->Session->read('Usuario.id')
118
         )
119
      );
120
121
      $banners = $this->Banner->find('all', $params);
122
123
      return $banners;
124
   } 
125
126
	public function addCart() {
127
		$produto = $this->request->data('produto');
128
		
129
		if (empty($produto)) {
130
			$this->redirect('/' . $this->usuario['Usuario']['loja'] . '/');
131
		}
132
133
      if (!$this->validateProduct($produto)) {
134
         $this->Session->setFlash('Quantidade de produtos escolhidas é maior do que a disponivel!');
135
         $this->redirect('/' . $this->usuario['Usuario']['loja'] . '/');
136
      }
137
138
		$cont = count($this->Session->read('Produto'));
139
140
		$this->Session->write('Produto.'.$produto['id'].'.id' , $produto['id']);
141
      $this->Session->write('Produto.'.$produto['id'].'.quantidade' , $produto['quantidade']);
142
      $this->Session->write('Produto.'.$produto['id'].'.variacao', $produto['variacao']);
143
144
		$this->redirect('/' . $this->usuario['Usuario']['loja'] . '/cart');
145
	}
146
147
   public function removeProductCart() {
148
      if ( ($this->Session->read('Produto.' . $this->params['id'])) !== null ) {
149
         $this->Session->delete( 'Produto.' . $this->params['id'] );
150
      }
151
152
      $this->redirect('/' . $this->usuario['Usuario']['loja'] . '/cart');
153
   }
154
155
	public function clearCart() {
156
		$this->Session->delete('Produto');
157
	}
158
159
   public function loadProductsAndValuesCart() {
160
      $this->loadModel('Produto');
161
      $this->loadModel('Variacao');
162
163
      $productsSession = $this->Session->read('Produto');
164
165
      (float) $total = 0.00;
166
      $produtos      = array();
167
      foreach ($productsSession as $indice => $item) {
168
         $produto =  $this->Produto->find('all', 
169
            array('conditions' => 
170
               array('Produto.ativo' => 1,
171
                    'Produto.id' => $item['id']
172
               )
173
            )
174
         );
175
176
         $total     += $produto[0]['Produto']['preco'] * $item['quantidade'];
177
178
         $produto[0]['Produto']['quantidade'] = $item['quantidade'];
179
180
         $variacao = $this->Variacao->find('all', 
181
            array('conditions' =>
182
               array('Variacao.id' => $item['variacao'])
183
            ),
184
            array('fields' => 
185
               array('Variacao.nome_variacao')
186
            )
187
         );
188
189
         $produto[0]['Produto']['variacao'] = $variacao[0]['Variacao']['nome_variacao'];
190
191
         $produtos[] = $produto[0];
192
      }
193
194
      return array('products_cart' => $produtos, 'total' => $total);
195
   }
196
197
   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...
198
      $this->loadModel('Categoria');
199
200
      $params = array('conditions' => 
201
         array('ativo' => 1,
202
              'usuario_id' => $this->Session->read('Usuario.id')
203
         )
204
      );
205
206
      $categorias = $this->Categoria->find('all', $params);
207
208
      return $categorias;
209
   }
210
211
   public function payment() {
212
      $andress = $this->request->data('endereco');
213
     
214
      $client  = $this->request->data('cliente');
215
216
      $products = $this->loadProductsAndValuesCart();
217
218
      (float) $valor_frete = number_format($this->Session->read('Frete.valor'), 2, '.', ',');
219
220
      $objVenda = new VendaController();
221
     
222
      $productsSale = $this->prepareProductsSale($products['products_cart']);
223
     
224
      $usuario_id = $this->Session->read('Usuario.id');
225
226
      $retorno_venda = $objVenda->salvar_venda($productsSale, array('forma_pagamento' => 'pagseguro'), array('valor' => $valor_frete + $products['total']), $usuario_id);
227
      
228
      $this->paymentPagSeguro($products['products_cart'], $andress, $client, $products['total'], $valor_frete, $retorno_venda['id']);
229
   }
230
231
   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...
232
      $pagamento = new PagamentoController('PagseguroController');   
233
234
      $pagamento->setToken($this->usuario['Usuario']['token_pagseguro']);
235
      
236
      $pagamento->setEmail($this->usuario['Usuario']['email_pagseguro']);
237
238
      $pagamento->setProdutos($products);
239
      
240
      $pagamento->adicionarProdutosGateway();
241
242
      $pagamento->setEndereco($andress);
243
244
      $pagamento->setReference('#' . $id);
245
      
246
      $pagamento->setValorFrete($shipping);
247
248
      return $this->redirect($pagamento->finalizarPedido());
249
   }
250
251
   public function prepareProductsSale($products) {
252
      $retorno = array();
253
     
254
      foreach ($products as $i => $product) {
255
         $retorno[$i]['id_produto'] = $product['Produto']['id'];
256
         $retorno[$i]['quantidade'] = $product['Produto']['quantidade'];
257
         $retorno[$i]['variacao']   = $product['Produto']['variacao'];
258
      }
259
260
      return $retorno;
261
   }
262
263
   public function searchAndressByCep($cep) {
264
      $this->layout = 'ajax';
265
266
      $curl = curl_init('http://cep.correiocontrol.com.br/'.$cep.'.js');
267
268
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
269
      
270
      $resultado = curl_exec($curl);
271
272
      echo $resultado;
273
274
      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...
275
   }
276
277
   public function calcTransportAjax() {
278
      $this->layout = 'ajax';
279
   
280
      $cep_destino = $this->request->data('cep_destino');
281
      $cep_origem  = $this->request->data('cep_origem');
282
   
283
      $dataProducts = $this->loadProductsAndValuesCart();
284
   
285
      (float) $peso = 0;
286
      foreach ($dataProducts['products_cart'] as $i => $product) {
287
         $peso += $product['Produto']['peso_bruto'] * $product['Produto']['quantidade'];
288
      }
289
   
290
      $fretes = $this->transport($cep_destino, $this->usuario['Usuario']['cep_origem'], $peso);
291
   
292
      $disponiveis = array();
293
   
294
      $cont = 0;
295
      foreach ($fretes as $i => $frete) {
296
         $disponiveis[$cont]['valor']  = (array) $frete->Valor;
297
         $disponiveis[$cont]['prazo']  = (array) $frete->PrazoEntrega;
298
         $disponiveis[$cont]['codigo'] = (array) $frete->Codigo;
299
         $disponiveis[$cont]['valor']  = array_shift($disponiveis[$cont]['valor']);
300
         $disponiveis[$cont]['prazo']  = array_shift($disponiveis[$cont]['prazo']);
301
         $disponiveis[$cont]['codigo'] = array_shift($disponiveis[$cont]['codigo']);
302
         
303
         $cont++;
304
      }
305
   
306
      $this->Session->write('Frete.valor', $disponiveis[$cont - 1]['valor']);
307
   
308
      (float) $total = $disponiveis[$cont - 1]['valor'] + $dataProducts['total'];
309
   
310
      $total = number_format($total, 2, ',', '.');
311
   
312
      $retorno = array('frete' => $disponiveis[$cont - 1]['valor'], 'total' => $total);
313
   
314
      echo json_encode($retorno);   
315
      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...
316
   }
317
   
318
   public function transport($cep_destino, $cep_origem, $peso) {
319
      $altura = '2';
320
      $largura = '11';
321
      $comprimento = '16';
322
323
      $dados['sCepDestino'] = $cep_destino;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$dados was never initialized. Although not strictly required by PHP, it is generally a good practice to add $dados = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
324
      $dados['sCepOrigem'] = $cep_origem;
325
      $dados['nVlPeso'] = $peso;
326
      $dados['nVlComprimento'] = $comprimento;
327
      $dados['nVlAltura'] = $altura;
328
      $dados['nVlLargura'] = $largura;
329
      $dados['nCdServico'] = '41106';
330
      $dados['nVlDiametro'] = '2';
331
      $dados['nCdFormato'] = '1';
332
      $dados['sCdMaoPropria'] = 'n';
333
      $dados['nVlValorDeclarado'] = '0';
334
      $dados['StrRetorno'] = 'xml';
335
      
336
      $dados = http_build_query($dados);
337
      
338
      $curl = curl_init('http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx' . '?' . $dados);
339
      
340
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
341
      
342
      $resultado = curl_exec($curl);
343
      $resultado = simplexml_load_string($resultado);
344
      
345
      return $resultado;
346
   }
347
348
   public function saveEmailNewsletter() {
349
      $nome  = $this->request->data('nome');
350
      $email = $this->request->data('email');
351
352
      $objNewsletter = new NewsletterController();
353
354
      if ($objNewsletter->newsletter_cadastro($nome, $email, $this->Session->read('Usuario.id')))
355
      {
356
         echo json_encode(true);
357
         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...
358
      } 
359
360
      echo json_encode(false);
361
      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...
362
   }
363
364
   public function useCoupon() {
365
      $this->layout = 'ajax';
366
367
      $cupom = $this->request->data('cupom');
368
      $valor  = $this->request->data('valor');
369
         
370
      $objCupom = new CupomController();
371
      $novo_valor = $objCupom->utilizar_cupom($cupom, $valor, $this->Session->read('Usuario.id'));
372
373
      if (!$novo_valor)
374
      {
375
         echo json_encode(false);
376
         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...
377
      }
378
379
      echo json_encode($novo_valor);
380
      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...
381
   }
382
383
   public function validateProduct($data) {
384
      $this->loadModel('Variacao');
385
386
      $params = array('conditions' => 
387
         array(
388
            'Variacao.id' => $data['variacao']
389
         )
390
      );
391
392
      $variacao = $this->Variacao->find('all', $params);
393
394
      if ($variacao[0]['Variacao']['estoque'] <= 0 || $data['quantidade'] > $variacao[0]['Variacao']['estoque'])
395
      {
396
         return false;
397
      }
398
399
      return true;   
400
   }
401
402
   public function saveClientFromEcommerce($data) {
403
      $this->loadModel('Cliente');
404
405
      $data['senha'] = sha1($data['senha']);
406
407
      $this->Cliente->set($data);
408
409
      if (!$this->Cliente->validates())
410
      {
411
         return false;
412
      }
413
414
      if (!$this->Cliente->save())
415
      {
416
         return false;
417
      }
418
419
      return $this->Cliente->getLastInsertId();
420
   }
421
422
   public function saveAndressClientFromEcommerce($data) {
423
      $this->loadModel('EnderecoClienteCadastro');
424
425
      $this->EnderecoClienteCadastro->set($data);
426
427
      if (!$this->EnderecoClienteCadastro->validates())
428
      {
429
         return false;
430
      }
431
432
      return $this->EnderecoClienteCadastro->save();
433
   }
434
435
	/**
436
	* Views
437
	*/
438
	public function index() {
439
      $this->set('usuario', $this->usuario);
440
      $this->set('banners', $this->loadBanners());
441
      $this->set('categorias', $this->loadCategoriesProducts());
442
      $this->set('produtos', $this->loadProducts());
443
      
444
      $this->render('/' . $this->usuario['Usuario']['folder_view'] . '/index');
445
	}
446
447 View Code Duplication
   public function cart() {
448
      $this->set('usuario', $this->usuario);
449
      $this->set('categorias', $this->loadCategoriesProducts());
450
      $products = $this->loadProductsAndValuesCart();
451
452
      $this->set('products', $products['products_cart']);
453
      $this->set('total', $products['total']);
454
455
      $this->render('/' . $this->usuario['Usuario']['folder_view'] . '/cart');
456
   }
457
458 View Code Duplication
   public function checkout() {
459
      $this->set('usuario', $this->usuario);
460
      $this->set('categorias', $this->loadCategoriesProducts());  
461
      $products = $this->loadProductsAndValuesCart();
462
463
      $this->set('products', $products['products_cart']);
464
      $this->set('total', $products['total']);
465
466
      $this->render('/' . $this->usuario['Usuario']['folder_view'] . '/checkout');
467
   }
468
469
   public function category() {
470
      $this->set('usuario', $this->usuario);
471
      $id   = $this->params['id'];
472
      $nome = $this->params['nome'];
473
474
      $products = $this->loadProducts($id);
475
476
      $this->set('categorias', $this->loadCategoriesProducts());
477
      $this->set('produtos', $products);
478
      $this->set('nameCategory', $nome);
479
480
      $this->render('/' . $this->usuario['Usuario']['folder_view'] . '/category');
481
   }
482
483
   public function product() {
484
      $this->set('usuario', $this->usuario);
485
      $this->loadModel('Produto');
486
487
      $id = $this->params['id'];
488
489
      $this->set('categorias', $this->loadCategoriesProducts());
490
      
491
      $produto = $this->loadProducts(null, $id)[0];
492
493
      $this->loadModel('Variacao');
494
495
      $query = array (
496
         'joins' => array(
497
                array(
498
                    'table' => 'produtos',
499
                    'alias' => 'Produto',
500
                    'type' => 'LEFT',
501
                    'conditions' => array(
502
                        'Variacao.produto_id = Produto.id',
503
                    ),
504
                )
505
            ),
506
           'conditions' => array('Variacao.produto_id' => $id, 'Variacao.ativo' => 1),
507
           'fields' => array('Produto.id, Variacao.*'),
508
      );
509
510
      $variacoes = $this->Variacao->find('all', $query);
511
      $this->set('variacoes', $variacoes);
512
513
      $this->set('produto', $produto);
514
515
      $this->render('/' . $this->usuario['Usuario']['folder_view'] . '/product');
516
   }
517
518
   public function retornopagseguro() {
0 ignored issues
show
Coding Style introduced by
retornopagseguro 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...
519
      $code = $_GET['code'];
520
521
      pr($code,1);
522
   }
523
524
}