Skip to content
Browse files

OSC PRO v 4.0.1

Olá pessoal gostaria de comunicar estou abrindo o source do OSC pro 4.0
como Free, acho que a necessidade desse módulo é muito grande e sua
importância para comunidade também para que eu possa simplesmente travas
somente vendas do mesmo! :)

OBS: Isso não quer dizer que não aceitarei mais doações rs, seram sempre
bem vindas em:
http://www.deivison.com.br/blog/2012/08/11/osc-magento-brasil-magento-one-step-checkout-free-e-normatizado-para-o-brasil/

Obrigado a todos!
Peço apenas que se possível seja colaborado com novas atualizações e
ajuda na reportagem dos erros para que os mesmo possam ser corrigidos.

Obs: De inicio tenho certeza que haverá alguns probleminhas a serem
consertados, mas acredito que juntos conseguiremos fazer algo estável!

Conto com vocês!
  • Loading branch information...
0 parents commit 65f1d26b1b414d6d550f903260af2d69b28b15af @deivisonarthur committed
Showing with 23,798 additions and 0 deletions.
  1. +5 −0 Link para gerar o serial do OSC PRO 4.0.url
  2. +119 −0 README.md
  3. +14 −0 ...code/local/DeivisonArthur/OnepageCheckout/Adminhtml/Model/System/Config/Source/AddressOptions.php
  4. +13 −0 ...de/local/DeivisonArthur/OnepageCheckout/Adminhtml/Model/System/Config/Source/AgreementOptions.php
  5. +20 −0 app/code/local/DeivisonArthur/OnepageCheckout/Block/Agreements.php
  6. +17 −0 app/code/local/DeivisonArthur/OnepageCheckout/Block/Links.php
  7. +101 −0 app/code/local/DeivisonArthur/OnepageCheckout/Block/Onepage/Billship.php
  8. +20 −0 app/code/local/DeivisonArthur/OnepageCheckout/Block/Onepage/Link.php
  9. +10 −0 app/code/local/DeivisonArthur/OnepageCheckout/Block/Widget/Dob.php
  10. +9 −0 app/code/local/DeivisonArthur/OnepageCheckout/Block/Widget/Gender.php
  11. +9 −0 app/code/local/DeivisonArthur/OnepageCheckout/Block/Widget/Name.php
  12. +9 −0 app/code/local/DeivisonArthur/OnepageCheckout/Block/Widget/Taxvat.php
  13. +67 −0 app/code/local/DeivisonArthur/OnepageCheckout/Helper/Data.php
  14. +8 −0 app/code/local/DeivisonArthur/OnepageCheckout/Helper/Url.php
  15. +29 −0 app/code/local/DeivisonArthur/OnepageCheckout/Model/Entity/Tipopessoa.php
  16. +29 −0 app/code/local/DeivisonArthur/OnepageCheckout/Model/Observer.php
  17. +30 −0 app/code/local/DeivisonArthur/OnepageCheckout/Model/Service/Quote.php
  18. +850 −0 app/code/local/DeivisonArthur/OnepageCheckout/Model/Type/Geo.php
  19. +659 −0 app/code/local/DeivisonArthur/OnepageCheckout/controllers/IndexController.php
  20. +22 −0 app/code/local/DeivisonArthur/OnepageCheckout/etc/adminhtml.xml
  21. +319 −0 app/code/local/DeivisonArthur/OnepageCheckout/etc/config.xml
  22. +593 −0 app/code/local/DeivisonArthur/OnepageCheckout/etc/system.xml
  23. +764 −0 app/code/local/DeivisonArthur/OnepageCheckout/sql/onepagecheckout_setup/mysql4-install-3.0.2.php
  24. +21 −0 app/code/local/DeivisonArthur/OnepageCheckout/sql/onepagecheckout_setup/mysql4-upgrade-4.0.0.php
  25. +153 −0 app/design/frontend/base/default/layout/onepagecheckout.xml
  26. +39 −0 app/design/frontend/base/default/template/onepagecheckout/cart/noItems.phtml
  27. +40 −0 app/design/frontend/base/default/template/onepagecheckout/forgotpassword.phtml
  28. +48 −0 app/design/frontend/base/default/template/onepagecheckout/login.phtml
  29. +36 −0 app/design/frontend/base/default/template/onepagecheckout/onepage/agreements.phtml
  30. +945 −0 app/design/frontend/base/default/template/onepagecheckout/onepage/billing.phtml
  31. +60 −0 app/design/frontend/base/default/template/onepagecheckout/onepage/coupon.phtml
  32. +5 −0 app/design/frontend/base/default/template/onepagecheckout/onepage/link.phtml
  33. +33 −0 app/design/frontend/base/default/template/onepagecheckout/onepage/payment.phtml
  34. +27 −0 app/design/frontend/base/default/template/onepagecheckout/onepage/payment/methods.phtml
  35. +16 −0 app/design/frontend/base/default/template/onepagecheckout/onepage/review.phtml
  36. +34 −0 app/design/frontend/base/default/template/onepagecheckout/onepage/review/info.phtml
  37. +117 −0 app/design/frontend/base/default/template/onepagecheckout/onepage/review/item.phtml
  38. +17 −0 app/design/frontend/base/default/template/onepagecheckout/onepage/review/totals.phtml
  39. +470 −0 app/design/frontend/base/default/template/onepagecheckout/onepage/shipping.phtml
  40. +15 −0 app/design/frontend/base/default/template/onepagecheckout/onepage/shipping_method.phtml
  41. +159 −0 app/design/frontend/base/default/template/onepagecheckout/onepagecheckout.phtml
  42. +115 −0 app/design/frontend/base/default/template/onepagecheckout/persistent/customer/address/book.phtml
  43. +217 −0 app/design/frontend/base/default/template/onepagecheckout/persistent/customer/address/edit.phtml
  44. +410 −0 app/design/frontend/base/default/template/onepagecheckout/persistent/customer/form/edit.phtml
  45. +402 −0 app/design/frontend/base/default/template/onepagecheckout/persistent/customer/form/register.phtml
  46. +42 −0 app/design/frontend/base/default/template/onepagecheckout/widget/dob.phtml
  47. +13 −0 app/design/frontend/base/default/template/onepagecheckout/widget/gender.phtml
  48. +66 −0 app/design/frontend/base/default/template/onepagecheckout/widget/name.phtml
  49. +7 −0 app/design/frontend/base/default/template/onepagecheckout/widget/taxvat.phtml
  50. +9 −0 app/etc/modules/DeivisonArthur_OnepageCheckout.xml
  51. +75 −0 app/locale/en_US/DeivisonArthur_OnepageCheckout.csv
  52. +75 −0 app/locale/pt_BR/DeivisonArthur_OnepageCheckout.csv
  53. +26 −0 html OSC 4.0.txt
  54. +186 −0 skin/frontend/base/default/css/onepagecheckout.css
  55. +187 −0 skin/frontend/base/default/deivison/buscacep.php
  56. +596 −0 skin/frontend/base/default/deivison/deivison.js
  57. +8,939 −0 skin/frontend/base/default/deivison/jquery.js
  58. +7 −0 skin/frontend/base/default/deivison/jquery.maskedinput-1.2.2.min.js
  59. +5,702 −0 skin/frontend/base/default/deivison/phpQuery-onefile.php
  60. BIN skin/frontend/base/default/images/onepagecheckout/Thumbs.db
  61. BIN skin/frontend/base/default/images/onepagecheckout/buttonbg.gif
  62. BIN skin/frontend/base/default/images/onepagecheckout/buttonbgsmall.gif
  63. BIN skin/frontend/base/default/images/onepagecheckout/cancel.png
  64. BIN skin/frontend/base/default/images/onepagecheckout/cancel_round.png
  65. BIN skin/frontend/base/default/images/onepagecheckout/cartOSC.png
  66. BIN skin/frontend/base/default/images/onepagecheckout/close.png
  67. BIN skin/frontend/base/default/images/onepagecheckout/loader.gif
  68. BIN skin/frontend/base/default/images/onepagecheckout/osc-brasil-adm.png
  69. BIN skin/frontend/base/default/images/onepagecheckout/osc-brasilp.png
  70. BIN skin/frontend/base/default/images/onepagecheckout/place-order.jpg
  71. BIN skin/frontend/base/default/images/onepagecheckout/shd-medium.png
  72. +773 −0 skin/frontend/base/default/js/onepagecheckout.js
5 Link para gerar o serial do OSC PRO 4.0.url
@@ -0,0 +1,5 @@
+[{000214A0-0000-0000-C000-000000000046}]
+Prop3=19,2
+[InternetShortcut]
+URL=http://onestepcheckout.com.br/LojaModelo/keygen/
+IDList=
119 README.md
@@ -0,0 +1,119 @@
+Módulo OSC-Magento-Brasil – Normatização do módulo para o padrão brasileiro
+=================
+O projeto OCS-MAgento-Brasil é uma iniciativa para traduzir e adaptar o módulo free de OSC(One Step Checkout) para Magento chamado IWD OnePageCheckout. O módulo irá traduzir, adicionar estados, formatar, validar campos e adicionar novos campos. Iremos tratar os principais campos, como: Rua, Bairro, Cidade, Estado, Cep com busca por Ajax com busca nos Correios, CPF/CNPJ, IE(Inscrição Estadual), tipo pessoa, Telefone, Celular,…
+
+Importante!
+=================
+#####################################################################
+# Faça sempre backup antes de realizar qualquer modificação! #
+#####################################################################
+
+
+Oque esse módulo irá fazer?
+=================
+
+Com o módulo OSC-Magento-Brasil irá se ter o meio mais famoso de checkout do Magento conhecido por OSC(One Step Checkout) e iremos fazer outros ajustes, como:
+
+* Tradução dos Campos do formulário. (feito!)
+* Inclusão dos estados brasileiros. (feito!)
+* Remodelação do campo endereço do magento de 4 linhas. Dividindo e formatando para Endereço, Número, Bairro e Cidade. (feito!)
+* Utilização do campo taxvat por padrão como campo de CPF/CNPJ. (feito!)
+* Busca do endereço por ajax direto do site dos Correios. (feito!)
+* Formatação dos campos por máscara. Exe: Telefone com 9 ou 8 dígitos (99) ?9999-9999. (feito!)
+* Inclusão do campo tipo pessoa (Física ou Jurídica) (feito!)
+* IE(Inscrição Estadual) para gereção da NFE (feito!)
+* Inclusão do campo RG(Identidade) (feito!)
+* Opção de desligar todos os campos (feito!)
+* Opção de atribuição de obrigatório em todos os campos (feito!)
+* E outras coisas mais
+
+Também pretendo implementar opções de segurança, como:
+
+* Detecção de utilização de proxy com envio de email ao administrador
+* Detecção de compras suspeitas com envio de email ao administrador (Irá verificar por Geolocalização local onde foi feito a compra e bater com o local de entrega)
+* Integração com o sistema de detecção de fraude Maxmind (http://www.maxmind.com)
+
+veja mais dicas sobre análise de risco e fraude no Magento em:
+http://www.deivison.com.br/blog/2012/07/25/modulo-de-analise-de-risco-e-fraude-no-magento-sem-mensalidade/
+
+Observações Importantes!
+=================
+Por motivos de segurança, recomendamos que faça sempre o download desse módulo diretamente no Github ou aqui no site do projeto. Atualmente na web, muitas pessoas mau intencionadas pegam templates e projetos Open Source, descompactam, inserem scripts maliciosos em js criptografados e redistribuem na web! Outra modalidade de pessoas mau intencionadas são as que pegam o projeto Open Source feito na integra, não realizam nenhuma alteração e redistribuem na web como se fosse a pessoa responsável ou participante no projeto, sem que ao menos terem adicionado uma linha sequer ao projeto!
+
+Dessa forma prestigiaram e incentivaram os mantenedores do projeto e terão a garantia de não pegar o módulos com scripts maliciosos!
+
+Projeto 100% auditado pelos mantenedores no Github!
+
+Considerações finais do projeto
+=================
+Realmente fazer essas customizações, nos deu muito trabalho e noites viradas, mas acreditamos ter valido a pena!
+Foi fundamental para o desenvolvimentos desse módulo nossas buscas incessantes de aperfeiçoamento em desenvolvimento no Magento e da ratificação da real necessidade de termos um módulo padronizado para o Brasil. E assim nos livrar do POG a cada instalação de um e-commerce! rs
+Um cuidado e observação nossa, foi desenvolver o módulo para trabalhar de forma genérica para assim atender as necessidades básicas descritas por nós e por emails e comentários enviados.
+
+Procuramos fazer todas as customizações seguindo as rigorosas padronizações do Zend, assim acreditamos ter criado um módulo robusto e que irá suprir e contribuir muito para a comunidade.
+
+Pensei por diversas vezes em colocar ou não esse módulo FREE! Por um lado eu poderia ter criptografado o módulo com o Ioncube e ter ganhado um bom dinheiro com ele, pois como podemos ver esse mesmo módulo sem customização nehuma é vendido pelos grandes cases em Magento de R$500 a R$1.200 reais. Mas por outro lado, pesou muito a contribuiçao e a nossa mente Open Source, onde acreditamos que o maior valor adquirido foi o conhecimento e a possibilidade do aumento infinito intelectual ao projeto!
+
+
+PS: Coloquei o projeto como sendo versão final, mas na verdade sei que será somente o começo né rsrs, pois sei oque o volume que receberei de dicas e acertos vai ser muito grande! Na verdade a versão final representará o ponto que irei pegar bem menos para mexer no projeto e deixarei o projeto aberto mais a contribuições da comunidade pelo Github.
+
+
+Release da versão Final 3.0
+=================
+1 Controle do conflito na duplicidade dos dados instalados (Ou seja, antes caso opta-se por reinstalar o módulos estava dando o erro no bd de campos duplicados. Acontecia isso com os estados e com os novos campos, caso já os tinha no bd. Já nessa versão o sistema faz a verificação da existencia no bd de todos os campos e dos estados.)
+2 Controle de todos os campos pela ADM por exibir ou não e/ou de serem ou não obrigatório.
+3 Campos configuráveis no registro dos usuários: CFP/CNPJ, Empresa, IE e Identidade.
+4 Campos configuráveis do reponsável pelo recebimento no envio: CFP/CNPJ, IE, Identidade e Celular.
+5 Opção de habilitar ou desabilitar a biblioteca Jquery.
+6 Opção de habilitar ou desabilitar a Formatação do campo CEP (Pois componentes como o Matrix Rates não permitem o "-", apenas os números).
+7 Opção de escolha do campo CPF/CNPJ pelo taxvat ou não.
+8 Exibição de todos os campos nos dados da ordem de serviço.
+9 Escolha da exibição do link de login pelo box OSC ou pela tela nativa do Magento.
+
+Release da versão Beta 2.0
+=================
+* Adicionado formatação dos campos telephone e fax com 8 ou 9 digitos por Expreg onde também altera o maxlength. E adicionado formatação do campo taxvat(CPF/CNPJ)
+
+Site e comunidade do projeto:
+=================
+http://onestepcheckout.com.br/
+
+Demostração online do projeto:
+=================
+http://onestepcheckout.com.br/final3/magento-1.5.1.0/onestep-magento-1-5-1-1.html
+
+Tutorial para instalação e tratamentos de erros:
+=================
+#########################################################################################################################
+http://www.deivison.com.br/blog/2012/08/11/osc-magento-brasil-magento-one-step-checkout-free-e-normatizado-para-o-brasil/
+#########################################################################################################################
+
+Desenvolvedores e mantenedores do projeto Módulo OSC-Magento-Brasil:
+=================
+* Deivison Arthur Lemos Serpa
+http://www.deivison.com.br
+* Denis Colli Spalenza
+http://www.xpdev.com.br
+
+Versão do projeto:
+=================
+O módulo ainda encontra-se em fase de desenvolvimento! Ou seja, Estágio Final – v 3.0 para testes e homologação!
+
+Créditos:
+=================
+* Projeto base de OSC utilizado: http://www.interiorwebdesign.com/magento/magento-one-step-checkout-module.html
+* Instação dos estados por Alex Braga: http://www.alexbraga.net
+* Script base para implementação da busca do CEP por Ajax: http://www.pinceladasdaweb.com.br/blog/2012/01/31/webservice-consulta-de-cep-diretamente-ao-site-dos-correios/
+* Traduções pt-BR do Magento: http://www.cerebrum.com.br/index.php/magento-portugues-download-traducao-brasil-cielo-redecard-american-express.html
+
+Logs:
+=================
+Projeto iniciado dia: 11/08/2012 ás 19h
+Estágio do projeto: Versão Final 3.0 (testes e homologação)
+Link do demo: http://onestepcheckout.com.br/final3
+
+Gostou do módulo?
+=================
+
+Se você gostou, se foi útil para você, se fez você economizar aquela grana pois estava prestes a pagar caro por aquele módulo pago, pois não achava um solução gratuita que te atendesse e queira prestigiar o trabalho feito efetuando uma doação de qualquer valor, não vou negar e vou ficar grato, você pode fazer isso utilizando o Pagseguro no site ofical do projeto:
+http://onestepcheckout.com.br/
14 ...al/DeivisonArthur/OnepageCheckout/Adminhtml/Model/System/Config/Source/AddressOptions.php
@@ -0,0 +1,14 @@
+<?php
+class DeivisonArthur_OnepageCheckout_Adminhtml_Model_System_Config_Source_AddressOptions
+{
+ public function toOptionArray()
+ {
+ $help_obj = Mage::helper('onepagecheckout');
+ $options = array(
+ array('value' => 'optional','label' => $help_obj->__('Optional')),
+ array('value' => 'required','label' => $help_obj->__('Required')),
+ array('value' => 'hidden', 'label' => $help_obj->__('Hidden'))
+ );
+ return $options;
+ }
+}
13 .../DeivisonArthur/OnepageCheckout/Adminhtml/Model/System/Config/Source/AgreementOptions.php
@@ -0,0 +1,13 @@
+<?php
+class DeivisonArthur_OnepageCheckout_Adminhtml_Model_System_Config_Source_AgreementOptions
+{
+ public function toOptionArray()
+ {
+ $help_obj = Mage::helper('onepagecheckout');
+ $options = array(
+ array('value' => 'standard','label' => $help_obj->__('Standard')),
+ array('value' => 'minimal', 'label' => $help_obj->__('Minimal'))
+ );
+ return $options;
+ }
+}
20 app/code/local/DeivisonArthur/OnepageCheckout/Block/Agreements.php
@@ -0,0 +1,20 @@
+<?php
+class DeivisonArthur_OnepageCheckout_Block_Agreements extends Mage_Core_Block_Template
+{
+ public function getAgreements()
+ {
+ if (!$this->hasAgreements())
+ {
+ $agre = array();
+ if (Mage::getStoreConfigFlag('onepagecheckout/agreements/enabled'))
+ {
+ $agre = Mage::getModel('checkout/agreement')->getCollection()
+ ->addStoreFilter(Mage::app()->getStore()->getId())
+ ->addFieldToFilter('is_active', 1);
+
+ }
+ $this->setAgreements($agre);
+ }
+ return $this->getData('agreements');
+ }
+}
17 app/code/local/DeivisonArthur/OnepageCheckout/Block/Links.php
@@ -0,0 +1,17 @@
+<?php
+class DeivisonArthur_OnepageCheckout_Block_Links extends Mage_Checkout_Block_Links
+{
+ public function addCheckoutLink()
+ {
+ if ($this->helper('onepagecheckout')->isOnepageCheckoutEnabled())
+ {
+ $parent = $this->getParentBlock();
+ if ($parent)
+ $parent->addLink($this->helper('checkout')->__('Checkout'), 'onepagecheckout', $this->helper('checkout')->__('Checkout'), true, array('_secure'=> true), 60, null, 'class="top-link-checkout"');
+
+ return $this;
+ }
+ else
+ return parent::addCheckoutLink();
+ }
+}
101 app/code/local/DeivisonArthur/OnepageCheckout/Block/Onepage/Billship.php
@@ -0,0 +1,101 @@
+<?php
+
+class DeivisonArthur_OnepageCheckout_Block_Onepage_Billship extends Mage_Checkout_Block_Onepage_Billing
+{
+ public function getBillAddress()
+ {
+ return $this->getQuote()->getBillingAddress();
+ }
+
+ public function getShipAddress()
+ {
+ return $this->getQuote()->getShippingAddress();
+ }
+
+ public function getCustomerBillAddr()
+ {
+ return $this->buildCustomerAddress('billing');
+ }
+
+ public function getBillingCountriesSelectBox()
+ {
+ return $this->buildCountriesSelectBox('billing');
+ }
+
+ public function getCustomerShipAddr()
+ {
+ return $this->buildCustomerAddress('shipping');
+ }
+
+ public function getShippingCountriesSelectBox()
+ {
+ return $this->buildCountriesSelectBox('shipping');
+ }
+
+ public function buildCustomerAddress($addr_type)
+ {
+ if ($this->isCustomerLoggedIn()) {
+ $options = array();
+ foreach ($this->getCustomer()->getAddresses() as $address) {
+ $options[] = array(
+ 'value'=>$address->getId(),
+ 'label'=>$address->format('oneline')
+ );
+ }
+
+ switch($addr_type)
+ {
+ case 'billing':
+ $address = $this->getCustomer()->getPrimaryBillingAddress();
+ break;
+ case 'shipping':
+ $address = $this->getCustomer()->getPrimaryShippingAddress();
+ break;
+ }
+
+ if ($address) {
+ $addressId = $address->getId();
+ } else {
+ if($addr_type == 'billing')
+ $obj = $this->getBillAddress();
+ else
+ $obj = $this->getShipAddress();
+
+ $addressId = $obj->getId();
+ }
+
+ $select = $this->getLayout()->createBlock('core/html_select')
+ ->setId("{$addr_type}_customer_address")->setName("{$addr_type}_address_id")
+ ->setValue($addressId)->setOptions($options)
+ ->setExtraParams('onchange="'.$addr_type.'.newAddress(!this.value)"')
+ ->setClass('customer_address');
+
+ $select->addOption('', Mage::helper('checkout')->__('New Address'));
+ return $select->getHtml();
+ }
+ return '';
+ }
+
+ public function buildCountriesSelectBox($addr_type)
+ {
+ if($addr_type == 'billing')
+ $obj = $this->getBillAddress();
+ else
+ $obj = $this->getShipAddress();
+
+ $countryId = $obj->getCountryId();
+ if (is_null($countryId)) {
+ $countryId = Mage::getStoreConfig('general/country/default');
+ }
+ $select = $this->getLayout()->createBlock('core/html_select')
+ ->setId("{$addr_type}:country_id")->setName("{$addr_type}[country_id]")
+ ->setValue($countryId)->setOptions($this->getCountryOptions())
+ ->setTitle(Mage::helper('checkout')->__('Country'))
+ ->setClass('validate-select');
+
+ if($addr_type == 'shipping')
+ $select->setExtraParams('onchange="shipping.setSameAsBilling(false);"');
+
+ return $select->getHtml();
+ }
+}
20 app/code/local/DeivisonArthur/OnepageCheckout/Block/Onepage/Link.php
@@ -0,0 +1,20 @@
+<?php
+
+class DeivisonArthur_OnepageCheckout_Block_Onepage_Link extends Mage_Core_Block_Template
+{
+ public function isOnepageCheckoutAllowed()
+ {
+ return $this->helper('onepagecheckout')->isOnepageCheckoutEnabled();
+ }
+
+ public function checkEnable()
+ {
+ return Mage::getSingleton('checkout/session')->getQuote()->validateMinimumAmount();
+ }
+
+ public function getOnepageCheckoutUrl()
+ {
+ $url = $this->getUrl('onepagecheckout', array('_secure' => true));
+ return $url;
+ }
+}
10 app/code/local/DeivisonArthur/OnepageCheckout/Block/Widget/Dob.php
@@ -0,0 +1,10 @@
+<?php
+class DeivisonArthur_OnepageCheckout_Block_Widget_Dob extends Mage_Customer_Block_Widget_Dob
+{
+ protected $_dateInputs = array();
+ public function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('onepagecheckout/widget/dob.phtml');
+ }
+}
9 app/code/local/DeivisonArthur/OnepageCheckout/Block/Widget/Gender.php
@@ -0,0 +1,9 @@
+<?php
+class DeivisonArthur_OnepageCheckout_Block_Widget_Gender extends Mage_Customer_Block_Widget_Gender
+{
+ public function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('onepagecheckout/widget/gender.phtml');
+ }
+}
9 app/code/local/DeivisonArthur/OnepageCheckout/Block/Widget/Name.php
@@ -0,0 +1,9 @@
+<?php
+class DeivisonArthur_OnepageCheckout_Block_Widget_Name extends Mage_Customer_Block_Widget_Name
+{
+ public function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('onepagecheckout/widget/name.phtml');
+ }
+}
9 app/code/local/DeivisonArthur/OnepageCheckout/Block/Widget/Taxvat.php
@@ -0,0 +1,9 @@
+<?php
+class DeivisonArthur_OnepageCheckout_Block_Widget_Taxvat extends Mage_Customer_Block_Widget_Taxvat
+{
+ public function _construct()
+ {
+ parent::_construct();
+ $this->setTemplate('onepagecheckout/widget/taxvat.phtml');
+ }
+}
67 app/code/local/DeivisonArthur/OnepageCheckout/Helper/Data.php
@@ -0,0 +1,67 @@
+<?php
+
+class DeivisonArthur_OnepageCheckout_Helper_Data extends Mage_Core_Helper_Abstract
+{
+ protected $_agree = null;
+
+ public function isOnepageCheckoutEnabled()
+ {
+ return (bool)Mage::getStoreConfig('onepagecheckout/general/enabled');
+ }
+
+ public function isGuestCheckoutAllowed()
+ {
+ return Mage::getStoreConfig('onepagecheckout/general/guest_checkout');
+ }
+
+ public function isShippingAddressAllowed()
+ {
+ return Mage::getStoreConfig('onepagecheckout/general/shipping_address');
+ }
+
+ public function getAgreeIds()
+ {
+ if (is_null($this->_agree))
+ {
+ if (Mage::getStoreConfigFlag('onepagecheckout/agreements/enabled'))
+ {
+ $this->_agree = Mage::getModel('checkout/agreement')->getCollection()
+ ->addStoreFilter(Mage::app()->getStore()->getId())
+ ->addFieldToFilter('is_active', 1)
+ ->getAllIds();
+ }
+ else
+ $this->_agree = array();
+ }
+ return $this->_agree;
+ }
+
+ public function isSubscribeNewAllowed()
+ {
+ if (!Mage::getStoreConfig('onepagecheckout/general/newsletter_checkbox'))
+ return false;
+
+ $cust_sess = Mage::getSingleton('customer/session');
+ if (!$cust_sess->isLoggedIn() && !Mage::getStoreConfig('newsletter/subscription/allow_guest_subscribe'))
+ return false;
+
+ $subscribed = $this->getIsSubscribed();
+ if($subscribed)
+ return false;
+ else
+ return true;
+ }
+
+ public function getIsSubscribed()
+ {
+ $cust_sess = Mage::getSingleton('customer/session');
+ if (!$cust_sess->isLoggedIn())
+ return false;
+
+ return Mage::getModel('newsletter/subscriber')->getCollection()
+ ->useOnlySubscribed()
+ ->addStoreFilter(Mage::app()->getStore()->getId())
+ ->addFieldToFilter('subscriber_email', $cust_sess->getCustomer()->getEmail())
+ ->getAllIds();
+ }
+}
8 app/code/local/DeivisonArthur/OnepageCheckout/Helper/Url.php
@@ -0,0 +1,8 @@
+<?php
+class DeivisonArthur_OnepageCheckout_Helper_Url extends Mage_Checkout_Helper_Url
+{
+ public function getCheckoutUrl()
+ {
+ return $this->_getUrl('onepagecheckout', array('_secure'=>true));
+ }
+}
29 app/code/local/DeivisonArthur/OnepageCheckout/Model/Entity/Tipopessoa.php
@@ -0,0 +1,29 @@
+<?php
+class DeivisonArthur_OnepageCheckout_Model_Entity_Tipopessoa extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
+{
+ public function getAllOptions()
+ {
+ if ($this->_options === null) {
+ $this->_options = array();
+ $this->_options[] = array(
+ 'value' => '',
+ 'label' => 'Escolha a opcao'
+ );
+ $this->_options[] = array(
+ 'value' => 1,
+ 'label' => 'Fisica'
+ );
+ $this->_options[] = array(
+ 'value' => 2,
+ 'label' => 'Juridica'
+ );
+ $this->_options[] = array(
+ 'value' => 3,
+ 'label' => 'Outro'
+ );
+
+ }
+
+ return $this->_options;
+ }
+}
29 app/code/local/DeivisonArthur/OnepageCheckout/Model/Observer.php
@@ -0,0 +1,29 @@
+<?php
+class DeivisonArthur_OnepageCheckout_Model_Observer
+{
+ public function addHistoryComment($data)
+ {
+ $comment = Mage::getSingleton('customer/session')->getOrderCustomerComment();
+ $comment = trim($comment);
+ if (!empty($comment))
+ $data['order']->addStatusHistoryComment($comment)->setIsVisibleOnFront(true)->setIsCustomerNotified(false);
+ }
+
+ public function removeHistoryComment()
+ {
+ Mage::getSingleton('customer/session')->setOrderCustomerComment(null);
+ }
+
+ public function setEmptyCartTemplate()
+ {
+ if (Mage::helper('onepagecheckout')->isOnepageCheckoutEnabled())
+ {
+ $cartHelper = Mage::helper('checkout/cart');
+ $layout = Mage::getSingleton('core/layout');
+
+ if (!$cartHelper->getItemsCount()){
+ $layout->getBlock('checkout.cart')->setTemplate('onepagecheckout/cart/noItems.phtml');
+ }
+ }
+ }
+}
30 app/code/local/DeivisonArthur/OnepageCheckout/Model/Service/Quote.php
@@ -0,0 +1,30 @@
+<?php
+class DeivisonArthur_OnepageCheckout_Model_Service_Quote extends Mage_Sales_Model_Service_Quote
+{
+ protected function _validate()
+ {
+ $helper = Mage::helper('sales');
+ if (!$this->getQuote()->isVirtual())
+ {
+ $address = $this->getQuote()->getShippingAddress();
+ $addrValidator = Mage::getSingleton('onepagecheckout/type_geo')->validateAddress($address);
+ if ($addrValidator !== true)
+ Mage::throwException($helper->__('Please check shipping address information. %s', implode(' ', $addrValidator)));
+
+ $ship_method = $address->getShippingMethod();
+ $rate = $address->getShippingRateByCode($ship_method);
+ if (!$this->getQuote()->isVirtual() && (!$ship_method || !$rate))
+ Mage::throwException($helper->__('Please specify a shipping method.'));
+ }
+
+ $addrValidator = Mage::getSingleton('onepagecheckout/type_geo')->validateAddress($this->getQuote()->getBillingAddress());
+
+ if ($addrValidator !== true)
+ Mage::throwException($helper->__('Please check billing address information. %s', implode(' ', $addrValidator)));
+
+ if (!($this->getQuote()->getPayment()->getMethod()))
+ Mage::throwException($helper->__('Please select a valid payment method.'));
+
+ return $this;
+ }
+}
850 app/code/local/DeivisonArthur/OnepageCheckout/Model/Type/Geo.php
@@ -0,0 +1,850 @@
+<?php
+
+include_once(Mage::getBaseDir('lib')."/MaxMind/GeoIP/geoip.inc");
+include_once(Mage::getBaseDir('lib')."/MaxMind/GeoIP/geoipcity.inc");
+include_once(Mage::getBaseDir('lib')."/MaxMind/GeoIP/geoipregionvars.php");
+
+class DeivisonArthur_OnepageCheckout_Model_Type_Geo
+{
+ const CUSTOMER = 'customer';
+ const GUEST = 'guest';
+ const REGISTER = 'register';
+
+ protected $_help_obj;
+ protected $_quote_obj;
+ private $_em_ex_msg = '';
+ protected $_cust_sess;
+ protected $_check_sess;
+
+ public function __construct()
+ {
+ $this->_help_obj = Mage::helper('checkout');
+ $this->_em_ex_msg = $this->_help_obj->__('This email adress is already registered. Please enter another email to register account or login using this email.');
+ $this->_check_sess = Mage::getSingleton('checkout/session');
+ $this->_quote_obj = $this->_check_sess->getQuote();
+
+ $this->_cust_sess = Mage::getSingleton('customer/session');
+ }
+
+ public function getQuote()
+ {
+ return $this->_quote_obj;
+ }
+
+ public function getCustomerSession()
+ {
+ return $this->_cust_sess;
+ }
+
+ public function getCheckout()
+ {
+ return $this->_check_sess;
+ }
+
+ protected function _PaymentMethodAllowed($pmnt_method)
+ {
+ if ($pmnt_method->canUseForCountry($this->getQuote()->getBillingAddress()->getCountry()))
+ {
+ $grand_total= $this->getQuote()->getBaseGrandTotal();
+ $min = $pmnt_method->getConfigData('min_order_total');
+ $max = $pmnt_method->getConfigData('max_order_total');
+
+ if((!empty($max) && ($grand_total > $max)) || (!empty($min) && ($grand_total < $min)))
+ return false;
+
+ return true;
+ }
+ else
+ return false;
+ }
+
+ public function initDefaultData()
+ {
+ $base_info = $this->_baseData();
+
+ if (!$this->getQuote()->getBillingAddress()->getCountryId())
+ {
+ $result = $this->saveBilling(array(
+ 'country_id' => $base_info['billing']['country_id'],
+ 'region_id' => $base_info['billing']['region_id'],
+ 'city' => $base_info['billing']['city'],
+ 'postcode' => $base_info['billing']['postcode'],
+ 'use_for_shipping' => $base_info['equal'],
+ 'register_account' => 0
+ ), false, false);
+ }
+
+ if (!$this->getQuote()->getShippingAddress()->getCountryId()) {
+ if (!$base_info['equal']) {
+ $result = $this->saveShipping(array(
+ 'country_id' => $base_info['shipping']['country_id'],
+ 'region_id' => $base_info['shipping']['region_id'],
+ 'city' => $base_info['shipping']['city'],
+ 'postcode' => $base_info['shipping']['postcode']
+ ), false, false);
+ }
+ }
+
+ $this->getQuote()->collectTotals()->save();
+
+ $this->usePayment();
+ $this->useShipping();
+
+ return $this;
+ }
+
+ private function _baseData()
+ {
+ $result = array(
+ 'shipping' => array(
+ 'country_id' => null,
+ 'city' => null,
+ 'region_id' => null,
+ 'postcode' => null
+ ),
+ 'billing' => array(
+ 'country_id' => null,
+ 'city' => null,
+ 'region_id' => null,
+ 'postcode' => null
+ ),
+ 'equal' => true
+ );
+
+ $customer = Mage::getSingleton('customer/session')->getCustomer();
+ $addresses = $customer->getAddresses();
+
+ if (!$customer || !$addresses)
+ {
+ $result['equal'] = true;
+
+ if (Mage::getStoreConfig('onepagecheckout/geo_ip/country'))
+ {
+ $geoip = geoip_open(Mage::getBaseDir('lib').DS.'MaxMind/GeoIP/data/'.Mage::getStoreConfig('onepagecheckout/geo_ip/country_file'),GEOIP_STANDARD);
+ $country_id = geoip_country_code_by_addr($geoip, Mage::helper('core/http')->getRemoteAddr());
+ $result['shipping']['country_id'] = $country_id;
+ $result['billing']['country_id'] = $country_id;
+ geoip_close($geoip);
+ }
+
+ if (Mage::getStoreConfig('onepagecheckout/geo_ip/city'))
+ {
+ $geoip = geoip_open(Mage::getBaseDir('lib').DS.'MaxMind/GeoIP/data/'.Mage::getStoreConfig('onepagecheckout/geo_ip/city_file'),GEOIP_STANDARD);
+ $record = geoip_record_by_addr($geoip, Mage::helper('core/http')->getRemoteAddr());
+ $result['shipping']['city'] = $record->city;
+ $result['billing']['city'] = $record->city;
+ $result['shipping']['postcode'] = $record->postal_code;
+ $result['billing']['postcode'] = $record->postal_code;
+ geoip_close($geoip);
+ }
+
+ if (empty($result['shipping']['country_id']))
+ {
+ $country_id = Mage::getStoreConfig('onepagecheckout/general/country');
+ $result['shipping']['country_id'] = $country_id;
+ $result['billing']['country_id'] = $country_id;
+ }
+ }
+ else
+ {
+ $bill_addr = $customer->getPrimaryBillingAddress();
+ if (!$bill_addr)
+ {
+ foreach ($addresses as $address) {
+ $bill_addr = $address;
+ break;
+ }
+ }
+
+ $ship_addr = $customer->getPrimaryShippingAddress();
+ if (!$ship_addr)
+ {
+ foreach ($addresses as $address)
+ {
+ $ship_addr = $address;
+ break;
+ }
+ }
+
+ $result['shipping']['country_id'] = $ship_addr->getCountryId();
+ $result['billing']['country_id'] = $bill_addr->getCountryId();
+ $eq = false;
+ if($ship_addr->getId() === $bill_addr->getId())
+ $eq = true;
+ $result['equal'] = $eq;
+ }
+
+ return $result;
+ }
+
+ public function initCheckout()
+ {
+ $checkout = $this->getCheckout();
+ $cust_sess = $this->getCustomerSession();
+
+ if ($this->getQuote()->getIsMultiShipping()) {
+ $this->getQuote()->setIsMultiShipping(false);
+ $this->getQuote()->save();
+ }
+
+ $customer = $cust_sess->getCustomer();
+ if ($customer)
+ $this->getQuote()->assignCustomer($customer);
+
+ return $this;
+ }
+
+ public function usePayment($method_code = null)
+ {
+ $store = null;
+ if($this->getQuote())
+ $store = $this->getQuote()->getStoreId();
+
+ $methods = Mage::helper('payment')->getStoreMethods($store, $this->getQuote());
+
+ $payments = array();
+ foreach ($methods as $method)
+ {
+ if ($this->_PaymentMethodAllowed($method))
+ $payments[] = $method;
+ }
+
+ $cp = count($payments);
+ if ($cp == 0)
+ {
+ $this->getQuote()->removePayment();
+ }
+ elseif ($cp == 1)
+ {
+ $payment = $this->getQuote()->getPayment();
+ $payment->setMethod($payments[0]->getCode());
+ $method = $payment->getMethodInstance();
+ $method->assignData(array('method' => $payments[0]->getCode()));
+ }
+ else
+ {
+ $exist = false;
+ if (!$method_code)
+ {
+ if ($this->getQuote()->isVirtual())
+ $method_code = $this->getQuote()->getBillingAddress()->getPaymentMethod();
+ else
+ $method_code = $this->getQuote()->getShippingAddress()->getPaymentMethod();
+ }
+
+ if($method_code)
+ {
+ foreach ($payments as $payment)
+ {
+ if ($method_code !== $payment->getCode())
+ continue;
+
+ $payment = $this->getQuote()->getPayment();
+ $payment->setMethod($method_code);
+ $method = $payment->getMethodInstance();
+ $method->assignData(array('method' => $method_code));
+ $exist = true;
+ break;
+ }
+ }
+ if (!$method_code || !$exist)
+ {
+ $method_code = Mage::getStoreConfig('onepagecheckout/general/payment_method');
+ foreach ($payments as $payment)
+ {
+ if ($method_code !== $payment->getCode())
+ continue;
+
+ $payment = $this->getQuote()->getPayment();
+ $payment->setMethod($method_code);
+ $method = $payment->getMethodInstance();
+ $method->assignData(array('method' => $method_code));
+ $exist = true;
+ break;
+ }
+ }
+ if (!$exist)
+ $this->getQuote()->removePayment();
+ }
+
+ return $this;
+ }
+
+ public function useShipping($method_code = null)
+ {
+ $rates = Mage::getModel('sales/quote_address_rate')->getCollection()->setAddressFilter($this->getQuote()->getShippingAddress()->getId())->toArray();
+
+ $cr = count($rates['items']);
+ if (!$cr)
+ {
+ $this->getQuote()->getShippingAddress()->setShippingMethod(false);
+ }
+ elseif ($cr == 1)
+ {
+ $this->getQuote()->getShippingAddress()->setShippingMethod($rates['items'][0]['code']);
+ }
+ else
+ {
+ $exist = false;
+ if (!$method_code)
+ $method_code = $this->getQuote()->getShippingAddress()->getShippingMethod();
+
+ if ($method_code)
+ {
+ foreach ($rates['items'] as $rate)
+ {
+ if ($method_code === $rate['code'])
+ {
+ $this->getQuote()->getShippingAddress()->setShippingMethod($method_code);
+ $exist = true;
+ break;
+ }
+ }
+ }
+
+ if (!$exist || !$method_code)
+ {
+ $method_code = Mage::getStoreConfig('onepagecheckout/general/shipping_method');
+ foreach ($rates['items'] as $rate)
+ {
+ if ($method_code === $rate['code'])
+ {
+ $this->getQuote()->getShippingAddress()->setShippingMethod($method_code);
+ $exist = true;
+ break;
+ }
+ }
+ }
+ if (!$exist)
+ $this->getQuote()->getShippingAddress()->setShippingMethod(false);
+ }
+ return $this;
+ }
+
+ public function getAddress($addr_id)
+ {
+ $address = Mage::getModel('customer/address')->load((int)$addr_id);
+ $address->explodeStreetAddress();
+ if ($address->getRegionId())
+ $address->setRegion($address->getRegionId());
+ return $address;
+ }
+
+ public function getCheckoutMethod()
+ {
+ if ($this->getCustomerSession()->isLoggedIn())
+ return self::CUSTOMER;
+
+ if (!$this->getQuote()->getCheckoutMethod())
+ {
+ if (Mage::helper('onepagecheckout')->isGuestCheckoutAllowed())
+ $this->getQuote()->setCheckoutMethod(self::GUEST);
+ else
+ $this->getQuote()->setCheckoutMethod(self::REGISTER);
+ }
+ return $this->getQuote()->getCheckoutMethod();
+ }
+
+ public function saveCheckoutMethod($method)
+ {
+ if (empty($method))
+ return array('error' => -1, 'message' => $this->_help_obj->__('Invalid data.'));
+
+ $this->getQuote()->setCheckoutMethod($method)->save();
+ return array();
+ }
+
+ public function saveShippingMethod($ship_method)
+ {
+ if (empty($ship_method))
+ return array( 'message' => $this->_help_obj->__('Invalid shipping method.'), 'error' => -1);
+
+ $rate = $this->getQuote()->getShippingAddress()->getShippingRateByCode($ship_method);
+ if (!$rate)
+ return array('message' => $this->_help_obj->__('Invalid shipping method.'), 'error' => -1);
+
+ $this->getQuote()->getShippingAddress()->setShippingMethod($ship_method);
+ $this->getQuote()->collectTotals()->save();
+ return array();
+ }
+
+ public function saveBilling($data, $cust_addr_id, $validate = true)
+ {
+ if (empty($data))
+ return array('error' => -1, 'message' => $this->_help_obj->__('Invalid data.'));
+
+ $address = $this->getQuote()->getBillingAddress();
+ if (!empty($cust_addr_id))
+ {
+ $cust_addr = Mage::getModel('customer/address')->load($cust_addr_id);
+ if ($cust_addr->getId())
+ {
+ if ($cust_addr->getCustomerId() != $this->getQuote()->getCustomerId())
+ return array('error' => 1, 'message' => $this->_help_obj->__('Customer Address is not valid.'));
+
+ $address->importCustomerAddress($cust_addr);
+ }
+ }
+ else
+ {
+ unset($data['address_id']);
+ $address->addData($data);
+ }
+
+ if($validate)
+ {
+ $val_results = $this->validateAddress($address);
+ if ($val_results !== true)
+ return array('error' => 1, 'message' => $val_results);
+ }
+
+ if (isset($data['register_account']) && $data['register_account'])
+ $this->getQuote()->setCheckoutMethod(self::REGISTER);
+ else if ($this->getCustomerSession()->isLoggedIn())
+ $this->getQuote()->setCheckoutMethod(self::CUSTOMER);
+ else
+ $this->getQuote()->setCheckoutMethod(self::GUEST);
+
+ if($validate)
+ {
+ if (!$this->getQuote()->getCustomerId() && (self::REGISTER == $this->getQuote()->getCheckoutMethod()))
+ {
+ if ($this->_customerEmailExists($address->getEmail(), Mage::app()->getWebsite()->getId()))
+ return array('error' => 1, 'message' => $this->_em_ex_msg);
+ }
+ }
+
+ $address->implodeStreetAddress();
+
+ if (!$this->getQuote()->isVirtual())
+ {
+ $ufs = 0;
+ if(isset($data['use_for_shipping']))
+ $ufs = (int) $data['use_for_shipping'];
+
+ switch($ufs)
+ {
+ case 0:
+ $ship = $this->getQuote()->getShippingAddress();
+ $ship->setSameAsBilling(0);
+ break;
+ case 1:
+ $bill = clone $address;
+ $bill->unsAddressId()->unsAddressType();
+ $ship = $this->getQuote()->getShippingAddress();
+ $ship_method = $ship->getShippingMethod();
+ $ship->addData($bill->getData());
+ $ship->setSameAsBilling(1)->setShippingMethod($ship_method)->setCollectShippingRates(true);
+ break;
+ }
+ }
+
+ if ($validate){
+ $result = $this->_processValidateCustomer($address);
+ if($result !== true)
+ return $result;
+ }
+
+ // fixed by Alex Calko for saving data to define property shipping method
+ $this->getQuote()->collectTotals()->save();
+
+ return array();
+ }
+
+ public function saveShipping($data, $cust_addr_id, $validate = true)
+ {
+ if (empty($data))
+ return array('message' => $this->_help_obj->__('Invalid data.'), 'error' => -1);
+
+ $address = $this->getQuote()->getShippingAddress();
+
+ if (empty($cust_addr_id))
+ {
+ unset($data['address_id']);
+ $address->addData($data);
+ }
+ else
+ {
+ $cust_addr = Mage::getModel('customer/address')->load($cust_addr_id);
+ if ($cust_addr->getId())
+ {
+ if ($this->getQuote()->getCustomerId() != $cust_addr->getCustomerId())
+ return array('message' => $this->_help_obj->__('Customer Address is not valid.'), 'error' => 1);
+
+ $address->importCustomerAddress($cust_addr);
+ }
+ }
+
+ $address->implodeStreetAddress();
+ $address->setCollectShippingRates(true);
+
+ if ($validate)
+ {
+ $val_result = $this->validateAddress($address);
+ if($val_result !== true)
+ return array('message' => $val_result, 'error' => 1);
+ }
+
+ // fixed by Alex Calko for saving data to define property shipping method
+ $this->getQuote()->collectTotals()->save();
+
+ return array();
+ }
+
+ public function savePayment($data)
+ {
+ if (empty($data))
+ return array('message' => $this->_help_obj->__('Invalid data.'), 'error' => -1);
+
+ if (!$this->getQuote()->isVirtual())
+ $this->getQuote()->getShippingAddress()->setPaymentMethod(isset($data['method']) ? $data['method'] : null);
+ else
+ $this->getQuote()->getBillingAddress()->setPaymentMethod(isset($data['method']) ? $data['method'] : null);
+
+ $payment = $this->getQuote()->getPayment();
+ $payment->importData($data);
+ $this->getQuote()->save();
+
+ return array();
+ }
+
+ protected function _processValidateCustomer(Mage_Sales_Model_Quote_Address $address)
+ {
+ if ($address->getGender())
+ $this->getQuote()->setCustomerGender($address->getGender());
+
+ $dob = '';
+ if ($address->getDob()) {
+ $dob = Mage::app()->getLocale()->date($address->getDob(), null, null, false)->toString('yyyy-MM-dd');
+ $this->getQuote()->setCustomerDob($dob);
+ }
+
+ if ($address->getTaxvat())
+ $this->getQuote()->setCustomerTaxvat($address->getTaxvat());
+
+ if ($this->getQuote()->getCheckoutMethod() == self::REGISTER)
+ {
+ $customer = Mage::getModel('customer/customer');
+ $this->getQuote()->setPasswordHash($customer->encryptPassword($address->getCustomerPassword()));
+
+ $cust_data = array(
+ 'email' => 'email',
+ 'password' => 'customer_password',
+ 'confirmation' => 'confirm_password',
+ 'firstname' => 'firstname',
+ 'lastname' => 'lastname',
+ 'gender' => 'gender',
+ 'taxvat' => 'taxvat');
+
+ foreach ($cust_data as $key => $value)
+ $customer->setData($key, $address->getData($value));
+
+ if ($dob)
+ $customer->setDob($dob);
+
+ $val_result = $customer->validate();
+ if ($val_result !== true && is_array($val_result))
+ return array('message' => implode(', ', $val_result), 'error' => -1);
+ }
+ elseif($this->getQuote()->getCheckoutMethod() == self::GUEST)
+ {
+ $email = $address->getData('email');
+ if (!Zend_Validate::is($email, 'EmailAddress'))
+ return array('message' => $this->_help_obj->__('Invalid email address "%s"', $email), 'error' => -1);
+ }
+
+ return true;
+ }
+
+ public function validate()
+ {
+ $quote = $this->getQuote();
+ if ($quote->getIsMultiShipping())
+ Mage::throwException($this->_help_obj->__('Invalid checkout type.'));
+
+ if (!Mage::helper('onepagecheckout')->isGuestCheckoutAllowed() && $quote->getCheckoutMethod() == self::GUEST)
+ Mage::throwException($this->_help_obj->__('Sorry, guest checkout is not allowed, please contact support.'));
+ }
+
+ public function saveOrder()
+ {
+ $info = Mage::getVersionInfo();
+ $version = "{$info['major']}.{$info['minor']}.{$info['revision']}.{$info['patch']}";
+
+ $this->validate();
+ $newCustomer = false;
+ switch ($this->getCheckoutMethod())
+ {
+ case self::GUEST:
+ $this->_prepareGuestQuote();
+ break;
+ case self::REGISTER:
+ $this->_prepareNewCustomerQuote();
+ $newCustomer = true;
+ break;
+ default:
+ $this->_prepareCustomerQuote();
+ break;
+ }
+
+ $service_quote = Mage::getModel('onepagecheckout/service_quote', $this->getQuote());
+ if($version == '1.4.0.1')
+ $order = $service_quote->submit();
+ else
+ {
+ $order = $service_quote->submitAll();
+ $order = $service_quote->getOrder();
+ }
+
+ if ($newCustomer)
+ {
+ try {
+ $this->_involveNewCustomer();
+ } catch (Exception $e) {
+ Mage::logException($e);
+ }
+ }
+
+ if($version != '1.4.0.1')
+ {
+ $this->getCheckout()->setLastQuoteId($this->getQuote()->getId())
+ ->setLastSuccessQuoteId($this->getQuote()->getId())
+ ->clearHelperData();
+ }
+
+ if ($order)
+ {
+ Mage::dispatchEvent('checkout_type_onepage_save_order_after', array('order'=>$order, 'quote'=>$this->getQuote()));
+ $r_url = $this->getQuote()->getPayment()->getOrderPlaceRedirectUrl();
+ if(!$r_url)
+ {
+ try {
+ $order->sendNewOrderEmail();
+ } catch (Exception $e) {
+ Mage::logException($e);
+ }
+ }
+
+ if($version == '1.4.0.1')
+ {
+ $this->getCheckout()->setLastQuoteId($this->getQuote()->getId())->setLastOrderId($order->getId())->setLastRealOrderId($order->getIncrementId())->setRedirectUrl($r_url)->setLastSuccessQuoteId($this->getQuote()->getId());
+ }
+ else
+ {
+ $this->getCheckout()->setLastOrderId($order->getId())->setRedirectUrl($r_url)->setLastRealOrderId($order->getIncrementId());
+
+ $agree = $order->getPayment()->getBillingAgreement();
+ if ($agree)
+ $this->getCheckout()->setLastBillingAgreementId($agree->getId());
+ }
+ }
+
+ if($version != '1.4.0.1')
+ {
+ $profiles = $service_quote->getRecurringPaymentProfiles();
+ if ($profiles)
+ {
+ $ids = array();
+ foreach($profiles as $profile)
+ $ids[] = $profile->getId();
+
+ $this->getCheckout()->setLastRecurringProfileIds($ids);
+ }
+ }
+
+ return $this;
+ }
+
+ protected function validateOrder()
+ {
+ if ($this->getQuote()->getIsMultiShipping())
+ Mage::throwException($this->_help_obj->__('Invalid checkout type.'));
+
+ if (!$this->getQuote()->isVirtual())
+ {
+ $address = $this->getQuote()->getShippingAddress();
+ $addrVal = $this->validateAddress($address);
+ if ($addrVal !== true)
+ Mage::throwException($this->_help_obj->__('Please check shipping address.'));
+
+ $method= $address->getShippingMethod();
+ $rate = $address->getShippingRateByCode($method);
+ if (!$this->getQuote()->isVirtual() && (!$method || !$rate))
+ Mage::throwException($this->_help_obj->__('Please specify shipping method.'));
+ }
+
+ $addrVal = $this->validateAddress($this->getQuote()->getBillingAddress());
+ if ($addrVal !== true)
+ Mage::throwException($this->_help_obj->__('Please check billing address.'));
+
+ if (!($this->getQuote()->getPayment()->getMethod()))
+ Mage::throwException($this->_help_obj->__('Please select valid payment method.'));
+ }
+
+ public function getLastOrderId()
+ {
+ $lo = $this->getCheckout()->getLastOrderId();
+ $order_id = false;
+ if ($lo)
+ {
+ $order = Mage::getModel('sales/order');
+ $order->load($lo);
+ $order_id = $order->getIncrementId();
+ }
+ return $order_id;
+ }
+
+ public function validateAddress($address)
+ {
+ $errors = array();
+ $helper = Mage::helper('customer');
+ $address->implodeStreetAddress();
+ $a_form = Mage::getStoreConfig('onepagecheckout/address_form');
+
+ if (!Zend_Validate::is($address->getFirstname(), 'NotEmpty'))
+ $errors[] = $helper->__('Please enter the first name.');
+
+ if (!Zend_Validate::is($address->getLastname(), 'NotEmpty'))
+ $errors[] = $helper->__('Please enter the last name.');
+
+ if ($a_form['company'] === 'required' && !Zend_Validate::is($address->getCompany(), 'NotEmpty'))
+ $errors[] = $helper->__('Please enter the company.');
+
+ if ($a_form['state'] === 'required' && $address->getCountryModel()->getRegionCollection()->getSize() && !Zend_Validate::is($address->getRegionId(), 'NotEmpty'))
+ $errors[] = $helper->__('Please enter the state/province.');
+
+ if ($a_form['address'] === 'required' && !Zend_Validate::is($address->getStreet(1), 'NotEmpty'))
+ $errors[] = $helper->__('Please enter the street.');
+
+ if ($a_form['city'] === 'required' && !Zend_Validate::is($address->getCity(), 'NotEmpty'))
+ $errors[] = $helper->__('Please enter the city.');
+
+ $_opt_zip = Mage::helper('directory')->getCountriesWithOptionalZip();
+ if ($a_form['zip'] === 'required' && !in_array($address->getCountryId(), $_opt_zip) && !Zend_Validate::is($address->getPostcode(), 'NotEmpty'))
+ $errors[] = $helper->__('Please enter the zip code.');
+
+ if ($a_form['phone'] === 'required' && !Zend_Validate::is($address->getTelephone(), 'NotEmpty'))
+ $errors[] = $helper->__('Please enter the phone number.');
+
+ if ($a_form['fax'] === 'required' && !Zend_Validate::is($address->getFax(), 'NotEmpty'))
+ $errors[] = $helper->__('Please enter the fax.');
+
+ if ($a_form['country'] === 'required' && !Zend_Validate::is($address->getCountryId(), 'NotEmpty'))
+ $errors[] = $helper->__('Please choose the country.');
+
+ if (empty($errors) || $address->getShouldIgnoreValidation())
+ return true;
+
+ return $errors;
+ }
+
+ protected function _prepareNewCustomerQuote()
+ {
+ $bill = $this->getQuote()->getBillingAddress();
+ $ship = null;
+ if(!$this->getQuote()->isVirtual())
+ $ship = $this->getQuote()->getShippingAddress();
+
+ $customer = $this->getQuote()->getCustomer();
+ $cust_bill = $bill->exportCustomerAddress();
+ $customer->addAddress($cust_bill);
+ $bill->setCustomerAddress($cust_bill);
+ $cust_bill->setIsDefaultBilling(true);
+ if($ship)
+ {
+ if(!$ship->getSameAsBilling())
+ {
+ $cust_ship = $ship->exportCustomerAddress();
+ $customer->addAddress($cust_ship);
+ $ship->setCustomerAddress($cust_ship);
+ $cust_ship->setIsDefaultShipping(true);
+ }
+ else
+ $cust_bill->setIsDefaultShipping(true);
+ }
+
+ if (!$bill->getCustomerGender() && $this->getQuote()->getCustomerGender())
+ $bill->setCustomerGender($this->getQuote()->getCustomerGender());
+
+ if (!$bill->getCustomerDob() && $this->getQuote()->getCustomerDob())
+ $bill->setCustomerDob($this->getQuote()->getCustomerDob());
+
+ if (!$bill->getCustomerTaxvat() && $this->getQuote()->getCustomerTaxvat())
+ $bill->setCustomerTaxvat($this->getQuote()->getCustomerTaxvat());
+
+ Mage::helper('core')->copyFieldset('checkout_onepage_billing', 'to_customer', $bill, $customer);
+
+ $customer->setPassword($customer->decryptPassword($this->getQuote()->getPasswordHash()));
+ $customer->setPasswordHash($customer->hashPassword($customer->getPassword()));
+ $this->getQuote()->setCustomer($customer)->setCustomerId(true);
+ }
+
+ protected function _prepareCustomerQuote()
+ {
+ $bill = $this->getQuote()->getBillingAddress();
+ $ship = null;
+ if(!$this->getQuote()->isVirtual())
+ $ship = $this->getQuote()->getShippingAddress();
+
+ $customer = $this->getCustomerSession()->getCustomer();
+ if (!$bill->getCustomerId() || $bill->getSaveInAddressBook())
+ {
+ $cust_bill = $bill->exportCustomerAddress();
+ $customer->addAddress($cust_bill);
+ $bill->setCustomerAddress($cust_bill);
+ }
+ if ($ship && (($ship->getSaveInAddressBook() && !$ship->getSameAsBilling()) || (!$ship->getSameAsBilling() && !$ship->getCustomerId())))
+ {
+ $cust_ship = $ship->exportCustomerAddress();
+ $customer->addAddress($cust_ship);
+ $ship->setCustomerAddress($cust_ship);
+ }
+
+ if (isset($cust_bill) && !$customer->getDefaultBilling())
+ $cust_bill->setIsDefaultBilling(true);
+
+ if ($ship && isset($cust_ship) && !$customer->getDefaultShipping())
+ $cust_ship->setIsDefaultShipping(true);
+ elseif (isset($cust_bill) && !$customer->getDefaultShipping())
+ $cust_bill->setIsDefaultShipping(true);
+
+ $this->getQuote()->setCustomer($customer);
+ }
+
+ protected function _prepareGuestQuote()
+ {
+ $quote = $this->getQuote();
+ $quote->setCustomerId(null)->setCustomerEmail($quote->getBillingAddress()->getEmail())->setCustomerIsGuest(true)->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
+ return $this;
+ }
+
+ protected function _involveNewCustomer()
+ {
+ $customer = $this->getQuote()->getCustomer();
+ if ($customer->isConfirmationRequired())
+ {
+ $customer->sendNewAccountEmail('confirmation');
+ $url = Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail());
+ $this->getCustomerSession()->addSuccess(Mage::helper('customer')->__('Account confirmation is required. Please, check your email for confirmation link. <a href="%s">Click here</a> to resend confirmation email.', $url));
+ }
+ else
+ {
+ $customer->sendNewAccountEmail();
+ $this->getCustomerSession()->loginById($customer->getId());
+ }
+ return $this;
+ }
+
+ protected function _customerEmailExists($email, $web_id = null)
+ {
+ $customer = Mage::getModel('customer/customer');
+ if ($web_id)
+ $customer->setWebsiteId($web_id);
+
+ $customer->loadByEmail($email);
+ if ($customer->getId())
+ return $customer;
+
+ return false;
+ }
+}
659 app/code/local/DeivisonArthur/OnepageCheckout/controllers/IndexController.php
@@ -0,0 +1,659 @@
+<?php
+class DeivisonArthur_OnepageCheckout_IndexController extends Mage_Checkout_Controller_Action
+{
+ private $_current_layout = null;
+
+ protected $_sectionUpdateFunctions = array(
+ 'review' => '_getReviewHtml',
+ 'shipping-method' => '_getShippingMethodsHtml',
+ 'payment-method' => '_getPaymentMethodsHtml',
+ );
+
+ public function preDispatch()
+ {
+ parent::preDispatch();
+ $this->_preDispatchValidateCustomer();
+ return $this;
+ }
+
+ protected function _ajaxRedirectResponse()
+ {
+ $this->getResponse()
+ ->setHeader('HTTP/1.1', '403 Session Expired')
+ ->setHeader('Login-Required', 'true')
+ ->sendResponse();
+ return $this;
+ }
+
+ protected function _expireAjax()
+ {
+ if (!$this->getOnepagecheckout()->getQuote()->hasItems()
+ || $this->getOnepagecheckout()->getQuote()->getHasError()
+ || $this->getOnepagecheckout()->getQuote()->getIsMultiShipping()) {
+ $this->_ajaxRedirectResponse();
+ return true;
+ }
+ $action = $this->getRequest()->getActionName();
+ if (Mage::getSingleton('checkout/session')->getCartWasUpdated(true)
+ && !in_array($action, array('index', 'progress'))) {
+ $this->_ajaxRedirectResponse();
+ return true;
+ }
+
+ return false;
+ }
+
+ protected function _getUpdatedLayout()
+ {$this->_initLayoutMessages('checkout/session');
+ if ($this->_current_layout === null)
+ {
+ $layout = $this->getLayout();
+ $update = $layout->getUpdate();
+ $update->load('onepagecheckout_index_updatecheckout');
+
+ $layout->generateXml();
+ $layout->generateBlocks();
+ $this->_current_layout = $layout;
+ }
+
+ return $this->_current_layout;
+ }
+
+ protected function _getShippingMethodsHtml()
+ {
+ $layout = $this->_getUpdatedLayout();
+ return $layout->getBlock('checkout.shipping.method')->toHtml();
+ }
+
+ protected function _getPaymentMethodsHtml()
+ {
+ $layout = $this->_getUpdatedLayout();
+ return $layout->getBlock('checkout.payment.method')->toHtml();
+ }
+
+ protected function _getCouponDiscountHtml()
+ {
+ $layout = $this->_getUpdatedLayout();
+ return $layout->getBlock('checkout.cart.coupon')->toHtml();
+ }
+
+ protected function _getReviewHtml()
+ {
+ $layout = $this->_getUpdatedLayout();
+ return $layout->getBlock('checkout.review')->toHtml();
+ }
+
+ public function getOnepagecheckout()
+ {
+ return Mage::getSingleton('onepagecheckout/type_geo');
+ }
+
+ public function indexAction()
+ {
+ if (!Mage::helper('onepagecheckout')->isOnepageCheckoutEnabled())
+ {
+ Mage::getSingleton('checkout/session')->addError($this->__('The one page checkout is disabled.'));
+ $this->_redirect('checkout/cart');
+ return;
+ }
+
+ $quote = $this->getOnepagecheckout()->getQuote();
+ if (!$quote->hasItems() || $quote->getHasError()) {
+ $this->_redirect('checkout/cart');
+ return;
+ }
+ if (!$quote->validateMinimumAmount()) {
+ $error = Mage::getStoreConfig('sales/minimum_order/error_message');
+ Mage::getSingleton('checkout/session')->addError($error);
+ $this->_redirect('checkout/cart');
+ return;
+ }
+
+ Mage::getSingleton('checkout/session')->setCartWasUpdated(false);
+ Mage::getSingleton('customer/session')->setBeforeAuthUrl(Mage::getUrl('*/*/*', array('_secure'=>true)));
+
+ $this->getOnepagecheckout()->initDefaultData()->initCheckout();
+ $this->loadLayout();
+ $this->_initLayoutMessages('customer/session');
+ $title = Mage::getStoreConfig('onepagecheckout/general/title');
+ $this->getLayout()->getBlock('head')->setTitle($title);
+ $this->renderLayout();
+ }
+
+ public function successAction()
+ {
+ $notallowed = $this->getRequest()->getParam('na', false);
+ if($notallowed)
+ {
+ $this->_redirect('checkout/onepage');
+ return;
+ }
+
+ $session = $this->getOnepagecheckout()->getCheckout();
+ if (!$session->getLastSuccessQuoteId()) {
+ $this->_redirect('checkout/cart');
+ return;
+ }
+
+ $lastQuoteId = $session->getLastQuoteId();
+ $lastOrderId = $session->getLastOrderId();
+ $lastRecurringProfiles = $session->getLastRecurringProfileIds();
+ if (!$lastQuoteId || (!$lastOrderId && empty($lastRecurringProfiles))) {
+ $this->_redirect('checkout/cart');
+ return;
+ }
+
+ $session->clear();
+ $this->loadLayout();
+ $this->_initLayoutMessages('checkout/session');
+ Mage::dispatchEvent('checkout_onepage_controller_success_action', array('order_ids' => array($lastOrderId)));
+ $this->renderLayout();
+ }
+
+ public function failureAction()
+ {
+ $lastQuoteId = $this->getOnepagecheckout()->getCheckout()->getLastQuoteId();
+ $lastOrderId = $this->getOnepagecheckout()->getCheckout()->getLastOrderId();
+
+ if (!$lastQuoteId || !$lastOrderId) {
+ $this->_redirect('checkout/cart');
+ return;
+ }
+
+ $this->loadLayout();
+ $this->renderLayout();
+ }
+
+ public function getAddressAction()
+ {
+ if ($this->_expireAjax()) {
+ return;
+ }
+ $addressId = $this->getRequest()->getParam('address', false);
+ if ($addressId) {
+ $address = $this->getOnepagecheckout()->getAddress($addressId);
+
+ if (Mage::getSingleton('customer/session')->getCustomer()->getId() == $address->getCustomerId()) {
+ $this->getResponse()->setHeader('Content-type', 'application/x-json');
+ $this->getResponse()->setBody($address->toJson());
+ } else {
+ $this->getResponse()->setHeader('HTTP/1.1','403 Forbidden');
+ }
+ }
+ }
+
+ public function updateCheckoutAction()
+ {
+ if ($this->_expireAjax() || !$this->getRequest()->isPost()) {
+ return;
+ }
+ /*********** DISCOUNT CODES **********/
+
+ $quote = $this->getOnepagecheckout()->getQuote();
+ $couponData = $this->getRequest()->getPost('coupon', array());
+ $processCoupon = $this->getRequest()->getPost('process_coupon', false);
+
+ $couponChanged = false;
+ if ($couponData && $processCoupon) {
+ if (!empty($couponData['remove'])) {
+ $couponData['code'] = '';
+
+ }
+ $oldCouponCode = $quote->getCouponCode();
+ if ($oldCouponCode != $couponData['code']) {
+ try {
+ $quote->setCouponCode(
+ strlen($couponData['code']) ? $couponData['code'] : ''
+ );
+ $this->getRequest()->setPost('payment-method', true);
+ $this->getRequest()->setPost('shipping-method', true);
+ if ($couponData['code']) {
+ $couponChanged = true;
+ } else {
+ $couponChanged = true;
+ Mage::getSingleton('checkout/session')->addSuccess($this->__('Coupon code was canceled.'));
+ }
+ } catch (Mage_Core_Exception $e) {
+ $couponChanged = true;
+ Mage::getSingleton('checkout/session')->addError($e->getMessage());
+ } catch (Exception $e) {
+ $couponChanged = true;
+ Mage::getSingleton('checkout/session')->addError($this->__('Cannot apply the coupon code.'));
+ }
+
+ }
+ }
+
+ /***********************************/
+
+ $bill_data = $this->getRequest()->getPost('billing', array());
+ $bill_data = $this->_filterPostData($bill_data);
+ $bill_addr_id = $this->getRequest()->getPost('billing_address_id', false);
+ $result = array();
+ $ship_updated = false;
+
+ if ($this->_checkChangedAddress($bill_data, 'Billing', $bill_addr_id) || $this->getRequest()->getPost('payment-method', false))
+ {
+ if (isset($bill_data['email']))
+ {
+ $bill_data['email'] = trim($bill_data['email']);
+ }
+
+ $bill_result = $this->getOnepagecheckout()->saveBilling($bill_data, $bill_addr_id, false);
+
+ if (!isset($bill_result['error']))
+ {
+ $pmnt_data = $this->getRequest()->getPost('payment', array());
+ $this->getOnepagecheckout()->usePayment(isset($pmnt_data['method']) ? $pmnt_data['method'] : null);
+
+ $result['update_section']['payment-method'] = $this->_getPaymentMethodsHtml();
+
+ if (isset($bill_data['use_for_shipping']) && $bill_data['use_for_shipping'] == 1 && !$this->getOnepagecheckout()->getQuote()->isVirtual())
+ {
+ $result['update_section']['shipping-method'] = $this->_getShippingMethodsHtml();
+ $result['duplicateBillingInfo'] = 'true';
+
+ $ship_updated = true;
+ }
+ }
+ else
+ {
+ $result['error_messages'] = $bill_result['message'];
+ }
+ }
+
+ $ship_data = $this->getRequest()->getPost('shipping', array());
+ $ship_addr_id = $this->getRequest()->getPost('shipping_address_id', false);
+ $ship_method = $this->getRequest()->getPost('shipping_method', false);
+
+ if (!$ship_updated && !$this->getOnepagecheckout()->getQuote()->isVirtual())
+ {
+ if ($this->_checkChangedAddress($ship_data, 'Shipping', $ship_addr_id) || $ship_method)
+ {
+ $ship_result = $this->getOnepagecheckout()->saveShipping($ship_data, $ship_addr_id, false);
+
+ if (!isset($ship_result['error']))
+ {
+ $result['update_section']['shipping-method'] = $this->_getShippingMethodsHtml();
+ }
+ }
+ }
+
+ $check_shipping_diff = false;
+
+ // check how many shipping methods exist
+ $rates = Mage::getModel('sales/quote_address_rate')->getCollection()->setAddressFilter($this->getOnepagecheckout()->getQuote()->getShippingAddress()->getId())->toArray();
+ if(count($rates['items'])==1)
+ {
+ if($rates['items'][0]['code']!=$ship_method)
+ {
+ $check_shipping_diff = true;
+
+ $result['reload_totals'] = 'true';
+ }
+ }
+ else
+ $check_shipping_diff = true;
+
+// get prev shipping method
+ if($check_shipping_diff){
+ $shipping = $this->getOnepagecheckout()->getQuote()->getShippingAddress();
+ $shippingMethod_before = $shipping->getShippingMethod();
+ }
+
+ $this->getOnepagecheckout()->useShipping($ship_method);
+
+ $this->getOnepagecheckout()->getQuote()->collectTotals()->save();
+
+ if($check_shipping_diff){
+ $shipping = $this->getOnepagecheckout()->getQuote()->getShippingAddress();
+ $shippingMethod_after = $shipping->getShippingMethod();
+
+ if($shippingMethod_before != $shippingMethod_after)
+ {
+ $result['update_section']['shipping-method'] = $this->_getShippingMethodsHtml();
+ $result['reload_totals'] = 'true';
+ }
+ else
+ unset($result['reload_totals']);
+ }
+///////////////
+
+ $result['update_section']['review'] = $this->_getReviewHtml();
+
+
+ /*********** DISCOUNT CODES **********/
+ if ($couponChanged) {
+ if ($couponData['code'] == $quote->getCouponCode()) {
+ Mage::getSingleton('checkout/session')->addSuccess(
+ $this->__('Coupon code "%s" was applied.', Mage::helper('core')->htmlEscape($couponData['code']))
+ );
+ } else {
+ Mage::getSingleton('checkout/session')->addError(
+ $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->htmlEscape($couponData['code']))
+ );
+ }
+ $method = str_replace(' ', '', ucwords(str_replace('-', ' ', 'coupon-discount')));
+ $result['update_section']['coupon-discount'] = $this->{'_get' . $method . 'Html'}();
+
+ }
+ /************************************/
+
+
+
+ $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
+ }
+
+ public function forgotpasswordAction()
+ {
+ $session = Mage::getSingleton('customer/session');
+
+ if ($this->_expireAjax() || $session->isLoggedIn()) {
+ return;
+ }
+
+ $email = $this->getRequest()->getPost('email');
+ $result = array('success' => false);
+
+ if (!$email)
+ {
+ $result['error'] = Mage::helper('customer')->__('Please enter your email.');
+ }
+ else
+ {
+ if (!Zend_Validate::is($email, 'EmailAddress'))
+ {
+ $session->setForgottenEmail($email);
+ $result['error'] = Mage::helper('checkout')->__('Invalid email address.');
+ }
+ else
+ {
+ $customer = Mage::getModel('customer/customer')->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->loadByEmail($email);
+ if(!$customer->getId())
+ {
+ $session->setForgottenEmail($email);
+ $result['error'] = Mage::helper('customer')->__('This email address was not found in our records.');
+ }
+ else
+ {
+ try
+ {
+ $new_pass = $customer->generatePassword();
+ $customer->changePassword($new_pass, false);
+ $customer->sendPasswordReminderEmail();
+ $result['success'] = true;
+ $result['message'] = Mage::helper('customer')->__('A new password has been sent.');
+ }
+ catch (Exception $e)
+ {
+ $result['error'] = $e->getMessage();
+ }
+ }
+ }
+ }
+
+ $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
+ }
+
+ public function loginAction()
+ {
+ $session = Mage::getSingleton('customer/session');
+ if ($this->_expireAjax() || $session->isLoggedIn()) {
+ return;
+ }
+
+ $result = array('success' => false);
+
+ if ($this->getRequest()->isPost())
+ {
+ $login_data = $this->getRequest()->getPost('login');
+ if (empty($login_data['username']) || empty($login_data['password'])) {
+ $result['error'] = Mage::helper('customer')->__('Login and password are required.');
+ }
+ else
+ {
+ try
+ {
+ $session->login($login_data['username'], $login_data['password']);
+ $result['success'] = true;
+ $result['redirect'] = Mage::getUrl('*/*/index');
+ }
+ catch (Mage_Core_Exception $e)
+ {
+ switch ($e->getCode()) {
+ case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
+ $message = Mage::helper('customer')->__('Email is not confirmed. <a href="%s">Resend confirmation email.</a>', Mage::helper('customer')->getEmailConfirmationUrl($login_data['username']));
+ break;
+ default:
+ $message = $e->getMessage();
+ }
+ $result['error'] = $message;
+ $session->setUsername($login_data['username']);
+ }
+ }
+ }
+
+ $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
+ }
+
+ public function saveOrderAction()
+ {
+ if ($this->_expireAjax()) {
+ return;
+ }
+
+ $result = array();
+ try {
+ $bill_data = $this->_filterPostData($this->getRequest()->getPost('billing', array()));
+
+ $result = $this->getOnepagecheckout()->saveBilling($bill_data,$this->getRequest()->getPost('billing_address_id', false));
+ if ($result)
+ {
+ $result['error_messages'] = $result['message'];
+ $result['error'] = true;
+ $result['success'] = false;
+ $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
+ return;
+ }
+
+ if ((!$bill_data['use_for_shipping'] || !isset($bill_data['use_for_shipping'])) && !$this->getOnepagecheckout()->getQuote()->isVirtual())
+ {
+ $result = $this->getOnepagecheckout()->saveShipping($this->_filterPostData($this->getRequest()->getPost('shipping', array())),$this->getRequest()->getPost('shipping_address_id', false));
+ if ($result)
+ {
+ $result['error_messages'] = $result['message'];
+ $result['error'] = true;
+ $result['success'] = false;
+ $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
+ return;
+ }
+ }
+
+ $agreements = Mage::helper('onepagecheckout')->getAgreeIds();
+ if($agreements)
+ {
+ $post_agree = array_keys($this->getRequest()->getPost('agreement', array()));
+ $is_different = array_diff($agreements, $post_agree);
+ if ($is_different)
+ {
+ $result['error_messages'] = Mage::helper('checkout')->__('Please agree to all the terms and conditions.');
+ $result['error'] = true;
+ $result['success'] = false;
+
+ $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
+ return;
+ }
+ }
+
+ $result = $this->_saveOrderPurchase();
+ if($result && !isset($result['redirect']))
+ {
+ $result['error_messages'] = $result['error'];
+ }
+
+ if(!isset($result['error']))
+ {
+ Mage::dispatchEvent('checkout_controller_onepage_save_shipping_method', array('request'=>$this->getRequest(), 'quote'=>$this->getOnepagecheckout()->getQuote()));
+ $this->_subscribeNews();
+ }
+
+ Mage::getSingleton('customer/session')->setOrderCustomerComment($this->getRequest()->getPost('order-comment'));
+
+ if (!isset($result['redirect']) && !isset($result['error']))
+ {
+ $pmnt_data = $this->getRequest()->getPost('payment', false);
+ if ($pmnt_data)
+ $this->getOnepagecheckout()->getQuote()->getPayment()->importData($pmnt_data);
+
+ $this->getOnepagecheckout()->saveOrder();
+ $redirectUrl = $this->getOnepagecheckout()->getCheckout()->getRedirectUrl();
+
+ $result['success'] = true;
+ $result['error'] = false;
+ $result['order_created'] = true;
+ }
+ }
+ catch (Mage_Core_Exception $e)
+ {
+ Mage::logException($e);
+ Mage::helper('checkout')->sendPaymentFailedEmail($this->getOnepagecheckout()->getQuote(), $e->getMessage());
+
+ $result['error_messages'] = $e->getMessage();
+ $result['error'] = true;
+ $result['success'] = false;
+
+ $goto_section = $this->getOnepagecheckout()->getCheckout()->getGotoSection();
+ if ($goto_section)
+ {
+ $this->getOnepagecheckout()->getCheckout()->setGotoSection(null);
+ $result['goto_section'] = $goto_section;
+ }
+
+ $update_section = $this->getOnepagecheckout()->getCheckout()->getUpdateSection();
+ if ($update_section)
+ {
+ if (isset($this->_sectionUpdateFunctions[$update_section]))
+ {
+ $layout = $this->_getUpdatedLayout();
+
+ $updateSectionFunction = $this->_sectionUpdateFunctions[$update_section];
+ $result['update_section'] = array(
+ 'name' => $update_section,
+ 'html' => $this->$updateSectionFunction()
+ );
+ }
+ $this->getOnepagecheckout()->getCheckout()->setUpdateSection(null);
+ }
+
+ $this->getOnepagecheckout()->getQuote()->save();
+ }
+ catch (Exception $e)
+ {
+ Mage::logException($e);
+ Mage::helper('checkout')->sendPaymentFailedEmail($this->getOnepagecheckout()->getQuote(), $e->getMessage());
+ $result['error_messages'] = Mage::helper('checkout')->__('There was an error processing your order. Please contact support or try again later.');
+ $result['error'] = true;
+ $result['success'] = false;
+
+ $this->getOnepagecheckout()->getQuote()->save();
+ }
+