iqromss

Untitled

Jun 5th, 2017
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 55.86 KB | None | 0 0
  1. <?php
  2.  
  3. class TM_FireCheckout_Model_Type_Standard
  4. {
  5. /**
  6. * Checkout types: Checkout as Guest, Register, Logged In Customer
  7. */
  8. const METHOD_GUEST = 'guest';
  9. const METHOD_REGISTER = 'register';
  10. const METHOD_CUSTOMER = 'customer';
  11. // const METHOD_GUEST_CUSTOMER = 'guest_customer';
  12.  
  13. /**
  14. * Error message of "customer already exists"
  15. *
  16. * @var string
  17. */
  18. private $_customerEmailExistsMessage = '';
  19.  
  20. /**
  21. * @var Mage_Customer_Model_Session
  22. */
  23. protected $_customerSession;
  24.  
  25. /**
  26. * @var Mage_Checkout_Model_Session
  27. */
  28. protected $_checkoutSession;
  29.  
  30. /**
  31. * @var Mage_Sales_Model_Quote
  32. */
  33. protected $_quote = null;
  34.  
  35. /**
  36. * @var Mage_Checkout_Helper_Data
  37. */
  38. protected $_helper;
  39.  
  40. /**
  41. * Class constructor
  42. * Set customer already exists message
  43. */
  44. public function __construct()
  45. {
  46. $this->_helper = Mage::helper('checkout');
  47. $this->_customerEmailExistsMessage = $this->_helper->__('There is already a customer registered using this email address. Please login using this email address or enter a different email address to register your account.');
  48. $this->_checkoutSession = Mage::getSingleton('checkout/session');
  49. $this->_customerSession = Mage::getSingleton('customer/session');
  50. }
  51.  
  52. /**
  53. * Get frontend checkout session object
  54. *
  55. * @return Mage_Checkout_Model_Session
  56. */
  57. public function getCheckout()
  58. {
  59. return $this->_checkoutSession;
  60. }
  61.  
  62. /**
  63. * Quote object getter
  64. *
  65. * @return Mage_Sales_Model_Quote
  66. */
  67. public function getQuote()
  68. {
  69. if ($this->_quote === null) {
  70. return $this->_checkoutSession->getQuote();
  71. }
  72. return $this->_quote;
  73. }
  74.  
  75. /**
  76. * Declare checkout quote instance
  77. *
  78. * @param Mage_Sales_Model_Quote $quote
  79. */
  80. public function setQuote(Mage_Sales_Model_Quote $quote)
  81. {
  82. $this->_quote = $quote;
  83. return $this;
  84. }
  85.  
  86. /**
  87. * Get customer session object
  88. *
  89. * @return Mage_Customer_Model_Session
  90. */
  91. public function getCustomerSession()
  92. {
  93. return $this->_customerSession;
  94. }
  95.  
  96.  
  97. /**
  98. * Retrieve shipping and billing addresses,
  99. * and boolean flag about their equality
  100. *
  101. * For the registered customer with available addresses returns
  102. * appropriate address.
  103. * For the Guest trying to detect country with geo-ip technology
  104. *
  105. * @return array
  106. */
  107. protected function _getDefaultAddress()
  108. {
  109. $result = array(
  110. 'shipping' => array(
  111. 'country_id' => null,
  112. 'city' => null,
  113. 'region_id' => null,
  114. 'postcode' => null,
  115. 'customer_address_id' => false
  116. ),
  117. 'billing' => array(
  118. 'country_id' => null,
  119. 'city' => null,
  120. 'region_id' => null,
  121. 'postcode' => null,
  122. 'customer_address_id' => false,
  123. 'use_for_shipping' => Mage::getStoreConfig('firecheckout/general/shipping_address_checkbox_state'),
  124. 'register_account' => 0
  125. )
  126. );
  127. if (($customer = Mage::getSingleton('customer/session')->getCustomer())
  128. && ($addresses = $customer->getAddresses())) {
  129.  
  130. if (!$shippingAddress = $customer->getPrimaryShippingAddress()) {
  131. foreach ($addresses as $address) {
  132. $shippingAddress = $address;
  133. break;
  134. }
  135. }
  136. if (!$billingAddress = $customer->getPrimaryBillingAddress()) {
  137. foreach ($addresses as $address) {
  138. $billingAddress = $address;
  139. break;
  140. }
  141. }
  142. $result['shipping'] = $shippingAddress->getData();
  143. $result['shipping']['country_id'] = $shippingAddress->getCountryId();
  144. $result['shipping']['customer_address_id'] = $shippingAddress->getId();
  145. $result['billing'] = $billingAddress->getData();
  146. $result['billing']['country_id'] = $billingAddress->getCountryId();
  147. $result['billing']['customer_address_id'] = $billingAddress->getId();
  148. $result['billing']['use_for_shipping'] = $shippingAddress->getId() === $billingAddress->getId();
  149. } else if ($this->getQuote()->getShippingAddress()->getCountryId()) {
  150. // Estimated shipping cost from shopping cart
  151. $address = $this->getQuote()->getShippingAddress();
  152. $result['shipping'] = $address->getData();
  153. if (!$address->getSameAsBilling()) {
  154. $address = $this->getQuote()->getBillingAddress();
  155. $result['billing'] = $address->getData();
  156. $result['billing']['use_for_shipping'] = false;
  157. } else {
  158. $result['billing'] = $result['shipping'];
  159. $result['billing']['use_for_shipping'] = true;
  160. }
  161. } else {
  162. $detectCountry = Mage::getStoreConfig('firecheckout/geo_ip/country');
  163. $detectCity = Mage::getStoreConfig('firecheckout/geo_ip/city');
  164. if ($detectCountry || $detectCity) {
  165. $remoteAddr = Mage::helper('core/http')->getRemoteAddr();
  166. try {
  167. $data = Mage::helper('firecheckout/geoip')->detect($remoteAddr);
  168. foreach ($data as $key => $value) {
  169. $result['shipping'][$key] =
  170. $result['billing'][$key] = $value;
  171. }
  172. } catch (Exception $e) {
  173. $this->_checkoutSession->addError($e->getMessage());
  174. }
  175. }
  176.  
  177. if (empty($result['shipping']['country_id'])
  178. || !Mage::getResourceModel('directory/country_collection')
  179. ->addCountryCodeFilter($result['shipping']['country_id'])
  180. ->loadByStore()
  181. ->count()) {
  182.  
  183. $result['shipping']['country_id'] =
  184. $result['billing']['country_id'] = Mage::helper('core')->getDefaultCountry();
  185. }
  186. }
  187.  
  188. // discount (free shipping rule) matters
  189. $result['billing']['register_account'] = $this->_canUseRegistrationMode();
  190.  
  191. return $result;
  192. }
  193.  
  194. /**
  195. * Check if registration checkbox is checked
  196. *
  197. * @return boolean
  198. */
  199. protected function _canUseRegistrationMode()
  200. {
  201. $mode = Mage::getStoreConfig('firecheckout/general/registration_mode');
  202. // @todo check '?register' parameter
  203. return $mode === 'optional-checked';
  204. }
  205.  
  206. /**
  207. * @param object $method
  208. * @return boolean
  209. */
  210. protected function _canUsePaymentMethod($method)
  211. {
  212. if (!$method->canUseForCountry($this->getQuote()->getBillingAddress()->getCountry())) {
  213. return false;
  214. }
  215.  
  216. $total = $this->getQuote()->getBaseGrandTotal();
  217. $minTotal = $method->getConfigData('min_order_total');
  218. $maxTotal = $method->getConfigData('max_order_total');
  219.  
  220. if((!empty($minTotal) && ($total < $minTotal)) || (!empty($maxTotal) && ($total > $maxTotal))) {
  221. return false;
  222. }
  223.  
  224. if (Mage::helper('core')->isModuleOutputEnabled('Amasty_Methods')) {
  225. if (!Mage::helper('ammethods')->canUseMethod($method, 'payment')) {
  226. return false;
  227. }
  228. }
  229.  
  230. return true;
  231. }
  232.  
  233. protected function _canUseShippingMethod($method)
  234. {
  235. if (Mage::helper('core')->isModuleOutputEnabled('Amasty_Methods')) {
  236. if (!Mage::helper('ammethods')->canUseMethod($method, 'shipping')) {
  237. return false;
  238. }
  239. }
  240.  
  241. // copied from Ophirah_Qquoteadv_Block_Checkout_Onepage_Shipping_Method_Available
  242. if (Mage::helper('core')->isModuleOutputEnabled('Ophirah_Qquoteadv')) {
  243. if (Mage::helper('qquoteadv')->isActiveConfirmMode(true) &&
  244. Mage::app()->getHelper('qquoteadv')->isSetQuoteShipPrice()) {
  245.  
  246. return 'qquoteshiprate' === $method;
  247. } else {
  248. return 'qquoteshiprate' !== $method;
  249. }
  250. }
  251.  
  252. return true;
  253. }
  254.  
  255. /**
  256. * Set the default values at the start of payment process
  257. *
  258. * @return TM_FireCheckout_Model_Type_Standard
  259. */
  260. public function applyDefaults()
  261. {
  262. $addressInfo = $this->_getDefaultAddress();
  263. $this->saveBilling(
  264. $addressInfo['billing'],
  265. $addressInfo['billing']['customer_address_id'],
  266. false
  267. );
  268. if (!$addressInfo['billing']['use_for_shipping']) {
  269. $this->saveShipping(
  270. $addressInfo['shipping'],
  271. $addressInfo['shipping']['customer_address_id'],
  272. false
  273. );
  274. }
  275.  
  276. /**
  277. * @var Mage_Sales_Model_Quote
  278. */
  279. $quote = $this->getQuote();
  280. $shippingAddress = $quote->getShippingAddress();
  281.  
  282. // weight vs destination fix
  283. $weight = 0;
  284. foreach($quote->getAllItems() as $item) {
  285. $weight += ($item->getWeight() * $item->getQty()) ;
  286. }
  287. $shippingAddress->setFreeMethodWeight($weight)->setWeight($weight);
  288.  
  289. $this->applyPaymentMethod();
  290. $shippingAddress->collectTotals()->collectShippingRates()->save(); // premiumrate fix
  291. $this->applyShippingMethod();
  292. // shipping method may affect the total in both sides (discount on using shipping address)
  293. $quote->collectTotals();
  294.  
  295. $ajaxHelper = Mage::helper('firecheckout/ajax');
  296. if ($ajaxHelper->getIsShippingMethodDependsOn('total')) {
  297. // changing total by shipping price may affect the shipping prices theoretically
  298. // (free shipping may be canceled or added)
  299. $shippingAddress->setCollectShippingRates(true)->collectShippingRates();
  300. // if shipping price was changed, we need to recalculate totals again.
  301. // Example: SELECTED SHIPPING METHOD NOW BECOMES FREE
  302. // previous method added a discount and selected shipping method wasn't free
  303. // but removing the previous shipping method removes the discount also
  304. // and selected shipping method is now free
  305. $quote->setTotalsCollectedFlag(false)->collectTotals();
  306. }
  307.  
  308. if ($ajaxHelper->getIsTotalDependsOn('payment-method')) { // @todo && method is changed
  309. // recollect totals again because adding/removing payment
  310. // method may add/remove some discounts in the order
  311.  
  312. // to recollect discount rules need to clear previous discount
  313. // descriptions and mark address as modified
  314. // see _canProcessRule in Mage_SalesRule_Model_Validator
  315.  
  316. // this line makes subtotal calculated without tax, causing missing discount
  317. // without this line discount per payment method is not applied if
  318. // 'discountable' method is default one. FIXED by moving applyPayment method before applyShipping
  319. // $shippingAddress->setDiscountDescriptionArray(array())->isObjectNew(true);
  320.  
  321. $quote->setTotalsCollectedFlag(false)->collectTotals();
  322. }
  323.  
  324. $quote->save();
  325.  
  326. return $this;
  327. }
  328.  
  329. /**
  330. * Update payment method information
  331. * Removes previously selected method if none is available,
  332. * set available if only one is available,
  333. * set previously selected payment,
  334. * set default from config if possible
  335. *
  336. * @param string $methodCode Default method code
  337. * @return TM_FireCheckout_Model_Type_Standard
  338. */
  339. public function applyPaymentMethod($methodCode = null)
  340. {
  341. if (false === $methodCode) {
  342. return $this->getQuote()->removePayment();
  343. }
  344.  
  345. $store = $this->getQuote() ? $this->getQuote()->getStoreId() : null;
  346. $methods = Mage::helper('payment')->getStoreMethods($store, $this->getQuote());
  347. $availablePayments = array();
  348. foreach ($methods as $key => $method) {
  349. if (!$method || !$method->canUseCheckout()) {
  350. continue;
  351. }
  352. if ($this->_canUsePaymentMethod($method)) {
  353. $availablePayments[] = $method;
  354. }
  355. }
  356.  
  357. $found = false;
  358. $count = count($availablePayments);
  359. if (1 === $count) {
  360. $methodCode = $availablePayments[0]->getCode();
  361. $found = true;
  362. } elseif ($count) {
  363. if (!$methodCode) {
  364. $methodCode = $this->getQuote()->getPayment()->getMethod();
  365. }
  366. if ($methodCode) {
  367. foreach ($availablePayments as $payment) {
  368. if ($methodCode == $payment->getCode()) {
  369. $found = true;
  370. break;
  371. }
  372. }
  373. }
  374. if (!$found || !$methodCode) {
  375. $methodCode = Mage::getStoreConfig('firecheckout/general/payment_method');
  376. foreach ($availablePayments as $payment) {
  377. if ($methodCode == $payment->getCode()) {
  378. $found = true;
  379. break;
  380. }
  381. }
  382. }
  383. }
  384.  
  385. if (!$found) {
  386. $this->getQuote()->removePayment();
  387. } elseif ($methodCode) {
  388. $payment = $this->getQuote()->getPayment();
  389. $payment->setMethod($methodCode);
  390. $payment->setMethodInstance(null); // fix for billmate payments
  391. $method = $payment->getMethodInstance();
  392. try {
  393. $data = new Varien_Object(array('method' => $methodCode));
  394. $method->assignData($data);
  395. } catch (Exception $e) {
  396. // Adyen HPP extension fix
  397. }
  398.  
  399. if ($this->getQuote()->isVirtual()) { // discount are looking for method inside address
  400. $this->getQuote()->getBillingAddress()->setPaymentMethod($methodCode);
  401. } else {
  402. $this->getQuote()->getShippingAddress()->setPaymentMethod($methodCode);
  403. }
  404. }
  405.  
  406. return $this;
  407. }
  408.  
  409. /**
  410. * Update shipping method information
  411. * Removes previously selected method if none is available,
  412. * set available if only one is available,
  413. * set previously selected payment,
  414. * set default from config if possible
  415. *
  416. * @param string $methodCode Default method code
  417. * @return TM_FireCheckout_Model_Type_Standard
  418. */
  419. public function applyShippingMethod($methodCode = null)
  420. {
  421. if (false === $methodCode) {
  422. return $this->getQuote()->getShippingAddress()->setShippingMethod(false);
  423. }
  424. $rates = Mage::getModel('sales/quote_address_rate')->getCollection()
  425. ->setAddressFilter($this->getQuote()->getShippingAddress()->getId())
  426. ->toArray();
  427.  
  428. // unset error shipping methods. Like ups_error etc.
  429. $hideIfFree = Mage::getStoreConfigFlag('firecheckout/general/hide_shipping_if_free');
  430. foreach ($rates['items'] as $k => $rate) {
  431. if ('freeshipping' === $rate['method']
  432. && empty($rate['error_message'])
  433. && $hideIfFree) {
  434.  
  435. $this->getQuote()->getShippingAddress()->setShippingMethod($rate['code']);
  436. return $this;
  437. }
  438. if ((empty($rate['method']) && $rate['code'] !== 'productmatrix_')
  439. || 'customshippingrate' == $rate['method']) {
  440.  
  441. unset($rates['items'][$k]);
  442. continue;
  443. }
  444.  
  445. if (!$this->_canUseShippingMethod($rate['method'])) {
  446. unset($rates['items'][$k]);
  447. }
  448. }
  449. reset($rates['items']);
  450.  
  451. if ((!$count = count($rates['items']))) {
  452. $this->getQuote()->getShippingAddress()->setShippingMethod(false);
  453. } elseif (1 === $count && !Mage::helper('firecheckout')->isOnecolumnMode()) {
  454. // do not apply method for onecolumn mode, because shipping methods are hidden on initial page load
  455. $rate = current($rates['items']);
  456. $this->getQuote()->getShippingAddress()->setShippingMethod($rate['code']);
  457. } else {
  458. $found = false;
  459. if (!$methodCode) {
  460. $methodCode = $this->getQuote()->getShippingAddress()->getShippingMethod();
  461. }
  462. if ($methodCode) {
  463. foreach ($rates['items'] as $rate) {
  464. if (is_array($methodCode) || $methodCode === $rate['code']) {
  465. $this->getQuote()->getShippingAddress()->setShippingMethod($methodCode);
  466. $found = true;
  467. break;
  468. }
  469. }
  470. }
  471. if (!$found || !$methodCode) {
  472. $methodCodes = array(
  473. Mage::getStoreConfig('firecheckout/general/shipping_method_code'),
  474. Mage::getStoreConfig('firecheckout/general/shipping_method')
  475. );
  476. foreach ($methodCodes as $methodCode) {
  477. if (!$methodCode) {
  478. continue;
  479. }
  480. foreach ($rates['items'] as $rate) {
  481. if ($methodCode === $rate['code']) {
  482. $this->getQuote()->getShippingAddress()->setShippingMethod($methodCode);
  483. $found = true;
  484. break 2;
  485. }
  486. }
  487. }
  488. }
  489. // if (!$found) {
  490. // foreach ($rates['items'] as $rate) {
  491. // $this->getQuote()->getShippingAddress()->setShippingMethod($rate['code']);
  492. // $found = true;
  493. // break;
  494. // }
  495. // }
  496. }
  497. return $this;
  498. }
  499.  
  500. /**
  501. * Initialize quote state to be valid for one page checkout
  502. *
  503. * @return Mage_Checkout_Model_Type_Onepage
  504. */
  505. public function initCheckout()
  506. {
  507. $checkout = $this->getCheckout();
  508. $customerSession = $this->getCustomerSession();
  509.  
  510. $quoteSave = false;
  511. $collectTotals = false;
  512.  
  513. /**
  514. * Reset multishipping flag before any manipulations with quote address
  515. * addAddress method for quote object related on this flag
  516. */
  517. if ($this->getQuote()->getIsMultiShipping()) {
  518. $this->getQuote()->setIsMultiShipping(false);
  519. $quoteSave = true;
  520. }
  521.  
  522. // /**
  523. // * Reset customer balance
  524. // */
  525. // if ($this->getQuote()->getUseCustomerBalance()) {
  526. // $this->getQuote()->setUseCustomerBalance(false);
  527. // $quoteSave = true;
  528. // $collectTotals = true;
  529. // }
  530. // /**
  531. // * Reset reward points
  532. // */
  533. // if ($this->getQuote()->getUseRewardPoints()) {
  534. // $this->getQuote()->setUseRewardPoints(false);
  535. // $quoteSave = true;
  536. // $collectTotals = true;
  537. // }
  538.  
  539. if ($collectTotals) {
  540. $this->getQuote()->collectTotals();
  541. }
  542.  
  543. if ($quoteSave) {
  544. $this->getQuote()->save();
  545. }
  546.  
  547. /*
  548. * want to load the correct customer information by assiging to address
  549. * instead of just loading from sales/quote_address
  550. */
  551. $customer = $customerSession->getCustomer();
  552. if ($customer) {
  553. if ($customer->getId()) {
  554. $this->getQuote()->setCustomer($customer);
  555. }
  556. // $this->getQuote()->assignCustomer($customer); // fixed reseting of selected address
  557. }
  558. return $this;
  559. }
  560.  
  561. /**
  562. * Get quote checkout method
  563. *
  564. * @return string
  565. */
  566. public function getCheckoutMethod()
  567. {
  568. if ($this->getCustomerSession()->isLoggedIn()) {
  569. return self::METHOD_CUSTOMER;
  570. }
  571. if (!$this->getQuote()->getCheckoutMethod()) {
  572. if (Mage::helper('firecheckout')->isAllowedGuestCheckout()) {
  573. $this->getQuote()->setCheckoutMethod(self::METHOD_GUEST);
  574. } else {
  575. $this->getQuote()->setCheckoutMethod(self::METHOD_REGISTER);
  576. }
  577. }
  578. return $this->getQuote()->getCheckoutMethod();
  579. }
  580.  
  581. /**
  582. * Specify checkout method
  583. *
  584. * @param string $method
  585. * @return array
  586. */
  587. public function saveCheckoutMethod($method)
  588. {
  589. if (empty($method)) {
  590. return array('error' => -1, 'message' => $this->_helper->__('Invalid data.'));
  591. }
  592.  
  593. $this->getQuote()->setCheckoutMethod($method)->save();
  594. return array();
  595. }
  596.  
  597. /**
  598. * Get customer address by identifier
  599. *
  600. * @param int $addressId
  601. * @return Mage_Customer_Model_Address
  602. */
  603. public function getAddress($addressId)
  604. {
  605. $address = Mage::getModel('customer/address')->load((int)$addressId);
  606. $address->explodeStreetAddress();
  607. if ($address->getRegionId()) {
  608. $address->setRegion($address->getRegionId());
  609. }
  610. return $address;
  611. }
  612.  
  613. /**
  614. * Save billing address information to quote
  615. * This method is called by One Page Checkout JS (AJAX) while saving the billing information.
  616. *
  617. * @param array $data
  618. * @param int $customerAddressId
  619. * @return Mage_Checkout_Model_Type_Onepage
  620. */
  621. public function saveBilling($data, $customerAddressId, $validate = true)
  622. {
  623. if (empty($data)) {
  624. return array('error' => -1, 'message' => $this->_helper->__('Invalid data.'));
  625. }
  626.  
  627. /* old code */
  628. if (isset($data['register_account']) && $data['register_account']) {
  629. $this->getQuote()->setCheckoutMethod(self::METHOD_REGISTER);
  630. } else if ($this->getCustomerSession()->isLoggedIn()) {
  631. $this->getQuote()->setCheckoutMethod(self::METHOD_CUSTOMER);
  632. } else {
  633. $this->getQuote()->setCheckoutMethod(self::METHOD_GUEST);
  634. }
  635. /* eof old code */
  636.  
  637. $address = $this->getQuote()->getBillingAddress();
  638. /* @var $addressForm Mage_Customer_Model_Form */
  639. $addressForm = Mage::getModel('customer/form');
  640. $addressForm->setFormCode('customer_address_edit')
  641. ->setEntityType('customer_address')
  642. ->setIsAjaxRequest(Mage::app()->getRequest()->isAjax());
  643.  
  644. if (!empty($customerAddressId)) {
  645. $customerAddress = Mage::getModel('customer/address')->load($customerAddressId);
  646. if ($customerAddress->getId()) {
  647. if ($customerAddress->getCustomerId() != $this->getQuote()->getCustomerId()) {
  648. return array('error' => 1,
  649. 'message' => $this->_helper->__('Customer Address is not valid.')
  650. );
  651. }
  652. $address->importCustomerAddress($customerAddress)->setSaveInAddressBook(0);
  653. // invalid validation of saved street address
  654. if (version_compare(Mage::helper('firecheckout')->getMagentoVersion(), '1.5.1.0') >= 0) {
  655. $addressForm->setEntity($address);
  656. if ($validate) {
  657. $addressErrors = $addressForm->validateData($address->getData());
  658. if ($addressErrors !== true) {
  659. return array('error' => 1, 'message' => $addressErrors);
  660. }
  661. }
  662. }
  663. }
  664. } else {
  665. $address->setCustomerAddressId(null);
  666. $addressForm->setEntity($address);
  667. // emulate request object
  668. $addressData = $addressForm->extractData($addressForm->prepareRequest($data));
  669. if ($validate) {
  670. $addressErrors = $addressForm->validateData($addressData);
  671. if ($addressErrors !== true) {
  672. return array('error' => 1, 'message' => $addressErrors);
  673. }
  674. }
  675. $addressForm->compactData($addressData);
  676. //unset billing address attributes which were not shown in form
  677. foreach ($addressForm->getAttributes() as $attribute) {
  678. if (!isset($data[$attribute->getAttributeCode()])) {
  679. $address->setData($attribute->getAttributeCode(), NULL);
  680. }
  681. }
  682.  
  683. // Additional form data, not fetched by extractData (as it fetches only attributes)
  684. $address->setSaveInAddressBook(empty($data['save_in_address_book']) ? 0 : 1);
  685. }
  686.  
  687. // set email for newly created user
  688. if (!$address->getEmail() && $this->getQuote()->getCustomerEmail()) {
  689. $address->setEmail($this->getQuote()->getCustomerEmail());
  690. }
  691.  
  692. // validate billing address
  693. if ($validate && ($validateRes = $address->validate()) !== true) {
  694. return array('error' => 1, 'message' => $validateRes);
  695. }
  696.  
  697. $address->implodeStreetAddress();
  698.  
  699. if (true !== ($result = $this->_validateCustomerData($data, $validate))) {
  700. if ($validate) {
  701. return $result;
  702. }
  703. }
  704.  
  705. if (isset($data['taxvat'])) { // fix for euvat extension
  706. $this->getQuote()->setCustomerTaxvat($data['taxvat']);
  707. }
  708.  
  709. if ($validate
  710. && !$this->getQuote()->getCustomerId()
  711. && self::METHOD_REGISTER == $this->getQuote()->getCheckoutMethod()) {
  712.  
  713. if ($this->_customerEmailExists($address->getEmail(), Mage::app()->getWebsite()->getId())) {
  714. return array('error' => 1, 'message' => $this->_customerEmailExistsMessage);
  715. }
  716. }
  717.  
  718. if (!$this->getQuote()->isVirtual()) {
  719. /**
  720. * Billing address using options
  721. */
  722. $usingCase = isset($data['use_for_shipping']) ? (int)$data['use_for_shipping'] : 0;
  723.  
  724. switch($usingCase) {
  725. case 0:
  726. $shipping = $this->getQuote()->getShippingAddress();
  727. $shipping->setSameAsBilling(0);
  728. break;
  729. case 1:
  730. $billing = clone $address;
  731. $billing->unsAddressId()->unsAddressType();
  732. $shipping = $this->getQuote()->getShippingAddress();
  733. $shippingMethod = $shipping->getShippingMethod();
  734.  
  735. // don't reset original shipping data, if it was not changed by customer
  736. foreach ($shipping->getData() as $shippingKey => $shippingValue) {
  737. if (!is_null($shippingValue)
  738. && !is_null($billing->getData($shippingKey))
  739. && !isset($data[$shippingKey])) {
  740. $billing->unsetData($shippingKey);
  741. }
  742. }
  743. $shipping->addData($billing->getData())
  744. ->setSameAsBilling(1)
  745. ->setSaveInAddressBook(0)
  746. ->setShippingMethod($shippingMethod)
  747. ->setCollectShippingRates(true);
  748. $this->getCheckout()->setStepData('shipping', 'complete', true);
  749. break;
  750. }
  751. }
  752.  
  753.  
  754. /* old code */
  755. if ($validate && (true !== $result = $this->_processValidateCustomer($address))) {
  756. return $result;
  757. }
  758. /* eof old code */
  759.  
  760. return array();
  761. }
  762.  
  763. /**
  764. * Validate customer data and set some its data for further usage in quote
  765. * Will return either true or array with error messages
  766. *
  767. * @param array $data
  768. * @return true|array
  769. */
  770. protected function _validateCustomerData(array $data, $validate = true)
  771. {
  772. /* @var $customerForm Mage_Customer_Model_Form */
  773. $customerForm = Mage::getModel('customer/form');
  774. $customerForm->setFormCode('checkout_register')
  775. ->setIsAjaxRequest(Mage::app()->getRequest()->isAjax());
  776.  
  777. $quote = $this->getQuote();
  778. if ($quote->getCustomerId()) {
  779. $customer = $quote->getCustomer();
  780. $customerForm->setEntity($customer);
  781. $customerData = $quote->getCustomer()->getData();
  782. } else {
  783. /* @var $customer Mage_Customer_Model_Customer */
  784. $customer = Mage::getModel('customer/customer');
  785. $customerForm->setEntity($customer);
  786. $customerRequest = $customerForm->prepareRequest($data);
  787. $customerData = $customerForm->extractData($customerRequest);
  788. }
  789.  
  790. $customerErrors = $customerForm->validateData($customerData);
  791. if ($validate && $customerErrors !== true) {
  792. return array(
  793. 'error' => -1,
  794. 'message' => implode(', ', $customerErrors)
  795. );
  796. }
  797.  
  798. if ($quote->getCustomerId()) {
  799. return true;
  800. }
  801.  
  802. $customerForm->compactData($customerData);
  803.  
  804. if ($quote->getCheckoutMethod() == self::METHOD_REGISTER) {
  805. // set customer password
  806. $password = $customerRequest->getParam('customer_password');
  807. if (empty($password)) {
  808. $password = $customer->generatePassword();
  809. $customer->setPassword($password);
  810. $customer->setConfirmation($password);
  811. $customer->setPasswordConfirmation($password);
  812. } else {
  813. $customer->setPassword($customerRequest->getParam('customer_password'));
  814. $customer->setConfirmation($customerRequest->getParam('confirm_password'));
  815. $customer->setPasswordConfirmation($customerRequest->getParam('confirm_password'));
  816. }
  817. } else {
  818. // emulate customer password for quest
  819. $password = $customer->generatePassword();
  820. $customer->setPassword($password);
  821. $customer->setConfirmation($password);
  822. $customer->setPasswordConfirmation($password);
  823. // set NOT LOGGED IN group id explicitly,
  824. // otherwise copyFieldset('customer_account', 'to_quote') will fill it with default group id value
  825. $customer->setGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
  826. }
  827.  
  828. $result = $customer->validate();
  829. if ($validate && true !== $result && is_array($result)) {
  830. return array(
  831. 'error' => -1,
  832. 'message' => implode(', ', $result)
  833. );
  834. }
  835.  
  836. if ($quote->getCheckoutMethod() == self::METHOD_REGISTER) {
  837. // save customer encrypted password in quote
  838. $quote->setPasswordHash($customer->encryptPassword($customer->getPassword()));
  839. }
  840.  
  841. // copy customer/guest email to address
  842. $quote->getBillingAddress()->setEmail($customer->getEmail());
  843.  
  844. // copy customer data to quote
  845. $enteredTaxvat = $quote->getCustomerTaxvat();
  846. Mage::helper('core')->copyFieldset('customer_account', 'to_quote', $customer, $quote);
  847. if ($enteredTaxvat && !$quote->getCustomerTaxvat()) {
  848. $quote->setCustomerTaxvat($enteredTaxvat);
  849. }
  850.  
  851. return true;
  852. }
  853.  
  854. /**
  855. * Deprecated but used by firecheckout to validate the taxvat field
  856. *
  857. * @deprecated Need to rename to _processValidateTaxvat
  858. * @param Mage_Sales_Model_Quote_Address $address
  859. * @return true|array
  860. */
  861. protected function _processValidateCustomer(Mage_Sales_Model_Quote_Address $address)
  862. {
  863. // set customer tax/vat number for further usage
  864. $fields = Mage::getStoreConfig('firecheckout/taxvat/field_names');
  865. $fields = explode(',', $fields);
  866.  
  867. $vatNumbers = array(
  868. 'taxvat' => $this->getQuote()->getCustomerTaxvat(), // $taxvat = $address->getTaxvat();
  869. 'vat_id' => $address->getVatId()
  870. );
  871. foreach ($vatNumbers as $fieldName => $value) {
  872. if (strlen($value) && in_array($fieldName, $fields)
  873. && Mage::getStoreConfig('firecheckout/taxvat/validate')) {
  874.  
  875. $taxvatValidator = Mage::getModel('firecheckout/taxvat_validator');
  876. if (!$taxvatValidator->isValid($value, $address->getCountryId())) {
  877. return array(
  878. 'error' => -1,
  879. 'message' => $taxvatValidator->getMessage()
  880. );
  881. }
  882. }
  883. }
  884.  
  885. // set customer tax/vat number for further usage
  886. if ($address->getTaxnumber()) {
  887. $this->getQuote()->setCustomerTaxnumber($address->getTaxnumber());
  888. }
  889.  
  890. return true;
  891. }
  892.  
  893. /**
  894. * Save checkout shipping address
  895. *
  896. * @param array $data
  897. * @param int $customerAddressId
  898. * @return Mage_Checkout_Model_Type_Onepage
  899. */
  900. public function saveShipping($data, $customerAddressId, $validate = true)
  901. {
  902. if (empty($data)) {
  903. return array('error' => -1, 'message' => $this->_helper->__('Invalid data.'));
  904. }
  905. $address = $this->getQuote()->getShippingAddress();
  906.  
  907. /* @var $addressForm Mage_Customer_Model_Form */
  908. $addressForm = Mage::getModel('customer/form');
  909. $addressForm->setFormCode('customer_address_edit')
  910. ->setEntityType('customer_address')
  911. ->setIsAjaxRequest(Mage::app()->getRequest()->isAjax());
  912.  
  913. if (!empty($customerAddressId)) {
  914. $customerAddress = Mage::getModel('customer/address')->load($customerAddressId);
  915. if ($customerAddress->getId()) {
  916. if ($customerAddress->getCustomerId() != $this->getQuote()->getCustomerId()) {
  917. return array('error' => 1,
  918. 'message' => $this->_helper->__('Customer Address is not valid.')
  919. );
  920. }
  921.  
  922. $address->importCustomerAddress($customerAddress)->setSaveInAddressBook(0);
  923. $addressForm->setEntity($address);
  924. if ($validate) {
  925. $addressErrors = $addressForm->validateData($address->getData());
  926. if ($addressErrors !== true) {
  927. return array('error' => 1, 'message' => $addressErrors);
  928. }
  929. }
  930. }
  931. } else {
  932. $address->setCustomerAddressId(null);
  933. $addressForm->setEntity($address);
  934. // emulate request object
  935. $addressData = $addressForm->extractData($addressForm->prepareRequest($data));
  936. if ($validate) {
  937. $addressErrors = $addressForm->validateData($addressData);
  938. if ($addressErrors !== true) {
  939. return array('error' => 1, 'message' => $addressErrors);
  940. }
  941. }
  942. $addressForm->compactData($addressData);
  943. // unset shipping address attributes which were not shown in form
  944. foreach ($addressForm->getAttributes() as $attribute) {
  945. if (!isset($data[$attribute->getAttributeCode()])) {
  946. $address->setData($attribute->getAttributeCode(), NULL);
  947. }
  948. }
  949.  
  950. // Additional form data, not fetched by extractData (as it fetches only attributes)
  951. $address->setSaveInAddressBook(empty($data['save_in_address_book']) ? 0 : 1);
  952. }
  953.  
  954. $address->setSameAsBilling(empty($data['same_as_billing']) ? 0 : 1);
  955. $address->implodeStreetAddress();
  956. $address->setCollectShippingRates(true);
  957.  
  958. // validate billing address
  959. if ($validate && ($validateRes = $address->validate()) !== true) {
  960. return array('error' => 1, 'message' => $validateRes);
  961. }
  962.  
  963. return array();
  964. }
  965.  
  966. /**
  967. * Specify quote shipping method
  968. *
  969. * @param string $shippingMethod
  970. * @return array
  971. */
  972. public function saveShippingMethod($shippingMethod)
  973. {
  974. if (empty($shippingMethod)) {
  975. return array('error' => -1, 'message' => $this->_helper->__('Invalid shipping method.'));
  976. }
  977. $rate = $this->getQuote()->getShippingAddress()->getShippingRateByCode($shippingMethod);
  978. if (!$rate) {
  979. return array('error' => -1, 'message' => $this->_helper->__('Invalid shipping method.'));
  980. }
  981. $this->getQuote()->getShippingAddress()
  982. ->setShippingMethod($shippingMethod);
  983. $this->getQuote()->collectTotals()
  984. ->save();
  985.  
  986. return array();
  987. }
  988.  
  989. /**
  990. * Specify quote payment method
  991. *
  992. * @param array $data
  993. * @return array
  994. */
  995. public function savePayment($data)
  996. {
  997. if (empty($data)) {
  998. return array('error' => -1, 'message' => $this->_helper->__('Invalid data.'));
  999. }
  1000. $quote = $this->getQuote();
  1001. if ($quote->isVirtual()) {
  1002. $quote->getBillingAddress()->setPaymentMethod(isset($data['method']) ? $data['method'] : null);
  1003. } else {
  1004. $quote->getShippingAddress()->setPaymentMethod(isset($data['method']) ? $data['method'] : null);
  1005. }
  1006.  
  1007. // shipping totals may be affected by payment method
  1008. if (!$quote->isVirtual() && $quote->getShippingAddress()) {
  1009. $quote->getShippingAddress()->setCollectShippingRates(true);
  1010. }
  1011.  
  1012. if (@defined('Mage_Payment_Model_Method_Abstract::CHECK_USE_CHECKOUT')) {
  1013. $data['checks'] = Mage_Payment_Model_Method_Abstract::CHECK_USE_CHECKOUT
  1014. | Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_COUNTRY
  1015. | Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_CURRENCY
  1016. | Mage_Payment_Model_Method_Abstract::CHECK_ORDER_TOTAL_MIN_MAX
  1017. | Mage_Payment_Model_Method_Abstract::CHECK_ZERO_TOTAL;
  1018. }
  1019.  
  1020. $payment = $quote->getPayment();
  1021. $payment->setMethod(isset($data['method']) ? $data['method'] : false); // Magebuzz_Rewardpoint fix
  1022. $payment->setMethodInstance(null); // fix for billmate payments
  1023.  
  1024. // fix for third-party-modules. If collect totals was called before
  1025. // save billing address - shipping description will stay empty
  1026. $quote->setTotalsCollectedFlag(false);
  1027.  
  1028. $payment->importData($data);
  1029.  
  1030. $quote->save();
  1031.  
  1032. // billpay integration
  1033. Mage::dispatchEvent('billpay_after_save_payment', array(
  1034. 'data'=>$data,
  1035. 'useHTMLFormat'=>false,
  1036. 'expectedDaysTillShipping'=>0
  1037. ));
  1038. // billpay integration
  1039.  
  1040. return array();
  1041. }
  1042.  
  1043. /**
  1044. * Validate quote state to be integrated with one page checkout process
  1045. */
  1046. public function validate()
  1047. {
  1048. $helper = Mage::helper('checkout');
  1049. $quote = $this->getQuote();
  1050. if ($quote->getIsMultiShipping()) {
  1051. Mage::throwException($helper->__('Invalid checkout type.'));
  1052. }
  1053.  
  1054. if ($quote->getCheckoutMethod() == self::METHOD_GUEST && !Mage::helper('firecheckout')->isAllowedGuestCheckout()) {
  1055. Mage::throwException($this->_helper->__('Sorry, guest checkout is not enabled. Please try again or contact store owner.'));
  1056. }
  1057. }
  1058.  
  1059. /**
  1060. * Prepare quote for guest checkout order submit
  1061. *
  1062. * @return Mage_Checkout_Model_Type_Onepage
  1063. */
  1064. protected function _prepareGuestQuote()
  1065. {
  1066. $quote = $this->getQuote();
  1067. $quote->setCustomerId(null)
  1068. ->setCustomerEmail($quote->getBillingAddress()->getEmail())
  1069. ->setCustomerIsGuest(true)
  1070. ->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
  1071. return $this;
  1072. }
  1073.  
  1074. /**
  1075. * Prepare quote for customer registration and customer order submit
  1076. *
  1077. * @return Mage_Checkout_Model_Type_Onepage
  1078. */
  1079. protected function _prepareNewCustomerQuote()
  1080. {
  1081. $quote = $this->getQuote();
  1082. $billing = $quote->getBillingAddress();
  1083. $shipping = $quote->isVirtual() ? null : $quote->getShippingAddress();
  1084.  
  1085. $customer = $quote->getCustomer();
  1086. /* @var $customer Mage_Customer_Model_Customer */
  1087. $customerBilling = $billing->exportCustomerAddress();
  1088. $customer->addAddress($customerBilling);
  1089. $billing->setCustomerAddress($customerBilling);
  1090. $customerBilling->setIsDefaultBilling(true);
  1091. if ($shipping && !$shipping->getSameAsBilling()) {
  1092. $customerShipping = $shipping->exportCustomerAddress();
  1093. $customer->addAddress($customerShipping);
  1094. $shipping->setCustomerAddress($customerShipping);
  1095. $customerShipping->setIsDefaultShipping(true);
  1096. } elseif ($shipping) {
  1097. $customerBilling->setIsDefaultShipping(true);
  1098. }
  1099.  
  1100. if ($quote->getCustomerTaxnumber() && !$billing->getCustomerTaxnumber()) {
  1101. $billing->setCustomerTaxnumber($quote->getCustomerTaxnumber());
  1102. }
  1103.  
  1104. Mage::helper('core')->copyFieldset('checkout_onepage_quote', 'to_customer', $quote, $customer);
  1105. $customer->setPassword($customer->decryptPassword($quote->getPasswordHash()));
  1106. $customer->setPasswordHash($customer->hashPassword($customer->getPassword()));
  1107. $quote->setCustomer($customer)
  1108. ->setCustomerId(true);
  1109. }
  1110.  
  1111. /**
  1112. * Prepare quote for customer order submit
  1113. *
  1114. * @return Mage_Checkout_Model_Type_Onepage
  1115. */
  1116. protected function _prepareCustomerQuote()
  1117. {
  1118. $quote = $this->getQuote();
  1119. $billing = $quote->getBillingAddress();
  1120. $shipping = $quote->isVirtual() ? null : $quote->getShippingAddress();
  1121.  
  1122. $customer = $this->getCustomerSession()->getCustomer();
  1123. if (!$billing->getCustomerId() || $billing->getSaveInAddressBook()) {
  1124. $customerBilling = $billing->exportCustomerAddress();
  1125. $customer->addAddress($customerBilling);
  1126. $billing->setCustomerAddress($customerBilling);
  1127. }
  1128. if ($shipping && !$shipping->getSameAsBilling() &&
  1129. (!$shipping->getCustomerId() || $shipping->getSaveInAddressBook())) {
  1130. $customerShipping = $shipping->exportCustomerAddress();
  1131. $customer->addAddress($customerShipping);
  1132. $shipping->setCustomerAddress($customerShipping);
  1133. }
  1134.  
  1135. if (isset($customerBilling) && !$customer->getDefaultBilling()) {
  1136. $customerBilling->setIsDefaultBilling(true);
  1137. }
  1138. if ($shipping && isset($customerShipping) && !$customer->getDefaultShipping()) {
  1139. $customerShipping->setIsDefaultShipping(true);
  1140. } else if (isset($customerBilling) && !$customer->getDefaultShipping()) {
  1141. $customerBilling->setIsDefaultShipping(true);
  1142. }
  1143. $quote->setCustomer($customer);
  1144. }
  1145.  
  1146. /**
  1147. * Involve new customer to system
  1148. *
  1149. * @return Mage_Checkout_Model_Type_Onepage
  1150. */
  1151. protected function _involveNewCustomer()
  1152. {
  1153. $customer = $this->getQuote()->getCustomer();
  1154. if ($customer->isConfirmationRequired()) {
  1155. $customer->sendNewAccountEmail('confirmation', '', $this->getQuote()->getStoreId());
  1156. $url = Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail());
  1157. $this->getCustomerSession()->addSuccess(
  1158. Mage::helper('customer')->__('Account confirmation is required. Please, check your e-mail for confirmation link. To resend confirmation email please <a href="%s">click here</a>.', $url)
  1159. );
  1160. } else {
  1161. $customer->sendNewAccountEmail('registered', '', $this->getQuote()->getStoreId());
  1162. $this->getCustomerSession()->loginById($customer->getId());
  1163. }
  1164. return $this;
  1165. }
  1166.  
  1167. /**
  1168. * Create order based on checkout type. Create customer if necessary.
  1169. *
  1170. * @return Mage_Checkout_Model_Type_Onepage
  1171. */
  1172. public function saveOrder()
  1173. {
  1174. $this->validate();
  1175. $isNewCustomer = false;
  1176. switch ($this->getCheckoutMethod()) {
  1177. case self::METHOD_GUEST:
  1178. $this->_prepareGuestQuote();
  1179. break;
  1180. case self::METHOD_REGISTER:
  1181. $this->_prepareNewCustomerQuote();
  1182. $isNewCustomer = true;
  1183. break;
  1184. default:
  1185. $this->_prepareCustomerQuote();
  1186. break;
  1187. }
  1188.  
  1189. /**
  1190. * @var TM_FireCheckout_Model_Service_Quote
  1191. */
  1192. $service = Mage::getModel('firecheckout/service_quote', $this->getQuote());
  1193. $service->submitAll();
  1194.  
  1195. if ($isNewCustomer) {
  1196. try {
  1197. $this->_involveNewCustomer();
  1198. } catch (Exception $e) {
  1199. Mage::logException($e);
  1200. }
  1201. }
  1202.  
  1203. $this->_checkoutSession->setLastQuoteId($this->getQuote()->getId())
  1204. ->setLastSuccessQuoteId($this->getQuote()->getId())
  1205. ->clearHelperData();
  1206.  
  1207. $order = $service->getOrder();
  1208. if ($order) {
  1209. Mage::dispatchEvent('checkout_type_onepage_save_order_after',
  1210. array('order'=>$order, 'quote'=>$this->getQuote()));
  1211.  
  1212. /**
  1213. * a flag to set that there will be redirect to third party after confirmation
  1214. * eg: paypal standard ipn
  1215. */
  1216. $redirectUrl = $this->getQuote()->getPayment()->getOrderPlaceRedirectUrl();
  1217. /**
  1218. * we only want to send to customer about new order when there is no redirect to third party
  1219. */
  1220. $canSendNewEmailFlag = true;
  1221. if (version_compare(Mage::helper('firecheckout')->getMagentoVersion(), '1.5.0.0', '>=')) {
  1222. $canSendNewEmailFlag = $order->getCanSendNewEmailFlag();
  1223. }
  1224. if (!$redirectUrl && $canSendNewEmailFlag) {
  1225. try {
  1226. if (method_exists($order, 'queueNewOrderEmail')) {
  1227. $order->queueNewOrderEmail();
  1228. } else {
  1229. $order->sendNewOrderEmail();
  1230. }
  1231. } catch (Exception $e) {
  1232. Mage::logException($e);
  1233. }
  1234. }
  1235.  
  1236. // add order information to the session
  1237. $this->_checkoutSession->setLastOrderId($order->getId())
  1238. ->setRedirectUrl($redirectUrl)
  1239. ->setLastRealOrderId($order->getIncrementId());
  1240.  
  1241. // as well a billing agreement can be created
  1242. $agreement = $order->getPayment()->getBillingAgreement();
  1243. if ($agreement) {
  1244. $this->_checkoutSession->setLastBillingAgreementId($agreement->getId());
  1245. }
  1246. }
  1247.  
  1248. // add recurring profiles information to the session
  1249. $profiles = $service->getRecurringPaymentProfiles();
  1250. if ($profiles) {
  1251. $ids = array();
  1252. foreach ($profiles as $profile) {
  1253. $ids[] = $profile->getId();
  1254. }
  1255. $this->_checkoutSession->setLastRecurringProfileIds($ids);
  1256. // TODO: send recurring profile emails
  1257. }
  1258.  
  1259. Mage::dispatchEvent(
  1260. 'checkout_submit_all_after',
  1261. array('order' => $order, 'quote' => $this->getQuote(), 'recurring_profiles' => $profiles)
  1262. );
  1263.  
  1264. return $this;
  1265. }
  1266.  
  1267. /**
  1268. * Validate quote state to be able submited from one page checkout page
  1269. *
  1270. * @deprecated after 1.4 - service model doing quote validation
  1271. * @return Mage_Checkout_Model_Type_Onepage
  1272. */
  1273. protected function validateOrder()
  1274. {
  1275. $helper = Mage::helper('checkout');
  1276. if ($this->getQuote()->getIsMultiShipping()) {
  1277. Mage::throwException($helper->__('Invalid checkout type.'));
  1278. }
  1279.  
  1280. if (!$this->getQuote()->isVirtual()) {
  1281. $address = $this->getQuote()->getShippingAddress();
  1282. $addressValidation = $this->validateAddress($address);
  1283. if ($addressValidation !== true) {
  1284. Mage::throwException($helper->__('Please check shipping address information.'));
  1285. }
  1286. $method= $address->getShippingMethod();
  1287. $rate = $address->getShippingRateByCode($method);
  1288. if (!$this->getQuote()->isVirtual() && (!$method || !$rate)) {
  1289. Mage::throwException($helper->__('Please specify shipping method.'));
  1290. }
  1291. }
  1292.  
  1293. $addressValidation = $this->validateAddress($this->getQuote()->getBillingAddress());
  1294. if ($addressValidation !== true) {
  1295. Mage::throwException($helper->__('Please check billing address information.'));
  1296. }
  1297.  
  1298. if (!($this->getQuote()->getPayment()->getMethod())) {
  1299. Mage::throwException($helper->__('Please select valid payment method.'));
  1300. }
  1301. }
  1302.  
  1303. /**
  1304. * Check if customer email exists
  1305. *
  1306. * @param string $email
  1307. * @param int $websiteId
  1308. * @return false|Mage_Customer_Model_Customer
  1309. */
  1310. protected function _customerEmailExists($email, $websiteId = null)
  1311. {
  1312. $customer = Mage::getModel('customer/customer');
  1313. if ($websiteId) {
  1314. $customer->setWebsiteId($websiteId);
  1315. }
  1316. $customer->loadByEmail($email);
  1317. if ($customer->getId()) {
  1318. return $customer;
  1319. }
  1320. return false;
  1321. }
  1322.  
  1323. /**
  1324. * Get last order increment id by order id
  1325. *
  1326. * @return string
  1327. */
  1328. public function getLastOrderId()
  1329. {
  1330. $lastId = $this->getCheckout()->getLastOrderId();
  1331. $orderId = false;
  1332. if ($lastId) {
  1333. $order = Mage::getModel('sales/order');
  1334. $order->load($lastId);
  1335. $orderId = $order->getIncrementId();
  1336. }
  1337. return $orderId;
  1338. }
  1339.  
  1340. public function validateAddress($address)
  1341. {
  1342. $errors = array();
  1343. $helper = Mage::helper('customer');
  1344. $address->implodeStreetAddress();
  1345. $formConfig = Mage::getStoreConfig('firecheckout/address_form_status');
  1346.  
  1347. if (!Zend_Validate::is($address->getFirstname(), 'NotEmpty')) {
  1348. $errors[] = $helper->__('Please enter the first name.');
  1349. }
  1350. if (!Zend_Validate::is($address->getLastname(), 'NotEmpty')) {
  1351. $errors[] = $helper->__('Please enter the last name.');
  1352. }
  1353.  
  1354. if ('required' === $formConfig['company']
  1355. && !Zend_Validate::is($address->getCompany(), 'NotEmpty')) {
  1356.  
  1357. $errors[] = $helper->__('Please enter the company.'); // translate
  1358. }
  1359.  
  1360. if ('required' === $formConfig['street1']
  1361. && !Zend_Validate::is($address->getStreet(1), 'NotEmpty')) {
  1362.  
  1363. $errors[] = $helper->__('Please enter the street.');
  1364. }
  1365.  
  1366. if ('required' === $formConfig['city']
  1367. && !Zend_Validate::is($address->getCity(), 'NotEmpty')) {
  1368.  
  1369. $errors[] = $helper->__('Please enter the city.');
  1370. }
  1371.  
  1372. if ('required' === $formConfig['telephone']
  1373. && !Zend_Validate::is($address->getTelephone(), 'NotEmpty')) {
  1374.  
  1375. $errors[] = $helper->__('Please enter the telephone number.');
  1376. }
  1377.  
  1378. if ('required' === $formConfig['fax']
  1379. && !Zend_Validate::is($address->getFax(), 'NotEmpty')) {
  1380.  
  1381. $errors[] = $helper->__('Please enter the fax.'); // translate
  1382. }
  1383.  
  1384. $_havingOptionalZip = Mage::helper('directory')->getCountriesWithOptionalZip();
  1385. if ('required' === $formConfig['postcode']
  1386. && !in_array($address->getCountryId(), $_havingOptionalZip)
  1387. && !Zend_Validate::is($address->getPostcode(), 'NotEmpty')) {
  1388.  
  1389. $errors[] = $helper->__('Please enter the zip/postal code.');
  1390. }
  1391.  
  1392. if ('required' === $formConfig['country_id']
  1393. && !Zend_Validate::is($address->getCountryId(), 'NotEmpty')) {
  1394.  
  1395. $errors[] = $helper->__('Please enter the country.');
  1396. }
  1397.  
  1398. if ('required' === $formConfig['region']
  1399. && $address->getCountryModel()->getRegionCollection()->getSize()
  1400. && !Zend_Validate::is($address->getRegionId(), 'NotEmpty')) {
  1401.  
  1402. $errors[] = $helper->__('Please enter the state/province.');
  1403. }
  1404.  
  1405. if (empty($errors) || $address->getShouldIgnoreValidation()) {
  1406. return true;
  1407. }
  1408. return $errors;
  1409. }
  1410.  
  1411. public function registerCustomerIfRequested()
  1412. {
  1413. if (self::METHOD_REGISTER != $this->getCheckoutMethod()) {
  1414. return;
  1415. }
  1416. $this->_prepareNewCustomerQuote();
  1417. $this->getQuote()->getCustomer()->save();
  1418. $this->_involveNewCustomer();
  1419. }
  1420.  
  1421. /**
  1422. * @param array $data
  1423. * date => string[optional]
  1424. * time => string[optional]
  1425. */
  1426. public function saveDeliveryDate(array $data, $validate = true)
  1427. {
  1428. $quote = $this->getQuote();
  1429. $quote->setFirecheckoutDeliveryDate(null);
  1430. $quote->setFirecheckoutDeliveryTimerange(null);
  1431.  
  1432. $shippingMethod = $this->getQuote()->getShippingAddress()->getShippingMethod();
  1433. /**
  1434. * @var TM_FireCheckout_Helper_Deliverydate
  1435. */
  1436. $helper = Mage::helper('firecheckout/deliverydate');
  1437. if (!$helper->canUseDeliveryDate($shippingMethod)) {
  1438. return;
  1439. }
  1440.  
  1441. // validate the date for weekend and excluded days
  1442. if (!empty($data['date'])) {
  1443. try {
  1444. // $date = new Zend_Date($data['date'], Mage::app()->getLocale()->getDateFormat());
  1445. // $date = new Zend_Date($data['date'], Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT));
  1446. $date = Mage::app()->getLocale()->date(
  1447. $data['date'],
  1448. Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT),
  1449. null,
  1450. false
  1451. );
  1452. } catch (Zend_Date_Exception $e) {
  1453. return array(
  1454. 'message' => Mage::helper('firecheckout')->__('Cannot parse delivery date. Following format expected: %s', Mage::app()->getLocale()->getDateFormat())
  1455. );
  1456. }
  1457.  
  1458. if ($validate && !$helper->isValidDate($date)) {
  1459. return array(
  1460. 'message' => Mage::helper('firecheckout')->__('We cannot deliver the package at the selected date. Please select another date for the delivery')
  1461. );
  1462. }
  1463. $quote->setFirecheckoutDeliveryDate($date->toString('yyyy-MM-dd'));
  1464. }
  1465.  
  1466. // validate time for valid range
  1467. if (!empty($data['time'])) {
  1468. if ($validate && !$helper->isValidTimeRange($data['time'])) {
  1469. return array(
  1470. 'message' => Mage::helper('firecheckout')->__('We cannot deliver the package at the selected time. Please select another time for the delivery')
  1471. );
  1472. }
  1473. $quote->setFirecheckoutDeliveryTimerange($data['time']);
  1474. }
  1475. }
  1476.  
  1477. public function getCustomerEmailExistsMessage()
  1478. {
  1479. return $this->_customerEmailExistsMessage;
  1480. }
  1481. }
Advertisement
Add Comment
Please, Sign In to add comment