Example #1
0
 /**
  * Format total value based on order currency
  *
  * @param   Varien_Object $total
  * @return  string
  */
 public function formatValue($total)
 {
     if (!$total->getIsFormated()) {
         return $this->helper('adminhtml/sales')->displayPrices($this->getOrder(), $total->getBaseValue(), $total->getValue());
     }
     return $total->getValue();
 }
 public function checkProductBuyState($product = null)
 {
     Mage_Catalog_Model_Product_Type_Abstract::checkProductBuyState($product);
     $product = $this->getProduct($product);
     $productOptionIds = $this->getOptionsIds($product);
     $productSelections = $this->getSelectionsCollection($productOptionIds, $product);
     $selectionIds = $product->getCustomOption('bundle_selection_ids');
     $selectionIds = unserialize($selectionIds->getValue());
     $buyRequest = $product->getCustomOption('info_buyRequest');
     $buyRequest = new Varien_Object(unserialize($buyRequest->getValue()));
     $bundleOption = $buyRequest->getBundleOption();
     if (empty($bundleOption)) {
         Mage::throwException($this->getSpecifyOptionMessage());
     }
     $skipSaleableCheck = Mage::helper('catalog/product')->getSkipSaleableCheck();
     foreach ($selectionIds as $selectionId) {
         /* @var $selection Mage_Bundle_Model_Selection */
         $selection = $productSelections->getItemById($selectionId);
         if (!$selection || !$selection->isSalable() && !$skipSaleableCheck) {
             Mage::throwException(Mage::helper('bundle')->__('Selected required options are not available.'));
         }
     }
     /*
     $product->getTypeInstance(true)->setStoreFilter($product->getStoreId(), $product);
     $optionsCollection = $this->getOptionsCollection($product);
     foreach ($optionsCollection->getItems() as $option) {
         if ($option->getRequired() && empty($bundleOption[$option->getId()])) {
             Mage::throwException(
                 Mage::helper('bundle')->__('Required options are not selected.')
             );
         }
     }
     */
     return $this;
 }
Example #3
0
 /**
  * @return mixed
  */
 protected function _getParams()
 {
     if (!Mage::registry(self::REGISTRY_KEY_PARAMS)) {
         $request = Mage::app()->getRequest();
         $params = array('host' => $request->getServer('HTTP_HOST'), 'port' => $request->getServer('SERVER_PORT'), 'full_action_name' => $this->getFullActionName());
         $uriParams = $this->_getUriParams();
         foreach ($request->getParams() as $requestParam => $requestParamValue) {
             if (!$requestParamValue) {
                 continue;
             }
             foreach ($uriParams as $uriParam) {
                 if ($this->_matchUriParam($uriParam, $requestParam)) {
                     $params['uri_' . $requestParam] = $requestParamValue;
                     break;
                 }
             }
         }
         if (Mage::getStoreConfig(self::XML_PATH_CUSTOMER_GROUPS)) {
             $customerSession = Mage::getSingleton('customer/session');
             $params['customer_group_id'] = $customerSession->getCustomerGroupId();
         }
         // edit parameters via event
         $parameters = new Varien_Object();
         $parameters->setValue($params);
         Mage::dispatchEvent('fpc_helper_collect_params', array('parameters' => $parameters));
         $params = $parameters->getValue();
         Mage::register(self::REGISTRY_KEY_PARAMS, serialize($params));
     }
     return Mage::registry(self::REGISTRY_KEY_PARAMS);
 }
Example #4
0
 /**
  * @param $group Webguys_Easytemplate_Model_Group
  * @return $this
  */
 public function setChildsBasedOnGroup($group, $parent = null)
 {
     if (!$this->countChildren()) {
         Varien_Profiler::start('easytemplate_template_rendering');
         /** @var $configModel Webguys_Easytemplate_Model_Input_Parser */
         $configModel = Mage::getSingleton('easytemplate/input_parser');
         $position = 1;
         $time = Mage::app()->getLocale()->storeTimeStamp(Mage::app()->getStore()->getId());
         /** @var $template Webguys_Easytemplate_Model_Template */
         foreach ($group->getTemplateCollection($parent) as $template) {
             $templateCode = $template->getCode();
             if ($model = $configModel->getTemplate($templateCode)) {
                 $active = $template->getActive();
                 $validFrom = $template->getValidFrom() ? strtotime($template->getValidFrom()) : false;
                 $validTo = $template->getValidTo() ? strtotime($template->getValidTo()) : false;
                 if ($validFrom !== false || $validTo !== false) {
                     $this->_cachingAllowed = false;
                 }
                 Varien_Profiler::start('easytemplate_template_rendering_' . $templateCode);
                 if ($active && (!$validFrom || $validFrom <= $time) && (!$validTo || $validTo >= $time)) {
                     /** @var $childBlock Webguys_Easytemplate_Block_Template */
                     $childBlock = $this->getLayout()->createBlock($model->getType());
                     $childBlock->setTemplate($model->getTemplate());
                     $childBlock->setTemplateModel($template);
                     $childBlock->setTemplateCode($templateCode);
                     $childBlock->setGroup($group);
                     /** @var $field Webguys_Easytemplate_Model_Input_Parser_Field */
                     foreach ($model->getFields() as $field) {
                         $fieldCode = $field->getCode();
                         Varien_Profiler::start('easytemplate_template_rendering_' . $templateCode . '_field_' . $fieldCode);
                         /** @var $inputValidator Webguys_Easytemplate_Model_Input_Renderer_Validator_Base */
                         $inputValidator = $field->getInputRendererValidator();
                         $inputValidator->setTemplate($template);
                         $inputValidator->setField($field);
                         $frontendValue = $inputValidator->prepareForFrontend($template->getFieldData($fieldCode));
                         if ($frontendValue) {
                             $valueTransport = new Varien_Object();
                             $valueTransport->setValue($frontendValue);
                             Mage::dispatchEvent('easytemplate_frontend_prepared_var', array('template' => $template, 'template_model' => $model, 'field' => $field, 'block' => $childBlock, 'validator' => $inputValidator, 'value' => $valueTransport));
                             $childBlock->setData($fieldCode, $valueTransport->getValue());
                         }
                         Varien_Profiler::stop('easytemplate_template_rendering_' . $templateCode . '_field_' . $fieldCode);
                     }
                     $this->setChild('block_' . $position . '_' . $templateCode, $childBlock);
                     $position++;
                 }
                 Varien_Profiler::stop('easytemplate_template_rendering_' . $templateCode);
             }
         }
         Varien_Profiler::stop('easytemplate_template_rendering');
     }
     return $this;
 }
Example #5
0
 /**
  * @test
  * @loadFixture fpc_helper_collect_params.yaml
  */
 public function testFpcHelperCollectParams()
 {
     Mage::app()->getRequest()->setRouteName('catalog');
     Mage::app()->getRequest()->setControllerName('category');
     Mage::app()->getRequest()->setActionName('view');
     /** @var Mage_Catalog_Model_Session $catalogSession */
     $catalogSession = Mage::getSingleton('catalog/session');
     $catalogSession->setData('fpc', 'cool');
     $expectedResult = array('fpc' => 'cool', 'store' => Mage::app()->getStore(true)->getCode(), 'currency' => Mage::app()->getStore()->getCurrentCurrencyCode(), 'design' => Mage::getDesign()->getPackageName() . '_' . Mage::getDesign()->getTheme('template'), 'session_fpc' => 'cool');
     $params = array('fpc' => 'cool');
     $object = new Varien_Object();
     $object->setValue($params);
     Mage::dispatchEvent('fpc_helper_collect_params', array('parameters' => $object));
     $this->assertEquals($expectedResult, $object->getValue());
 }
Example #6
0
 /**
  * Format price using order currency
  *
  * @param   Varien_Object $total
  * @return  string
  */
 protected function _formatPrice($total)
 {
     if (!$total->getIsFormated()) {
         return Mage::helper('Mage_XmlConnect_Helper_Customer_Order')->formatPrice($this, $total->getValue());
     }
     return $total->getValue();
 }
 /**
  * Retrieve the pattern used to match the URL to the permalink structure
  *
  * @return string
  */
 protected function _getPermalinkPattern()
 {
     $routerHelper = Mage::helper('wordpress/router');
     if ($structure = $this->_getExplodedPermalinkStructure()) {
         $lastPiece = $structure[count($structure) - 1];
         if ($lastPiece === '/') {
             array_pop($structure);
         }
         foreach ($structure as $i => $part) {
             if (preg_match('/^\\%[a-zA-Z0-9_-]{1,}\\%$/', $part)) {
                 $part = trim($part, '%');
                 if ($part === 'year') {
                     $part = '[1-2]{1}[0-9]{3}';
                 } else {
                     if ($part === 'monthnum') {
                         $part = '[0-1]{1}[0-9]{1}';
                     } else {
                         if ($part === 'day') {
                             $part = '[0-3]{1}[0-9]{1}';
                         } else {
                             if ($part === 'hour') {
                                 $part = '[0-2]{1}[0-9]{1}';
                             } else {
                                 if ($part === 'minute') {
                                     $part = '[0-5]{1}[0-9]{1}';
                                 } else {
                                     if ($part === 'second') {
                                         $part = '[0-5]{1}[0-9]{1}';
                                     } else {
                                         if ($part === 'post_id') {
                                             $part = '[0-9]{1,}';
                                         } else {
                                             if ($part === 'postname') {
                                                 $part = $routerHelper->getPermalinkStringRegex();
                                             } else {
                                                 if ($part === 'category') {
                                                     $part = $routerHelper->getPermalinkStringRegex('\\/');
                                                 } else {
                                                     if ($part === 'author') {
                                                         $part = $routerHelper->getPermalinkStringRegex();
                                                     } else {
                                                         $response = new Varien_Object(array('value' => false));
                                                         Mage::dispatchEvent('wordpress_permalink_segment_unknown_pattern', array('response' => $response, 'segment' => $part));
                                                         if ($response->getValue() !== false) {
                                                             $part = $response->getValue();
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
                 $part = '(' . $part . ')';
             } else {
                 $part = preg_replace('/([.|\\\\|\\/]{1})/i', '\\\\$1', $part);
             }
             $structure[$i] = $part;
         }
         return '^' . implode('', $structure) . '$';
     }
     return false;
 }
Example #8
0
 /**
  * Move quote item to another items store
  *
  * @param   mixed $item
  * @param   string $mogeTo
  * @return  Mage_Adminhtml_Model_Sales_Order_Create
  */
 public function moveQuoteItem($item, $moveTo, $qty)
 {
     if ($item = $this->_getQuoteItem($item)) {
         switch ($moveTo) {
             case 'order':
                 $info = array();
                 if ($info = $item->getOptionByCode('info_buyRequest')) {
                     $info = new Varien_Object(unserialize($info->getValue()));
                     $info->setOptions($this->_prepareOptionsForRequest($item));
                 }
                 $product = Mage::getModel('catalog/product')->setStoreId($this->getQuote()->getStoreId())->load($item->getProduct()->getId());
                 $product->setSkipCheckRequiredOption(true);
                 $newItem = $this->getQuote()->addProduct($product, $info);
                 if (is_string($newItem)) {
                     Mage::throwException($newItem);
                 }
                 $product->unsSkipCheckRequiredOption();
                 $newItem->checkData();
                 $newItem->setQty($qty);
                 break;
             case 'cart':
                 if (($cart = $this->getCustomerCart()) && is_null($item->getOptionByCode('additional_options'))) {
                     //options and info buy request
                     $product = Mage::getModel('catalog/product')->setStoreId($this->getQuote()->getStoreId())->load($item->getProduct()->getId());
                     $product->setSkipCheckRequiredOption(true);
                     $info = array();
                     if ($info = $item->getOptionByCode('info_buyRequest')) {
                         $info = new Varien_Object(unserialize($info->getValue()));
                         $info->setOptions($this->_prepareOptionsForRequest($item));
                     } else {
                         $info = new Varien_Object(array('product_id' => $product->getId(), 'qty' => $qty, 'options' => $this->_prepareOptionsForRequest($item)));
                     }
                     $cartItem = $cart->addProduct($product, $info);
                     if (is_string($cartItem)) {
                         Mage::throwException($cartItem);
                     }
                     $product->unsSkipCheckRequiredOption();
                     $cartItem->setQty($qty);
                     $cartItem->setPrice($item->getProduct()->getPrice());
                     $cart->collectTotals()->save();
                 }
                 break;
             case 'wishlist':
                 if ($wishlist = $this->getCustomerWishlist()) {
                     $wishlist->addNewItem($item->getProduct()->getId());
                 }
                 break;
             case 'comparelist':
                 break;
             default:
                 break;
         }
         $this->getQuote()->removeItem($item->getId());
         $this->setRecollect(true);
     }
     return $this;
 }
Example #9
0
 /**
  * return the  permalink based on permalink structure
  * which is defined in WP Admin
  *
  * @param Fishpig_Wordpress_Model_Post
  * @return string
  */
 public function getPermalink(Fishpig_Wordpress_Model_Post $post)
 {
     if ($this->useGuidLinks()) {
         return $this->getUrl('?p=' . $post->getId());
     } else {
         $structure = $this->_getExplodedPermalinkStructure();
         if (count($structure) > 0) {
             $url = array();
             foreach ($structure as $part) {
                 if (preg_match('/^\\%[a-zA-Z0-9_]{1,}\\%$/', $part)) {
                     $part = trim($part, '%');
                     if ($part === 'year') {
                         $url[] = $post->getPostDate('Y');
                     } else {
                         if ($part === 'monthnum') {
                             $url[] = $post->getPostDate('m');
                         } else {
                             if ($part === 'day') {
                                 $url[] = $post->getPostDate('d');
                             } else {
                                 if ($part === 'hour') {
                                     $url[] = $post->getPostDate('H');
                                 } else {
                                     if ($part === 'minute') {
                                         $url[] = $post->getPostDate('i');
                                     } else {
                                         if ($part === 'second') {
                                             $url[] = $post->getPostDate('s');
                                         } else {
                                             if ($part === 'post_id') {
                                                 $url[] = $post->getId();
                                             } else {
                                                 if ($part === 'postname') {
                                                     $url[] = urldecode($post->getPostName());
                                                 } else {
                                                     if ($part === 'category') {
                                                         $url[] = $this->_getPermalinkCategoryPortion($post);
                                                     } else {
                                                         if ($part === 'author') {
                                                         } else {
                                                             $response = new Varien_Object(array('value' => false));
                                                             Mage::dispatchEvent('wordpress_permalink_segment_unknown_getpermalink', array('response' => $response, 'post' => $post, 'segment' => $part));
                                                             if ($response->getValue() !== false) {
                                                                 $url[] = $response->getValue();
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 } else {
                     if ($part === '/') {
                         $partCount = count($url);
                         if ($partCount > 0 && $url[$partCount - 1] === $part) {
                             continue;
                         }
                     }
                     $url[] = $part;
                 }
             }
             if ($this->permalinkHasTrainingSlash()) {
                 $url[count($url) - 1] .= '/';
             }
             return $this->getUrl(implode('', $url));
         }
     }
 }
 /**
  * Format total value based on order currency
  *
  * @param   Varien_Object $total
  * @return  string
  */
 protected function formatTotalValue($total)
 {
     if (!$total->getIsFormated()) {
         return Mage::helper('core')->currency($total->getValue(), true, false);
     }
     return $total->getValue();
 }
Example #11
0
 /**
  * Checks if cart has quote items in it, if so returns true
  * this is used by lock quantity and lock shipping address
  * and method
  */
 public function cartHasQuoteItems()
 {
     $cart = Mage::getSingleton('checkout/cart')->getQuote();
     foreach ($cart->getAllItems() as $item) {
         $buyrequest = $item->getOptionByCode('info_buyRequest');
         $buyrequest = new Varien_Object(unserialize($buyrequest->getValue()));
         if ($buyrequest->getData(ITwebexperts_Request4quote_Model_Quote::QUOTE_ID_OPTION)) {
             return $buyrequest->getData(ITwebexperts_Request4quote_Model_Quote::QUOTE_ID_OPTION);
         }
     }
     return false;
 }
Example #12
0
 /**
  * Method is needed for specific actions to change given quote options values
  * according current product type logic
  * Example: the cataloginventory validation of decimal qty can change qty to int,
  * so need to change quote item qty option value too.
  *
  * @param   array           $options
  * @param   Varien_Object   $option
  * @param   mixed           $value
  * @param   Mage_Catalog_Model_Product $product
  * @return  Mage_Bundle_Model_Product_Type
  */
 public function updateQtyOption($options, Varien_Object $option, $value, $product = null)
 {
     $optionProduct = $option->getProduct($product);
     $optionUpdateFlag = $option->getHasQtyOptionUpdate();
     $optionCollection = $this->getOptionsCollection($product);
     $selections = $this->getSelectionsCollection($optionCollection->getAllIds(), $product);
     foreach ($selections as $selection) {
         if ($selection->getProductId() == $optionProduct->getId()) {
             foreach ($options as &$option) {
                 if ($option->getCode() == 'selection_qty_' . $selection->getSelectionId()) {
                     if ($optionUpdateFlag) {
                         $option->setValue(intval($option->getValue()));
                     } else {
                         $option->setValue($value);
                     }
                 }
             }
         }
     }
     return $this;
 }
Example #13
0
 /**
  * @param $observer
  */
 public function httpResponseSendBefore($observer)
 {
     $response = $observer->getEvent()->getResponse();
     if ($this->_getFpc()->isActive() && !$this->_cached && Mage::helper('fpc')->canCacheRequest() && $response->getHttpResponseCode() == 200) {
         $fullActionName = Mage::helper('fpc')->getFullActionName();
         $cacheableActions = Mage::helper('fpc')->getCacheableActions();
         if (in_array($fullActionName, $cacheableActions)) {
             $key = Mage::helper('fpc')->getKey();
             $body = $observer->getEvent()->getResponse()->getBody();
             $session = Mage::getSingleton('core/session');
             $formKey = $session->getFormKey();
             if ($formKey) {
                 $body = str_replace($formKey, self::FORM_KEY_PLACEHOLDER, $body);
                 $this->_placeholder[] = self::FORM_KEY_PLACEHOLDER;
                 $this->_html[] = $formKey;
             }
             $sid = $session->getEncryptedSessionId();
             if ($sid) {
                 $body = str_replace($sid, self::SESSION_ID_PLACEHOLDER, $body);
                 $this->_placeholder[] = self::SESSION_ID_PLACEHOLDER;
                 $this->_html[] = $sid;
             }
             // edit cacheTags via event
             $cacheTags = new Varien_Object();
             $cacheTags->setValue($this->_cacheTags);
             Mage::dispatchEvent('fpc_observer_collect_cache_tags', array('cache_tags' => $cacheTags));
             $this->_cacheTags = $cacheTags->getValue();
             $this->_getFpc()->save(time() . $body, $key, $this->_cacheTags);
             $this->_cached = true;
             $body = str_replace($this->_placeholder, $this->_html, $body);
             $observer->getEvent()->getResponse()->setBody($body);
         }
     }
 }
Example #14
0
 /**
  * Format total value based on order currency
  *
  * @param   Varien_Object $total
  * @return  string
  */
 public function formatValue($total)
 {
     if (!$total->getIsFormated()) {
         return $this->getOrder()->formatPrice($total->getValue());
     }
     return $total->getValue();
 }
Example #15
0
 protected function _getAttributeValue($item, $attrCode, $mapItem)
 {
     //Callback method configuration for special attribute
     Mage::app()->setCurrentStore($this->getProfile()->getStoreId());
     $attributeValueFilter = array('price_catalog_rule' => '_getPriceWithCatalogRule', 'url' => '_getProductUrl', 'price' => '_getPrice', 'gross_price' => '_getGrossPrice', 'qty' => '_getQuantity', 'is_in_stock' => '_getIsInStock', 'image_url' => '_getImageUrl', '_category' => '_getProductCategory', '_category_id' => '_getProductCategoryId', '_categories' => '_getProductCategories', '_media_gallery' => '_getMediaGallery', 'base_price_reference_amount' => '_getBasePriceReferenceAmount', 'is_salable' => '_getIsSalable', 'google_mapping' => '_getGoogleMapping', 'manage_stock' => '_getManageStock', '_type' => '_getType');
     $attrValue = $item->getData($attrCode);
     if (empty($attrValue)) {
         $item->load($item->getId());
         $attrValue = $item->getData($attrCode);
     }
     if (isset($attributeValueFilter[$attrCode])) {
         $attrValue = $this->{$attributeValueFilter}[$attrCode]($item, $mapItem);
     }
     if (isset($this->_attributeValues[$attrCode])) {
         if (isset($this->_attributeValues[$attrCode][$attrValue])) {
             $attrValue = $this->_attributeValues[$attrCode][$attrValue];
         }
     }
     if (isset($this->_attributeTypes[$attrCode])) {
         if ($this->_attributeTypes[$attrCode] == 'multiselect') {
             $currentValues = explode(',', $attrValue);
             foreach ($currentValues as &$currentValue) {
                 if (isset($this->_attributeValues[$attrCode][$currentValue])) {
                     $currentValue = $this->_attributeValues[$attrCode][$currentValue];
                 }
             }
             $attrValue = implode(',', $currentValues);
         }
     }
     Mage::app()->setCurrentStore(0);
     $eventObject = new Varien_Object(array('value' => $attrValue, 'attribute_code' => $attrCode, 'item' => $mapItem));
     Mage::dispatchEvent('mep_product_attribute_value', array('export' => $eventObject));
     return $eventObject->getValue();
 }
Example #16
0
 /**
  * @param array $tags
  * @return mixed
  */
 protected function dispatchCollectTagsEvent(array $tags)
 {
     $cacheTags = new Varien_Object();
     $cacheTags->setValue($tags);
     Mage::dispatchEvent('fpc_observer_collect_cache_tags', array('cache_tags' => $cacheTags));
     return $cacheTags->getValue();
 }
Example #17
0
 /**
  * @desc order comments or history
  * @param type $order
  * @param Varien_Object $response
  */
 protected function _addStatusHistoryComment($order, Varien_Object $response, $status = false)
 {
     Mage::log("_addStatusHistoryComment", Zend_Log::DEBUG, "adyen_notification.log", true);
     //notification
     $pspReference = $response->getData('pspReference');
     $success = trim($response->getData('success'));
     $success_result = strcmp($success, 'false') == 0 || !$success ? 'false' : 'true';
     $eventCode = $response->getData('eventCode');
     $reason = $response->getData('reason');
     $success = !empty($reason) ? "{$success_result} <br />reason:{$reason}" : $success_result;
     $klarnaReservationNumber = $response->getData('additionalData_additionalData_acquirerReference');
     $boletoPaidAmount = $response->getData('additionalData_boletobancario_paidAmount');
     //post
     $authResult = $response->getData('authResult');
     $pspReference = $response->getData('pspReference');
     //payment method
     $paymentMethod = $response->getData('paymentMethod');
     //data type
     $type = !empty($authResult) ? 'Adyen Result URL Notification(s):' : 'Adyen HTTP Notification(s):';
     switch ($type) {
         case 'Adyen Result URL Notification(s):':
             /*PCD*/
             // choose not to update the adyen_event_code in the order when the order is already on notification:Authorisation status and authresult = resultURL:Authorised
             if (!(substr($order->getAdyenEventCode(), 0, 13) == Adyen_Payment_Model_Event::ADYEN_EVENT_AUTHORISATION && $authResult == Adyen_Payment_Model_Event::ADYEN_EVENT_AUTHORISED)) {
                 Mage::log("Adyen Result URL order authResult:" . $authResult, Zend_Log::DEBUG, "adyen_notification.log", true);
                 $order->setAdyenEventCode($authResult);
             }
             $comment = Mage::helper('adyen')->__('%s <br /> authResult: %s <br /> pspReference: %s <br /> paymentMethod: %s', $type, $authResult, $pspReference, $paymentMethod);
             break;
         default:
             Mage::log("default order authResult:" . $eventCode . " : " . strtoupper($success_result), Zend_Log::DEBUG, "adyen_notification.log", true);
             if ($eventCode == Adyen_Payment_Model_Event::ADYEN_EVENT_REFUND) {
                 $currency = $order->getOrderCurrencyCode();
                 // check if it is a full or partial refund
                 $amount = Mage::helper('adyen')->formatAmount($response->getValue() / 100, $currency);
                 $orderAmount = Mage::helper('adyen')->formatAmount($order->getGrandTotal(), $currency);
                 if ($amount == $orderAmount) {
                     $order->setAdyenEventCode($eventCode . " : " . strtoupper($success_result));
                 } else {
                     $order->setAdyenEventCode("(PARTIAL) " . $eventCode . " : " . strtoupper($success_result));
                 }
             } else {
                 $order->setAdyenEventCode($eventCode . " : " . strtoupper($success_result));
             }
             // if payment method is klarna or openinvoice/afterpay show the reservartion number
             if (($paymentMethod == "klarna" || $paymentMethod == "afterpay_default" || $paymentMethod == "openinvoice") && ($klarnaReservationNumber != null && $klarnaReservationNumber != "")) {
                 $klarnaReservationNumberText = "<br /> reservationNumber: " . $klarnaReservationNumber;
             } else {
                 $klarnaReservationNumberText = "";
             }
             if ($boletoPaidAmount != null && $boletoPaidAmount != "") {
                 $boletoPaidAmountText = "<br /> Paid amount: " . $boletoPaidAmount;
             } else {
                 $boletoPaidAmountText = "";
             }
             $comment = Mage::helper('adyen')->__('%s <br /> eventCode: %s <br /> pspReference: %s <br /> paymentMethod: %s <br /> success: %s %s %s', $type, $eventCode, $pspReference, $paymentMethod, $success, $klarnaReservationNumberText, $boletoPaidAmountText);
             break;
     }
     $order->addStatusHistoryComment($comment, $status);
     $order->save();
 }
Example #18
0
 /**
  * Add field to Options form based on parameter configuration
  *
  * @param Varien_Object $parameter
  * @return Varien_Data_Form_Element_Abstract
  */
 protected function _addField($parameter)
 {
     $form = $this->getForm();
     $fieldset = $this->getMainFieldset();
     //$form->getElement('options_fieldset');
     // prepare element data with values (either from request of from default values)
     $fieldName = $parameter->getKey();
     $data = array('name' => $form->addSuffixToName($fieldName, 'parameters'), 'label' => $this->_translationHelper->__($parameter->getLabel()), 'required' => $parameter->getRequired(), 'class' => 'widget-option', 'note' => $this->_translationHelper->__($parameter->getDescription()));
     if ($values = $this->getWidgetValues()) {
         $data['value'] = isset($values[$fieldName]) ? $values[$fieldName] : '';
     } else {
         $data['value'] = $parameter->getValue();
         //prepare unique id value
         if ($fieldName == 'unique_id' && $data['value'] == '') {
             $data['value'] = md5(microtime(1));
         }
     }
     // prepare element dropdown values
     if ($values = $parameter->getValues()) {
         // dropdown options are specified in configuration
         $data['values'] = array();
         foreach ($values as $option) {
             $data['values'][] = array('label' => $this->_translationHelper->__($option['label']), 'value' => $option['value']);
         }
     } elseif ($sourceModel = $parameter->getSourceModel()) {
         $data['values'] = Mage::getModel($sourceModel)->toOptionArray();
     }
     // prepare field type or renderer
     $fieldRenderer = null;
     $fieldType = $parameter->getType();
     // hidden element
     if (!$parameter->getVisible()) {
         $fieldType = 'hidden';
     } elseif (false !== strpos($fieldType, '/')) {
         $fieldRenderer = $this->getLayout()->createBlock($fieldType);
         $fieldType = $this->_defaultElementType;
     }
     // instantiate field and render html
     $field = $fieldset->addField($this->getMainFieldsetHtmlId() . '_' . $fieldName, $fieldType, $data);
     if ($fieldRenderer) {
         $field->setRenderer($fieldRenderer);
     }
     // extra html preparations
     if ($helper = $parameter->getHelperBlock()) {
         $helperBlock = $this->getLayout()->createBlock($helper->getType(), '', $helper->getData());
         if ($helperBlock instanceof Varien_Object) {
             $helperBlock->setConfig($helper->getData())->setFieldsetId($fieldset->getId())->setTranslationHelper($this->_translationHelper)->prepareElementHtml($field);
         }
     }
     // dependencies from other fields
     $dependenceBlock = $this->getChild('form_after');
     $dependenceBlock->addFieldMap($field->getId(), $fieldName);
     if ($parameter->getDepends()) {
         foreach ($parameter->getDepends() as $from => $row) {
             $values = isset($row['values']) ? array_values($row['values']) : (string) $row['value'];
             $dependenceBlock->addFieldDependence($fieldName, $from, $values);
         }
     }
     return $field;
 }
Example #19
0
 /**
  * @desc Handle Refund here
  * @todo create credit memo && set order status to closed
  * @param Varien_Object $order
  * @param Varien_Object $response
  * @since 0.0.9.2
  */
 public function refundOrder($order, $response)
 {
     //skip orders with [refund-received]
     $pspReference = trim($response->getData('pspReference'));
     $result = Mage::getModel('adyen/event')->getEvent($pspReference, '[refund-received]');
     if (!empty($result)) {
         $this->_writeLog("\nSkip refund process, as refund initiated via Magento id: {$order->getIncrementId()}");
         return false;
     }
     $_mail = (bool) $this->_getConfigData('send_update_mail');
     $amount = $response->getValue() / 100;
     if ($order->canCreditmemo()) {
         $service = Mage::getModel('sales/service_order', $order);
         $creditmemo = $service->prepareCreditmemo();
         $creditmemo->getOrder()->setIsInProcess(true);
         //set refund data on the order
         $creditmemo->setGrandTotal($amount);
         $creditmemo->setBaseGrandTotal($amount);
         $creditmemo->save();
         try {
             Mage::getModel('core/resource_transaction')->addObject($creditmemo)->addObject($creditmemo->getOrder())->save();
             //refund
             $creditmemo->refund();
             $transactionSave = Mage::getModel('core/resource_transaction')->addObject($creditmemo)->addObject($creditmemo->getOrder());
             if ($creditmemo->getInvoice()) {
                 $transactionSave->addObject($creditmemo->getInvoice());
             }
             $transactionSave->save();
             if ($_mail) {
                 $creditmemo->getOrder()->setCustomerNoteNotify(true);
                 $creditmemo->sendEmail();
             }
         } catch (Exception $e) {
             $this->_writeLog($e->getMessage());
         }
     } else {
         $this->_writeLog("\nOrder can not refund {$order->getIncrementId()}");
     }
 }
Example #20
0
 /**
  * Get rendered row value
  *
  * @param Varien_Object $row
  * @return string
  */
 public function renderRowValue(Varien_Object $row)
 {
     $value = $row->getValue();
     if (is_array($value)) {
         $value = implode("\n", $value);
     }
     if (!$row->getSkipHtmlEscaping()) {
         $value = $this->escapeHtml($value);
     }
     return nl2br($value);
 }
Example #21
0
 /**
  * Format price using order currency
  *
  * @param   Varien_Object $total
  * @return  string
  */
 protected function _formatPrice($total)
 {
     if (!$total->getIsFormated()) {
         return $this->getOrder()->getOrderCurrency()->formatPrecision($total->getValue(), 2, array(), false);
     }
     return $total->getValue();
 }
Example #22
0
 /**
  * Move quote item to another items list
  *
  * @param   int|Mage_Sales_Model_Quote_Item $item
  * @param   string $moveTo
  * @param   int $qty
  * @return  Mage_Adminhtml_Model_Sales_Order_Create
  */
 public function moveQuoteItem($item, $moveTo, $qty)
 {
     $item = $this->_getQuoteItem($item);
     if ($item) {
         $removeItem = false;
         $moveTo = explode('_', $moveTo);
         switch ($moveTo[0]) {
             case 'order':
                 $info = $item->getBuyRequest();
                 $info->setOptions($this->_prepareOptionsForRequest($item))->setQty($qty);
                 $product = Mage::getModel('catalog/product')->setStoreId($this->getQuote()->getStoreId())->load($item->getProduct()->getId());
                 $product->setSkipCheckRequiredOption(true);
                 $newItem = $this->getQuote()->addProduct($product, $info);
                 if (is_string($newItem)) {
                     Mage::throwException($newItem);
                 }
                 $product->unsSkipCheckRequiredOption();
                 $newItem->checkData();
                 $this->_needCollectCart = true;
                 break;
             case 'cart':
                 $cart = $this->getCustomerCart();
                 if ($cart && is_null($item->getOptionByCode('additional_options'))) {
                     //options and info buy request
                     $product = Mage::getModel('catalog/product')->setStoreId($this->getQuote()->getStoreId())->load($item->getProduct()->getId());
                     $info = $item->getOptionByCode('info_buyRequest');
                     if ($info) {
                         $info = new Varien_Object(unserialize($info->getValue()));
                         $info->setQty($qty);
                         $info->setOptions($this->_prepareOptionsForRequest($item));
                     } else {
                         $info = new Varien_Object(array('product_id' => $product->getId(), 'qty' => $qty, 'options' => $this->_prepareOptionsForRequest($item)));
                     }
                     $cartItem = $cart->addProduct($product, $info);
                     if (is_string($cartItem)) {
                         Mage::throwException($cartItem);
                     }
                     $cartItem->setPrice($item->getProduct()->getPrice());
                     $this->_needCollectCart = true;
                     $removeItem = true;
                 }
                 break;
             case 'wishlist':
                 $wishlist = null;
                 if (!isset($moveTo[1])) {
                     $wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($this->getSession()->getCustomer(), true);
                 } else {
                     $wishlist = Mage::getModel('wishlist/wishlist')->load($moveTo[1]);
                     if (!$wishlist->getId() || $wishlist->getCustomerId() != $this->getSession()->getCustomerId()) {
                         $wishlist = null;
                     }
                 }
                 if (!$wishlist) {
                     Mage::throwException(Mage::helper('wishlist')->__('Could not find wishlist'));
                 }
                 $wishlist->setStore($this->getSession()->getStore())->setSharedStoreIds($this->getSession()->getStore()->getWebsite()->getStoreIds());
                 if ($wishlist->getId() && $item->getProduct()->isVisibleInSiteVisibility()) {
                     $info = $item->getBuyRequest();
                     $info->setOptions($this->_prepareOptionsForRequest($item))->setQty($qty)->setStoreId($this->getSession()->getStoreId());
                     $wishlist->addNewItem($item->getProduct(), $info);
                     $removeItem = true;
                 }
                 break;
             case 'remove':
                 $removeItem = true;
                 break;
             default:
                 break;
         }
         if ($removeItem) {
             $this->getQuote()->deleteItem($item);
         }
         $this->setRecollect(true);
     }
     return $this;
 }
 /**
  * Retrieve a meta value
  *
  * @param string $key
  * @return false|string
  */
 public function getMetaValue($key)
 {
     if ($this->hasMeta()) {
         if (!isset($this->_meta[$key])) {
             $value = $this->getResource()->getMetaValue($this, $this->_getRealMetaKey($key));
             $meta = new Varien_Object(array('key' => $key, 'value' => $value));
             Mage::dispatchEvent($this->_eventPrefix . '_get_meta_value', array('object' => $this, $this->_eventObject => $this, 'meta' => $meta));
             $this->_meta[$key] = $meta->getValue();
         }
         return $this->_meta[$key];
     }
     return false;
 }
Example #24
0
 /**
  * Format price using order currency
  *
  * @param   Varien_Object $total
  * @return  string
  */
 protected function _formatPrice($total)
 {
     if (!$total->getIsFormated()) {
         return Mage::helper('xmlconnect/customer_order')->formatPrice($this, $total->getValue());
     }
     return $total->getValue();
 }
Example #25
0
 public function uploadAndImport(Varien_Object $object)
 {
     $csvFile = $_FILES["groups"]["tmp_name"]["tablerate"]["fields"]["import"]["value"];
     if (!empty($csvFile)) {
         $csv = trim(file_get_contents($csvFile));
         $table = Mage::getSingleton('core/resource')->getTableName('shipping/tablerate');
         $websiteId = $object->getScopeId();
         $websiteModel = Mage::app()->getWebsite($websiteId);
         $conditionName = $object->getValue();
         if ($conditionName[0] == '_') {
             $conditionName = substr($conditionName, 1, strpos($conditionName, '/') - 1);
         } else {
             $conditionName = $websiteModel->getConfig('carriers/tablerate/condition_name');
         }
         $conditionFullName = Mage::getModel('shipping/carrier_tablerate')->getCode('condition_name_short', $conditionName);
         if (!empty($csv)) {
             $exceptions = array();
             $csvLines = explode("\n", $csv);
             $csvLine = array_shift($csvLines);
             $csvLine = $this->_getCsvValues($csvLine);
             if (count($csvLine) < 5) {
                 $exceptions[0] = Mage::helper('shipping')->__('Invalid Table Rates File Format');
             }
             $countryCodes = array();
             $regionCodes = array();
             foreach ($csvLines as $k => $csvLine) {
                 $csvLine = $this->_getCsvValues($csvLine);
                 if (count($csvLine) > 0 && count($csvLine) < 5) {
                     $exceptions[0] = Mage::helper('shipping')->__('Invalid Table Rates File Format');
                 } else {
                     $countryCodes[] = $csvLine[0];
                     $regionCodes[] = $csvLine[1];
                 }
             }
             if (empty($exceptions)) {
                 $data = array();
                 $countryCodesToIds = array();
                 $regionCodesToIds = array();
                 $countryCollection = Mage::getResourceModel('directory/country_collection')->addCountryCodeFilter($countryCodes)->load();
                 foreach ($countryCollection->getItems() as $country) {
                     $countryCodesToIds[$country->getData('iso3_code')] = $country->getData('country_id');
                 }
                 $regionCollection = Mage::getResourceModel('directory/region_collection')->addRegionCodeFilter($regionCodes)->load();
                 foreach ($regionCollection->getItems() as $region) {
                     $regionCodesToIds[$region->getData('code')] = $region->getData('region_id');
                 }
                 foreach ($csvLines as $k => $csvLine) {
                     $csvLine = $this->_getCsvValues($csvLine);
                     if (empty($countryCodesToIds) || !array_key_exists($csvLine[0], $countryCodesToIds)) {
                         $countryId = '0';
                         if ($csvLine[0] != '*' && $csvLine[0] != '') {
                             $exceptions[] = Mage::helper('shipping')->__('Invalid Country "%s" in the Row #%s', $csvLine[0], $k + 1);
                         }
                     } else {
                         $countryId = $countryCodesToIds[$csvLine[0]];
                     }
                     if (empty($regionCodesToIds) || !array_key_exists($csvLine[1], $regionCodesToIds)) {
                         $regionId = '0';
                         if ($csvLine[1] != '*' && $csvLine[1] != '') {
                             $exceptions[] = Mage::helper('shipping')->__('Invalid Region/State "%s" in the Row #%s', $csvLine[1], $k + 1);
                         }
                     } else {
                         $regionId = $regionCodesToIds[$csvLine[1]];
                     }
                     if ($csvLine[2] == '*' || $csvLine[2] == '') {
                         $zip = '';
                     } else {
                         $zip = $csvLine[2];
                     }
                     if (!$this->_isPositiveDecimalNumber($csvLine[3]) || $csvLine[3] == '*' || $csvLine[3] == '') {
                         $exceptions[] = Mage::helper('shipping')->__('Invalid %s "%s" in the Row #%s', $conditionFullName, $csvLine[3], $k + 1);
                     } else {
                         $csvLine[3] = (double) $csvLine[3];
                     }
                     if (!$this->_isPositiveDecimalNumber($csvLine[4])) {
                         $exceptions[] = Mage::helper('shipping')->__('Invalid Shipping Price "%s" in the Row #%s', $csvLine[4], $k + 1);
                     } else {
                         $csvLine[4] = (double) $csvLine[4];
                     }
                     $data[] = array('website_id' => $websiteId, 'dest_country_id' => $countryId, 'dest_region_id' => $regionId, 'dest_zip' => $zip, 'condition_name' => $conditionName, 'condition_value' => $csvLine[3], 'price' => $csvLine[4]);
                     $dataDetails[] = array('country' => $csvLine[0], 'region' => $csvLine[1]);
                 }
             }
             if (empty($exceptions)) {
                 $connection = $this->_getWriteAdapter();
                 $condition = array($connection->quoteInto('website_id = ?', $websiteId), $connection->quoteInto('condition_name = ?', $conditionName));
                 $connection->delete($table, $condition);
                 foreach ($data as $k => $dataLine) {
                     try {
                         $connection->insert($table, $dataLine);
                     } catch (Exception $e) {
                         $exceptions[] = Mage::helper('shipping')->__('Duplicate Row #%s (Country "%s", Region/State "%s", Zip "%s" and Value "%s")', $k + 1, $dataDetails[$k]['country'], $dataDetails[$k]['region'], $dataLine['dest_zip'], $dataLine['condition_value']);
                     }
                 }
             }
             if (!empty($exceptions)) {
                 throw new Exception("\n" . implode("\n", $exceptions));
             }
         }
     }
 }