/** * Update stock data of multiple products at once * * @param array $itemData * @return array */ public function inventoryPush($itemData) { if (isset($itemData['records'])) { $itemData = $itemData['records']; } $response = array(); $response['records'] = array(); $orderItemsCollection = Mage::getResourceModel('retailops_api/api')->getRetailopsReadyOrderItems(); $orderItems = $this->filterOrderItems($orderItemsCollection); $productIds = $this->getProductIds($itemData); foreach ($itemData as $item) { try { $itemObj = new Varien_Object($item); Mage::dispatchEvent('retailops_inventory_push_record', array('record' => $itemObj)); $result = array(); $result['sku'] = $itemObj->getSku(); $itemObj->setQty($itemObj->getQuantity()); // api update accepts qty not quantity parameter $qty = $itemObj->getQty(); if (isset($orderItems[$itemObj->getSku()])) { $qty = $itemObj->getQty() - $orderItems[$itemObj->getSku()]; } $itemObj->setQty($qty); Mage::dispatchEvent('retailops_inventory_push_record_qty_processed', array('record' => $itemObj)); $this->update($productIds[$itemObj->getSku()], $itemObj->getData()); $result['status'] = RetailOps_Api_Helper_Data::API_STATUS_SUCCESS; } catch (Mage_Core_Exception $e) { $result['status'] = RetailOps_Api_Helper_Data::API_STATUS_FAIL; $result['error'] = array('code' => $e->getCode(), 'message' => $e->getMessage()); } $response['records'][] = $result; } return $response; }
/** * * @loadFixture testPrepareCart * @dataProvider provider__testPrepareCartObserverQty * The main goul of this test is to check if the error will be araised if items are added one by one * */ public function testPrepareCartObserverQty($dealId, $qty, $productId, $expectedPrice, $infoBuyRequest, $count, $uid) { $deal = Mage::getModel('collpur/deal')->load($dealId); /* set deal id in request */ Mage::app()->getRequest()->setParam('deal_id', $dealId); Mage::app()->getRequest()->setParam('product', $productId); $observer = new Varien_Object(); $buyRequest = new Varien_Object(); $product = Mage::getModel('catalog/product')->load($productId); $buyRequest->setQty($qty); $observer->setBuyRequest($buyRequest); $observer->setProduct($product); /* set quote id and replace existing one in session */ $quote = $this->getModelMock('sales/quote'); $quoteItemsCollection = array(); for ($i = 0; $i < $count; $i++) { $item = $this->getModelMock('sales/quote_item'); $optionByCode = new Varien_Object(); $optionByCode->setValue($infoBuyRequest); $item->expects($this->any())->method('getOptionByCode')->will($this->returnValue($optionByCode)); $item->expects($this->any())->method('getQty')->will($this->returnValue(1)); $quoteItemsCollection[] = $item; } $quote->expects($this->any())->method('getId')->will($this->returnValue(1)); $quote->expects($this->any())->method('getItemsCollection')->will($this->returnValue($quoteItemsCollection)); Mage::getSingleton('checkout/session')->replaceQuote($quote); if ($uid == '002') { $this->setExpectedException('Mage_Checkout_Exception'); } Mage::getModel('collpur/observer')->prepareCart($observer); }
/** * Get request for product add to cart procedure * * @param mixed $requestInfo * @return Varien_Object */ protected function _getProductRequest($requestInfo) { if ($requestInfo instanceof Varien_Object) { $request = $requestInfo; } elseif (is_numeric($requestInfo)) { $request = new Varien_Object(); $request->setQty($requestInfo); } else { $request = new Varien_Object($requestInfo); } if (!$request->hasQty()) { $request->setQty(1); } return $request; }
public function estimate() { $product = $this->getProduct(); $addToCartInfo = (array) $product->getAddToCartInfo(); $addressInfo = (array) $this->getAddressInfo(); if (!$product instanceof Mage_Catalog_Model_Product || !$product->getId()) { Mage::throwException(Mage::helper('webdevlopers_productpageshipping')->__('Please specify a valid product')); } if (!isset($addressInfo['country_id'])) { Mage::throwException(Mage::helper('webdevlopers_productpageshipping')->__('Please specify a country')); } if (empty($addressInfo['cart'])) { $this->resetQuote(); } $shippingAddress = $this->getQuote()->getShippingAddress(); $shippingAddress->setCountryId($addressInfo['country_id']); if (isset($addressInfo['region_id'])) { $shippingAddress->setRegionId($addressInfo['region_id']); } if (isset($addressInfo['postcode'])) { $shippingAddress->setPostcode($addressInfo['postcode']); } if (isset($addressInfo['region'])) { $shippingAddress->setRegion($addressInfo['region']); } if (isset($addressInfo['city'])) { $shippingAddress->setCity($addressInfo['city']); } $shippingAddress->setCollectShippingRates(true); if (isset($addressInfo['coupon_code'])) { $this->getQuote()->setCouponCode($addressInfo['coupon_code']); } $request = new Varien_Object($addToCartInfo); if ($product->getStockItem()) { $minimumQty = $product->getStockItem()->getMinSaleQty(); if ($minimumQty > 0 && $request->getQty() < $minimumQty) { $request->setQty($minimumQty); } } $result = $this->getQuote()->addProduct($product, $request); if (is_string($result)) { Mage::throwException($result); } Mage::dispatchEvent('checkout_cart_product_add_after', array('quote_item' => $result, 'product' => $product)); $this->getQuote()->collectTotals(); $this->_result = $shippingAddress->getGroupedAllShippingRates(); return $this; }
/** * Use our own method to get buyRequest * @param Mage_Sales_Model_Quote_Item $salesItem * @return Varien_Object * */ public function getBuyRequest($salesItem, $option = false) { if ($option) { $option = $salesItem->getOptionByCode('info_buyRequest'); $buyRequest = new Varien_Object($option && $option->getValue() ? unserialize($option->getValue()) : null); $buyRequest->setOriginalQty($buyRequest->getQty())->setQty($salesItem->getQty() * 1); return $buyRequest; } $option = $salesItem->getProductOptionByCode('info_buyRequest'); if (!$option) { $option = array(); } $buyRequest = new Varien_Object($option); $buyRequest->setQty($salesItem->getQtyOrdered() * 1); return $buyRequest; }
/** * Called from payperrentals/inventory helper after_booked event of getBooked() * * Observer that adds maintenance quantity when using specific maintenance dates to * the serialized inventory field of the product * * @param Varien_Event_Observer $observer */ function addMaintenanceToSerialized(Varien_Event_Observer $observer) { $booked = $observer->getResult()->getBooked(); $reservedCollection = $observer->getReservedCollection(); /** @var $maintenanceColl ITwebexperts_Maintenance_Model_Mysql4_Items_Collection */ foreach ($booked as $productid => $booking) { $maintenanceColl = Mage::getModel('simaintenance/items')->getCollection(); $maintenanceColl->addFieldToFilter('product_id', $productid); foreach ($maintenanceColl as $maintenanceItem) { if (is_null($maintenanceItem->getStartDate()) || $maintenanceItem->getSpecificDates()) { continue; } $start = strtotime($maintenanceItem->getStartDate()); $end = strtotime($maintenanceItem->getEndDate()); $usetimes = Mage::getResourceModel('catalog/product')->getAttributeRawValue($productid, 'payperrentals_use_times', Mage::app()->getStore()->getStoreId()); if (date('H:i:s', $start) != '00:00:00' || date('H:i:s', $end) != '23:59:00' && date('H:i:s', $end) != '23:58:59' || $usetimes == 1) { $configHelper = Mage::helper('payperrentals/config'); $timeIncrement = $configHelper->getTimeIncrement() * 60; } else { $timeIncrement = 3600 * 24; } while ($start < $end) { $dateFormatted = date('Y-m-d H:i', $start); if (!isset($booking[$dateFormatted])) { $vObject = new Varien_Object(); $vObject->setQty($maintenanceItem->getQuantity()); $vObject->setOrders(array('m')); $booking[$dateFormatted] = $vObject; } else { $vObject = $booking[$dateFormatted]; $vObject->setQty($vObject->getQty() + $maintenanceItem->getQuantity()); $orderArr = $vObject->getOrders(); $orderArr = array_merge($orderArr, array('m')); $vObject->setOrders($orderArr); } $booked[$productid][$dateFormatted] = $vObject; $start += $timeIncrement; } } } $observer->getResult()->setBooked($booked); }
/** * Initialize creation data from existing order Item * * @param Mage_Sales_Model_Order_Item $orderItem * @return Mage_Sales_Model_Quote_Item | string */ public function initFromOrderItem(Mage_Sales_Model_Order_Item $orderItem, $qty = 1) { if (!$orderItem->getId()) { return $this; } $product = Mage::getModel('catalog/product')->setStoreId($this->getSession()->getStoreId())->load($orderItem->getProductId()); if ($product->getId()) { $info = $orderItem->getProductOptionByCode('info_buyRequest'); $info = new Varien_Object($info); $product->setSkipCheckRequiredOption(true); $info->setQty($orderItem->getQtyOrdered()); $item = $this->getQuote()->addProduct($product, $info); if (is_string($item)) { return $item; } //$item->setQty($qty); if ($additionalOptions = $orderItem->getProductOptionByCode('additional_options')) { $item->addOption(new Varien_Object(array('product' => $item->getProduct(), 'code' => 'additional_options', 'value' => serialize($additionalOptions)))); } Mage::dispatchEvent('sales_convert_order_item_to_quote_item', array('order_item' => $orderItem, 'quote_item' => $item)); return $item; } return $this; }
public function addProductAdvanced(Mage_Catalog_Model_Product $product, $request = null, $processMode = null) { if ($request === null) { $request = 1; } if (is_numeric($request)) { $request = new Varien_Object(array('qty' => $request)); } if (!$request instanceof Varien_Object) { Mage::throwException(Mage::helper('sales')->__('Invalid request for adding product to quote.')); } switch ($product->getTypeId()) { case 'simple': case 'virtual': case 'downloadable': case 'configurable': case 'bundle': $qty = $request->getQty(); if ($qty > 1) { $request->setQty(1); for ($i = 1; $i < $qty; $i++) { $lineProduct = clone $product; $lineRequest = clone $request; $this->addProductAdvanced($lineProduct, $lineRequest, $processMode); } } break; case 'grouped': $superGroup = $request->getSuperGroup(); foreach ($superGroup as $productId => $qty) { if ($qty > 1) { for ($i = 1; $i < $qty; $i++) { $customSuperGroup = $request->getSuperGroup(); foreach ($customSuperGroup as $customProductId => $customQty) { $customSuperGroup[$customProductId] = $customProductId === $productId ? 1 : 0; } $lineProduct = clone $product; $lineRequest = clone $request; $lineRequest->setSuperGroup($customSuperGroup); $this->addProductAdvanced($lineProduct, $lineRequest, $processMode); } } $superGroup[$productId] = $qty > 0 ? 1 : 0; } $request->setSuperGroup($superGroup); break; } $cartCandidates = $product->getTypeInstance(true)->prepareForCartAdvanced($request, $product, $processMode); /** * Error message */ if (is_string($cartCandidates)) { return $cartCandidates; } /** * If prepare process return one object */ if (!is_array($cartCandidates)) { $cartCandidates = array($cartCandidates); } $parentItem = null; $errors = array(); $items = array(); foreach ($cartCandidates as $candidate) { // Child items can be sticked together only within their parent $stickWithinParent = $candidate->getParentProductId() ? $parentItem : null; $candidate->setStickWithinParent($stickWithinParent); $item = $this->_addCatalogProduct($candidate, $candidate->getCartQty()); if ($request->getResetCount() && !$stickWithinParent && $item->getId() === $request->getId()) { $item->setData('qty', 0); } $items[] = $item; /** * As parent item we should always use the item of first added product */ if (!$parentItem) { $parentItem = $item; } if ($parentItem && $candidate->getParentProductId()) { $item->setParentItem($parentItem); } /** * We specify qty after we know about parent (for stock) */ $item->addQty($candidate->getCartQty()); // collect errors instead of throwing first one if ($item->getHasError()) { $message = $item->getMessage(); if (!in_array($message, $errors)) { // filter duplicate messages $errors[] = $message; } } } if (!empty($errors)) { Mage::throwException(implode("\n", $errors)); } Mage::dispatchEvent('sales_quote_product_add_after', array('items' => $items)); return $item; }
public function updateAttQtyAction() { $result = array(); $result['error'] = false; $id = (int) $this->getRequest()->getParam('id'); $result['item_id'] = $id; $params = $this->getRequest()->getParams(); if (!isset($params['options'])) { $params['options'] = array(); } $params['super_attribute'] = Zend_Json::decode($params['super_attribute']); try { $cart = Mage::getSingleton('checkout/cart'); $quoteItem = $cart->getQuote()->getItemById($id); if (!$quoteItem) { Mage::throwException($this->__('Quote item is not found.')); } $params['qty'] = $quoteItem->getQty(); if (method_exists($cart, 'updateItem')) { $item = $cart->updateItem($id, new Varien_Object($params)); } else { $request = new Varien_Object($params); $productId = $quoteItem->getProduct()->getId(); $product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($productId); if ($product->getStockItem()) { $minimumQty = $product->getStockItem()->getMinSaleQty(); if ($minimumQty && $minimumQty > 0 && $request->getQty() < $minimumQty && !$cart->getQuote()->hasProductId($productId)) { $request->setQty($minimumQty); } } $item = $cart->getQuote()->addProduct($product, $request); if ($item->getParentItem()) { $item = $item->getParentItem(); } if ($item->getId() != $id) { $cart->getQuote()->removeItem($id); $items = $cart->getQuote()->getAllItems(); foreach ($items as $_item) { if ($_item->getProductId() == $productId && $_item->getId() != $item->getId()) { if ($item->compare($_item)) { $item->setQty($item->getQty() + $_item->getQty()); $this->removeItem($_item->getId()); break; } } } } else { $item->setQty($request->getQty()); } } if (is_string($item)) { Mage::throwException($item); } $cart->save(); Mage::getSingleton('checkout/session')->setCartWasUpdated(true); Mage::dispatchEvent('checkout_cart_update_item_complete', array('item' => $item, 'request' => $this->getRequest(), 'response' => $this->getResponse())); } catch (Mage_Core_Exception $e) { $success_param = array(); if ($quoteItem) { if ($quoteItem->getProduct()->getTypeInstance(true)->getSpecifyOptionMessage() == $e->getMessage()) { $all_params = $params['super_attribute']; $productCollection = $quoteItem->getProduct()->getTypeInstance(true)->getUsedProductCollection($quoteItem->getProduct()); foreach ($all_params as $attribute_id => $value) { $tmp_params = $success_param; $tmp_params[$attribute_id] = $value; $productObject = $quoteItem->getProduct()->getTypeInstance(true)->getProductByAttributes($tmp_params, $quoteItem->getProduct()); if ($productObject && $productObject->getId()) { $success_param[$attribute_id] = $value; $productCollection->addAttributeToFilter($attribute_id, $value); } else { $result['update_attribute'] = $attribute_id; $attribute_data = array(); $attribute = null; $product = Mage::getModel('catalog/product')->load($quoteItem->getProduct()->getId()); $product->getTypeInstance(true)->getUsedProductAttributeIds($product); $usedAttributes = $product->getData('_cache_instance_used_attributes'); foreach ($usedAttributes as $key => $_arrtibute) { if ($key == $attribute_id) { $attribute = $_arrtibute; break; } } foreach ($productCollection as $_product) { $_product = Mage::getModel('catalog/product')->load($_product->getId()); if ($_product->isSaleable()) { $_key = $_product->getData($attribute->getProductAttribute()->getAttributeCode()); foreach ($attribute->getPrices() as $_v) { if ($_v['value_index'] == $_key) { $attribute_data[$_key] = $_v['label']; break; } } } } $result['attribute_data'] = $attribute_data; break; } } } } $result['choosetext'] = Mage::helper('catalog')->__('Choose an Option...'); $result['success_param'] = $success_param; $result['error'] = true; $result['message'] = $e->getMessage(); } catch (Exception $e) { $result['error'] = true; $result['message'] = $e->getMessage(); Mage::logException($e); } if (!$result['error']) { if ($total = $this->getCartTotal()) { $result['total'] = $total; } if ($shipping = $this->getCartShipping()) { $result['shipping'] = $shipping; } } $result['items_html'] = $this->getCartItems(); $result['cart'] = Mage::getModel('flycart/observer')->getCartSidebar(); $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result)); }
protected function _addProductsToQuote($productInCardList, $paramsArray) { $productInCardList = $this->_concatenateProductsInQuote($productInCardList); foreach ($productInCardList as $productItem) { $product = Mage::getModel('catalog/product')->load($productItem['id']); if (!$product->getId()) { throw new LogicException('Product does not exist. Probably it was deleted.'); } if ($product->getStatus() === Mage_Catalog_Model_Product_Status::STATUS_DISABLED) { throw new LogicException('Product is disabled.'); } $productTypeId = $product->getTypeId(); if ($productTypeId == Ess_M2ePro_Model_MagentoProduct::TYPE_GROUPED) { // Grouped product converted to assigned simple if (!isset($productItem['options'])) { throw new LogicException('The item does not have options. At the current version, Order Import for grouped product supports only multi variation listing.'); } $product = $this->_getRelatedProductFromGroupedForEbayData($product, $productItem); if (is_null($product)) { throw new LogicException('There is no associated products found for grouped product.'); } else { $productTypeId = $product->getTypeId(); } } $productItem['price'] = $this->_getConvertedPrice($productItem['price']); $request = new Varien_Object(); $request->setQty($productItem['qty']); switch ($productTypeId) { case Ess_M2ePro_Model_MagentoProduct::TYPE_SIMPLE: $haveRequiredOptionsInstant = $product->getTypeInstance(true)->hasRequiredOptions($product); $haveRequiredOptions = $product->hasRequiredOptions(); if ($haveRequiredOptions && !$product->getRequiredOptions()) { $haveRequiredOptions = false; // important: possible incorect behavior } if ($haveRequiredOptionsInstant || $haveRequiredOptions || $this->_checkSimpleProductHasRequiredCustomOptions($product)) { $customOptionsData = array(); if (isset($productItem['options']) && count($productItem['options'])) { // Have multivariation data for simple product // Use to set Custom Options data $customOptionsData = $this->_getCustomOptionsForEbayData($productItem); $this->_addNotifyMessage('Product has <b>Required Options</b>. Selected Options Values are taken from eBay Multi Variation Data'); } else { // No multivariation data, set first required option $customOptionsData = $this->_getRandomCustomOptions($productItem); $this->_addNotifyMessage('Product has <b>Required Options</b>. First option value is selected.'); } $request->setOptions($customOptionsData['options']); // Dec price for percent change (after apply percent price inc = need price) $productItem['price'] = $productItem['price'] / (1 + $customOptionsData['price_change_percent'] / 100); // Change for custom options price. price_change_fixed low that 0 when option inc price, more 0 - when inc $productItem['price'] += $customOptionsData['price_change_fixed'] / (1 + $customOptionsData['price_change_percent'] / 100); } // end of $haveRequriedOptions break; case Ess_M2ePro_Model_MagentoProduct::TYPE_CONFIGURABLE: if (!isset($productItem['options'])) { throw new LogicException('The item does not have options. At the current version, Order Import for configurable product supports only multi variation listing.'); } $configurableOptions = $this->_getConfigurableAttributeForEbayData($productItem); // Set selected attributes $request->setSuperAttribute($configurableOptions['options']); // Each option value can change total price value, remove // this changes for equal: order price = eBay sold price $productItem['price'] += $configurableOptions['price_change']; break; case Ess_M2ePro_Model_MagentoProduct::TYPE_BUNDLE: if (!isset($productItem['options'])) { throw new LogicException('The item does not have options. At the current version, Order Import for bundle product supports only multi variation listing.'); } $bundleOptions = $this->_getBundleOptionsForEbayData($productItem); $request->setBundleOption($bundleOptions['options']); // $bundleQty = array(); // foreach ($bundleOptions['options'] as $optionId => $optionValue) { // $bundleQty[$optionId] = $productItem['qty']; // } // $request->setBundleOptionQty($bundleQty); // $request->setQty(1); $this->_addNotifyMessage('Price for Bundle item is taken from Magento store.'); break; default: throw new LogicException('At the current version, Order Import does not support product type: ' . $productTypeId . ''); } $product->setPrice($productItem['price']); $product->setSpecialPrice($productItem['price']); $this->_initProductTaxClassId($product, $paramsArray['taxPercent']); $result = $this->_quote->addProduct($product, $request); if (is_string($result)) { throw new Exception($result); } // TODO: ugly hack //if ($productTypeId == Ess_M2ePro_Model_MagentoProduct::TYPE_BUNDLE || // Ess_M2ePro_Model_MagentoProduct::TYPE_CONFIGURABLE || // Ess_M2ePro_Model_MagentoProduct::TYPE_GROUPED) { foreach ($paramsArray['products'] as $tempProduct) { if ($tempProduct['id'] == $product->getId()) { $tempQuoteItem = $this->_quote->getItemByProduct($product); if ($tempQuoteItem !== false) { $tempQuoteItem->setNoDiscount(1); $tempQuoteItem->setOriginalCustomPrice($this->_getConvertedPrice($tempProduct['price'])); } break; } } //} } // foreach $productInCardList }
/** * Returns formatted buy request - object, holding request received from * product view page with keys and options for configured product * * @return Varien_Object */ public function getBuyRequest() { $option = $this->getProductOptionByCode('info_buyRequest'); if (!$option) { $option = array(); } $buyRequest = new Varien_Object($option); $buyRequest->setQty($this->getQtyOrdered() * 1); return $buyRequest; }
public function changeattributecartAction() { $result = array(); $result['error'] = false; $id = (int) $this->getRequest()->getParam('id'); $result['item_id'] = $id; $params = $this->getRequest()->getParams(); if (!isset($params['options'])) { $params['options'] = array(); } $params['super_attribute'] = Zend_Json::decode($params['super_attribute']); try { $cart = Mage::getSingleton('checkout/cart'); $quoteItem = $cart->getQuote()->getItemById($id); if (!$quoteItem) { Mage::throwException($this->__('Quote item is not found.')); } $params['qty'] = $quoteItem->getQty(); if (method_exists($cart, 'updateItem')) { $item = $cart->updateItem($id, new Varien_Object($params)); } else { $request = new Varien_Object($params); $productId = $quoteItem->getProduct()->getId(); $product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($productId); if ($product->getStockItem()) { $minimumQty = $product->getStockItem()->getMinSaleQty(); if ($minimumQty && $minimumQty > 0 && $request->getQty() < $minimumQty && !$cart->getQuote()->hasProductId($productId)) { $request->setQty($minimumQty); } } $item = $cart->getQuote()->addProduct($product, $request); if ($item->getParentItem()) { $item = $item->getParentItem(); } if ($item->getId() != $id) { $cart->getQuote()->removeItem($id); $items = $cart->getQuote()->getAllItems(); foreach ($items as $_item) { if ($_item->getProductId() == $productId && $_item->getId() != $item->getId()) { if ($item->compare($_item)) { $item->setQty($item->getQty() + $_item->getQty()); $this->removeItem($_item->getId()); break; } } } } else { $item->setQty($request->getQty()); } } if (is_string($item)) { Mage::throwException($item); } $cart->save(); Mage::getSingleton('checkout/session')->setCartWasUpdated(true); Mage::dispatchEvent('checkout_cart_update_item_complete', array('item' => $item, 'request' => $this->getRequest(), 'response' => $this->getResponse())); } catch (Mage_Core_Exception $e) { $result['error'] = true; $result['message'] = $e->getMessage(); } catch (Exception $e) { $result['error'] = true; $result['message'] = $e->getMessage(); Mage::logException($e); } if (!$result['error']) { if ($item_html = $this->getCartItem($item->getId())) { $result['item_html'] = $item_html; $result['new_item_id'] = $item->getId(); } if ($total = $this->getCartTolal()) { $result['total'] = $total; } } else { if ($item_html = $this->getCartItem($result['item_id'])) { $result['item_html'] = $item_html; } } $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result)); }
/** * 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; switch ($moveTo) { 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 = $this->getCustomerWishlist(); if ($wishlist && $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()->removeItem($item->getId()); } $this->setRecollect(true); } return $this; }
/** * @param ShopgateCartBase $order * @throws ShopgateLibraryException */ protected function _getSimpleShopgateCoupons(ShopgateCartBase $order) { if ($order instanceof ShopgateOrder) { foreach ($order->getItems() as $item) { /** @var ShopgateOrderItem $item */ if (!$item->isSgCoupon()) { continue; } if ($this->useTaxClasses) { $itemAmount = $item->getUnitAmount(); } else { $itemAmount = $item->getUnitAmountWithTax(); } $obj = new Varien_Object(); $obj->setName($item->getName()); $obj->setItemNumber($item->getItemNumber()); $obj->setUnitAmountWithTax($itemAmount); $obj->setQty($item->getQuantity()); $this->_virtualObjectStack[] = $obj; } } }
/** * Add product to current order quote * * $config can be integer qty (older behaviour, when no product configuration was possible) * or it can be array of options (newer behaviour). * * In case of older behaviour same product ids are not added, but quote item qty is increased. * In case of newer behaviour same product ids with different configs are added as separate quote items. * * @param mixed $product * @param array|float|int|Varien_Object $config * @return Mage_Adminhtml_Model_Sales_Order_Create */ public function addProduct($product, $config = 1) { if (is_array($config) || $config instanceof Varien_Object) { $config = is_array($config) ? new Varien_Object($config) : $config; $qty = (double) $config->getQty(); $separateSameProducts = true; } else { $qty = (double) $config; $config = new Varien_Object(); $config->setQty($qty); $separateSameProducts = false; } if (!$product instanceof Mage_Catalog_Model_Product) { $productId = $product; $product = Mage::getModel('catalog/product')->setStore($this->getStore())->setStoreId($this->getStore()->getId())->load($product); if (!$product->getId()) { Mage::throwException(Mage::helper('adminhtml')->__('Failed to add a product to cart by id "%s".', $productId)); } } if ($product->getStockItem()) { if (!$product->getStockItem()->getIsQtyDecimal()) { $qty = (int) $qty; } else { $product->setIsQtyDecimal(1); } } $qty = $qty > 0 ? $qty : 1; $item = null; if (!$separateSameProducts) { $item = $this->getQuote()->getItemByProduct($product); } if ($item) { $item->setQty($item->getQty() + $qty); } else { $item = $this->getQuote()->addProduct($product, $config); if (is_string($item)) { Mage::throwException($item); } $item->checkData(); } $this->setRecollect(true); return $this; }
/** * Convert quote to order * * @return $this */ public function orderAction() { $quoteId = $this->getRequest()->getParam('quote_id'); try { $this->_initQuote('quote_id'); $r4qQuote = Mage::registry('current_quote'); if (!$r4qQuote->getId()) { throw new Exception($this->__('Wrong Quote ID')); } $orderSession = Mage::getSingleton('adminhtml/session_quote'); $orderSession->clear(); $orderCreateModel = Mage::getSingleton('adminhtml/sales_order_create'); $importData = array(); $customerModel = Mage::getModel('customer/customer'); $websites = Mage::app()->getWebsites(); foreach ($websites as $website) { $customerModel->setWebsiteId($website->getId()); $customerModel->loadByEmail($r4qQuote->getCustomerEmail()); if ($customerModel->getId()) { break; } } //here needs to check if on import carries the entity_id. Thats why it might needs so the billing address has the same data as the rfq address $billingAddressArray = $r4qQuote->getBillingAddress()->getData(); unset($billingAddressArray['address_id']); $shippingAddressArray = $r4qQuote->getShippingAddress()->getData(); unset($shippingAddressArray['address_id']); if ($customerModel->getId()) { $orderSession->setCustomerId($customerModel->getId()); $importData['order'] = array('account' => array('email' => $r4qQuote->getCustomerEmail()), 'billing_address' => $billingAddressArray); } else { $orderSession->setCustomerId(0); if ($r4qQuote->getCustomerEmail()) { $importData['order'] = array('account' => array('email' => $r4qQuote->getCustomerEmail()), 'billing_address' => $billingAddressArray); $importData['account'] = array('email' => $r4qQuote->getCustomerEmail()); } } if ($r4qQuote->getQuoteCurrencyCode()) { $orderSession->setCurrencyId($r4qQuote->getQuoteCurrencyCode()); } $orderSession->setStoreId($r4qQuote->getStoreId()); if ($r4qQuote->getShippingAddress()->getShippingMethod()) { $orderSession->setShippingMethod($r4qQuote->getShippingAddress()->getShippingMethod()); } // import order data $orderCreateModel->importPostData($importData); if ($r4qQuote->getBillingAddress()) { $orderCreateModel->setBillingAddress($billingAddressArray); } if ($r4qQuote->getShippingAddress()) { $orderCreateModel->setShippingAddress($shippingAddressArray); } if (!$r4qQuote->getR4qShippingAsBilling() || $r4qQuote->getR4qShippingAsBilling() == '0') { //$orderCreateModel->setShippingAddress($r4qQuote->getBillingAddress()); $orderCreateModel->setShippingAsBilling(0); } // add items foreach ($r4qQuote->getAllItems() as $item) { if ($item->getParentItem()) { continue; } $product = $item->getProduct(); if ($product) { $product = Mage::getModel('catalog/product')->setStoreId($r4qQuote->getStoreId())->load($product->getId()); $info = $item->getOptionByCode('info_buyRequest'); if ($info) { $infoBuyRequest = new Varien_Object(unserialize($info->getValue())); } else { $infoBuyRequest = new Varien_Object(array('qty' => 1)); } if (isset($infoBuyRequest['start_date'])) { $infoBuyRequest['start_date'] = date('Y-m-d', strtotime($infoBuyRequest['start_date'])); } if (isset($infoBuyRequest['end_date'])) { $infoBuyRequest['end_date'] = date('Y-m-d', strtotime($infoBuyRequest['end_date'])); } if (Mage::helper('request4quote')->isOpenendedInstalled()) { $infoBuyRequest[ITwebexperts_Openendedinvoices_Helper_Data::BILLING_PERIOD_CUSTOM_PRICE] = $item->getR4qPriceProposal(); } $infoBuyRequest->setQty($item->getQty()); $infoBuyRequest->setStockId($item->getStockId()); if ($infoBuyRequest->getSelPay() && $infoBuyRequest->getSelPay() == 'recurring') { $infoBuyRequest->setData(ITwebexperts_Request4quote_Model_Quote::PRICE_PROPOSAL_OPTION, 0); } else { $infoBuyRequest->setData(ITwebexperts_Request4quote_Model_Quote::PRICE_PROPOSAL_OPTION, $item->getR4qPriceProposal()); } $infoBuyRequest->setData(ITwebexperts_Request4quote_Model_Quote::QUOTE_ID_OPTION, $r4qQuote->getId()); $orderCreateModel->addProduct($product, $infoBuyRequest->getData()); } } if ($r4qQuote->getCouponCode()) { $orderCreateModel->applyCoupon($r4qQuote->getCouponCode()); } $orderCreateModel->saveQuote(); $this->_redirect('adminhtml/sales_order_create/index'); return $this; } catch (Mage_Core_Exception $e) { $this->_getSession()->addError($e->getMessage()); } catch (Exception $e) { $this->_getSession()->addError($e->getMessage()); Mage::logException($e); } $this->_redirect('*/*/'); }
public function deleteAction() { // if (!$this->_validateFormKey()) { // Mage::throwException('Invalid form key'); // } $id = (int) $this->getRequest()->getParam('id'); $response = new Varien_Object(); $response->setError(0); if ($id) { try { $this->_getCart()->removeItem($id)->save(); $response->setQty($this->_getCart()->getSummaryQty()); $this->loadLayout(); $content = $this->getLayout()->getBlock('cart_sidebar')->toHtml(); $response->setContent($content); $response->setSuccessMessage($this->__('<div class="removed-successfully">This item was removed from the cart</div>')); } catch (Exception $e) { $response->setError(1); $response->setErrorMessage($this->__('<div class="removed-failed">Can not remove the item.</div>')); } } $this->getResponse()->setBody($response->toJson()); }
/** * override for changing the current stock qty based on the quote_item * (this is a bad design from Magento, checkQuoteItemQty should receive the quoteItem in the original code too) * * @param mixed $qty * @param mixed $summaryQty * @param int $origQty * @param Mage_Sales_Model_Quote_Item $quoteItem * * @return Varien_Object */ public function checkQuoteItemQty($qty, $summaryQty, $origQty = 0, $quoteItem = null, $product = null) { if ($quoteItem && ITwebexperts_Payperrentals_Helper_Data::isReservationOnly($product) && (!$quoteItem->getChildren() || Mage::app()->getStore()->isAdmin())) { $qtyOption = 1; if ($quoteItem->getParentProductQty()) { $qty = $quoteItem->getParentProductQty(); $qtyOption = $quoteItem->getParentProductQtyOption(); } $quoteItemId = $quoteItem->getId(); if ($quoteItem->getParentItem() && $quoteItem->getParentItem()->getProduct()) { if ($quoteItem->getParentItem()->getProduct()->getTypeId() == ITwebexperts_Payperrentals_Helper_Data::PRODUCT_TYPE_BUNDLE) { $quoteItemId = $quoteItem->getParentItem()->getItemId(); } } $turnoverArr = ITwebexperts_Payperrentals_Helper_Data::getTurnoverFromQuoteItemOrBuyRequest($product, $quoteItem); list($startDate, $endDate) = array($turnoverArr['before'], $turnoverArr['after']); $result = new Varien_Object(); $result->setHasError(false); if (!is_numeric($qty)) { $qty = Mage::app()->getLocale()->getNumber($qty); } /** * Check quantity type */ $result->setItemIsQtyDecimal($this->getIsQtyDecimal()); if (!$this->getIsQtyDecimal()) { $result->setHasQtyOptionUpdate(true); $qty = intval($qty); /** * Adding stock data to quote item */ $result->setItemQty($qty); if (!is_numeric($qty)) { $qty = Mage::app()->getLocale()->getNumber($qty); } $origQty = intval($origQty); $result->setOrigQty($origQty); } if ($qty < ITwebexperts_Payperrentals_Helper_Inventory::getMinSaleQuantity($product)) { $result->setHasError(true)->setMessage(Mage::helper('cataloginventory')->__('The minimum quantity allowed for purchase is %s.', ITwebexperts_Payperrentals_Helper_Inventory::getMinSaleQuantity($product)))->setErrorCode('qty_min')->setQuoteMessage(Mage::helper('cataloginventory')->__('Some of the products cannot be ordered in requested quantity.'))->setQuoteMessageIndex('qty'); return $result; } if ($qty > ITwebexperts_Payperrentals_Helper_Inventory::getMaxSaleQuantity($product)) { $result->setHasError(true)->setMessage(Mage::helper('cataloginventory')->__('The maximum quantity allowed for purchase is %s.', ITwebexperts_Payperrentals_Helper_Inventory::getMaxSaleQuantity($product)))->setErrorCode('qty_max')->setQuoteMessage(Mage::helper('cataloginventory')->__('Some of the products cannot be ordered in requested quantity.'))->setQuoteMessageIndex('qty'); return $result; } $result->addData($this->checkQtyIncrements($qty)->getData()); if ($result->getHasError()) { return $result; } $option = $quoteItem->getOptionByCode('info_buyRequest'); $buyRequest = $option ? unserialize($option->getValue()) : null; if (Mage::app()->getStore()->isAdmin() && Mage::getSingleton('adminhtml/session_quote')->getOrderId()) { $editedOrderId = Mage::getSingleton('adminhtml/session_quote')->getOrderId(); $order = Mage::getModel('sales/order')->load($editedOrderId); $buyRequestArray = (array) $buyRequest; foreach ($order->getAllItems() as $oItem) { if ($oItem->getProduct()->getId() != $product->getId()) { continue; } if (is_object($oItem->getOrderItem())) { $item = $oItem->getOrderItem(); } else { $item = $oItem; } if ($item->getParentItem()) { continue; } //check for bundles if (count($item->getChildrenItems()) > 0) { foreach ($item->getChildrenItems() as $child) { $turnoverArr = ITwebexperts_Payperrentals_Helper_Data::getTurnoverFromQuoteItemOrBuyRequest($child->getProductId(), $child); $buyRequestArray['excluded_qty'][] = array('product_id' => $child->getProductId(), 'start_date' => $turnoverArr['before'], 'end_date' => $turnoverArr['after'], 'qty' => $item->getQtyOrdered()); } } else { $turnoverArr = ITwebexperts_Payperrentals_Helper_Data::getTurnoverFromQuoteItemOrBuyRequest($item->getProductId(), $item); $buyRequestArray['excluded_qty'][] = array('product_id' => $item->getProductId(), 'start_date' => $turnoverArr['before'], 'end_date' => $turnoverArr['after'], 'qty' => $item->getQtyOrdered()); } } $buyRequest = new Varien_Object($buyRequestArray); } if (isset($buyRequest['start_date']) && isset($buyRequest['end_date'])) { if (strtotime($buyRequest['start_date']) > strtotime($buyRequest['end_date'])) { $message = Mage::helper('payperrentals')->__('Start Date is bigger then End Date. Please change!'); $result->setHasError(true)->setMessage($message)->setQuoteMessage($message); return $result; } } $isAvailable = false; if (ITwebexperts_Payperrentals_Helper_Inventory::isAllowedOverbook($product->getId())) { $isAvailable = true; } if (ITwebexperts_Payperrentals_Helper_Data::isBuyout($buyRequest)) { if (!$isAvailable) { Mage::register('quote_item_id', $quoteItemId); $maxQty = ITwebexperts_Payperrentals_Helper_Inventory::getQuantity($product, null, null, $buyRequest); Mage::unregister('quote_item_id'); if ($maxQty >= $qty) { $isAvailable = true; } } if ($isAvailable) { return $result; } else { $message = Mage::helper('payperrentals')->__('There is not enough quantity for buy this product'); $result->setHasError(true)->setMessage($message)->setQuoteMessage($message); return $result; } } if (!Mage::app()->getStore()->isAdmin() && !Mage::getSingleton('checkout/session')->getIsExtendedQuote() && isset($buyRequest['start_date']) && isset($buyRequest['end_date']) && ITwebexperts_Payperrentals_Helper_Inventory::isExcludedDay($product->getId(), $buyRequest['start_date'], $buyRequest['end_date'])) { $message = Mage::helper('payperrentals')->__('There are blocked dates or excluded days on your selected dates!'); $result->setHasError(true)->setMessage($message)->setQuoteMessage($message); return $result; } else { if (!$isAvailable && isset($buyRequest['start_date']) && isset($buyRequest['end_date'])) { Mage::register('quote_item_id', $quoteItemId); $maxQty = ITwebexperts_Payperrentals_Helper_Inventory::getQuantity($product, $startDate, $endDate, $buyRequest); Mage::unregister('quote_item_id'); if ($maxQty >= $qty) { $isAvailable = true; } } } if (ITwebexperts_Payperrentals_Helper_Data::isUsingGlobalDatesShoppingCart($product) && !$buyRequest['start_date']) { $message = Mage::helper('payperrentals')->__('Please select Global Dates!'); $result->setHasError(true)->setMessage($message)->setQuoteMessage($message); return $result; } if (!Mage::app()->getStore()->isAdmin() && !ITwebexperts_Payperrentals_Helper_Data::isBuyout($buyRequest) && (isset($buyRequest['start_date']) && strtotime($buyRequest['start_date']) < strtotime(date('Y-m-d')) || isset($buyRequest['end_date']) && strtotime($buyRequest['end_date']) < strtotime(date('Y-m-d')))) { $message = Mage::helper('payperrentals')->__('The selected Dates are in the past. Please select new dates!'); $result->setHasError(true)->setMessage($message)->setQuoteMessage($message); return $result; } if (Mage::app()->getStore()->isAdmin() && ITwebexperts_Payperrentals_Helper_Inventory::isAllowedOverbook($product->getId()) && ITwebexperts_Payperrentals_Helper_Inventory::showAdminOverbookWarning()) { Mage::register('quote_item_id', $quoteItemId); $maxQty = ITwebexperts_Payperrentals_Helper_Inventory::getQuantity($product, $startDate, $endDate, $buyRequest, true); Mage::unregister('quote_item_id'); if ($maxQty < $qty) { $message = Mage::helper('cataloginventory')->__('Product is not available for the selected dates'); $result->setHasError(false)->setMessage($message)->setQuoteMessage($message)->setQuoteMessageIndex('qtyppr'); return $result; } } Mage::dispatchEvent('before_stock_check', array('buyrequest' => $buyRequest, 'isavailable' => &$isAvailable)); if (!$isAvailable) { if (isset($buyRequest['start_date']) && isset($buyRequest['end_date'])) { //Mage::register('no_quote', 1); Mage::register('quote_item_id', $quoteItemId); $maxQty = ITwebexperts_Payperrentals_Helper_Inventory::getQuantity($product, $startDate, $endDate, $buyRequest); Mage::unregister('quote_item_id'); $maxQty = intval($maxQty / $qtyOption); //Mage::unregister('no_quote', 1); if ($maxQty > 0) { $message = Mage::helper('payperrentals')->__('Max quantity available for these dates is: ' . $maxQty . ', your quantity has been adjusted.'); // Mage::getSingleton('checkout/session')->addError($message); $result->setHasQtyOptionUpdate(true); //$result->setOrigQty($maxQty); $result->setQty($maxQty); $result->setItemQty($maxQty); $result->setMessage($message)->setQuoteMessage($message); return $result; } $message = Mage::helper('cataloginventory')->__('The requested quantity for "%s" is not available.', $this->getProductName()); } else { $message = Mage::helper('cataloginventory')->__('Please select Start and End Dates'); } $result->setHasError(true)->setMessage($message)->setQuoteMessage($message)->setQuoteMessageIndex('qtyppr'); return $result; } return $result; } $return = parent::checkQuoteItemQty($qty, $summaryQty, $origQty); return $return; }
public function quoteProductAddAfter($observer) { $helper = Mage::helper('customoptions'); if (!$helper->isEnabled() || !$helper->isOptionSkuPolicyEnabled() || !$helper->isOptionSkuPolicyApplyToCart()) { return $this; } $configSkuPolicy = $helper->getOptionSkuPolicyDefault(); $items = $observer->getEvent()->getItems(); foreach ($items as $item) { $itemChangesFlag = false; $itemRemoveFlag = false; $product = $item->getProduct(); // if bad magento)) if (is_null($product->getHasOptions())) { $product->load($product->getId()); } if (!$product->getHasOptions()) { continue; } $productSkuPolicy = $helper->getProductSkuPolicy($product); if ($productSkuPolicy == 0) { $productSkuPolicy = $configSkuPolicy; } $post = $helper->getInfoBuyRequest($product); if (isset($post['options'])) { $options = $post['options']; } else { $options = false; } if ($options) { foreach ($options as $optionId => $value) { $optionModel = $product->getOptionById($optionId); if (!$optionModel) { continue; } $optionModel->setProduct($product); $customoptionsIsOnetime = $optionModel->getCustomoptionsIsOnetime(); $skuPolicy = $optionModel->getSkuPolicy(); // or $productSkuPolicy = Grouped if ($skuPolicy == 0 || $productSkuPolicy == 3) { $skuPolicy = $productSkuPolicy; } if ($skuPolicy == 1) { continue; } switch ($optionModel->getType()) { case 'drop_down': case 'radio': case 'checkbox': case 'multiple': case 'swatch': case 'multiswatch': case 'hidden': if (is_array($value)) { $optionTypeIds = $value; } else { $optionTypeIds = explode(',', $value); } foreach ($optionTypeIds as $index => $optionTypeId) { if (!$optionTypeId) { continue; } $valueModel = $optionModel->getValueById($optionTypeId); $sku = $valueModel->getSku(); if (!$sku) { continue; } $productIdBySku = $helper->getProductIdBySku($sku); if (!$productIdBySku) { continue; } if ($skuPolicy == 2 || $skuPolicy == 3) { // Independent, Grouped // add new product by $productIdBySku if (isset($post['options_' . $optionId . '_qty'])) { $optionQty = intval($post['options_' . $optionId . '_qty']); } elseif (isset($post['options_' . $optionId . '_' . $optionTypeId . '_qty'])) { $optionQty = intval($post['options_' . $optionId . '_' . $optionTypeId . '_qty']); } else { $optionQty = 1; } $optionTotalQty = $customoptionsIsOnetime ? $optionQty : $optionQty * $item->getQty(); $request = new Varien_Object(); $request->setQty($optionTotalQty); $optionResourceModel = $optionModel->getResource(); $request->setSkuPolicyName($optionResourceModel->getValueTitle($optionTypeId, $item->getStoreId())); if ($helper->isWeightEnabled()) { $request->setSkuPolicyWeight($valueModel->getWeight()); } if ($helper->isCostEnabled()) { $request->setSkuPolicyCost($valueModel->getCost()); } //$item->getQuote() or Mage::getSingleton('checkout/cart') $result = $item->getQuote()->addProduct(Mage::getModel('catalog/product')->setStoreId($item->getStoreId())->load($productIdBySku), $request); if (!is_object($result)) { continue; } // remove option or optionValue from item if (is_array($value)) { unset($value[$index]); } else { $value = ''; } if ($value) { // if remove optionValue $post['options'][$optionId] = $value; $itemOption = $item->getOptionByCode('option_' . $optionId); $itemOption->setValue(is_array($value) ? implode(',', $value) : $value); $item->addOption($itemOption); } else { // if remove option unset($post['options'][$optionId]); $item->removeOption('option_' . $optionId); $itemOptionIds = $item->getOptionByCode('option_ids'); $optionIds = $itemOptionIds->getValue(); if ($optionIds) { $optionIds = explode(',', $optionIds); $i = array_search($optionId, $optionIds); if ($i !== false) { unset($optionIds[$i]); } if ($optionIds) { $optionIds = implode(',', $optionIds); } } if ($optionIds) { $itemOptionIds->setValue($optionIds); $item->addOption($itemOptionIds); } else { $item->removeOption('option_ids'); } } $infoBuyRequest = $item->getOptionByCode('info_buyRequest'); $infoBuyRequest->setValue(serialize($post)); $item->addOption($infoBuyRequest); // end remove option from item $itemChangesFlag = true; if ($skuPolicy == 3) { $itemRemoveFlag = true; } } elseif ($skuPolicy == 4) { $infoBuyRequest = $item->getOptionByCode('info_buyRequest'); $post['sku_policy_sku'] = $sku; $infoBuyRequest->setValue(serialize($post)); $item->addOption($infoBuyRequest); } } break; default: if (!$value) { continue; } $sku = $optionModel->getSku(); if (!$sku) { continue; } $productIdBySku = $helper->getProductIdBySku($sku); if (!$productIdBySku) { continue; } if ($skuPolicy == 2 || $skuPolicy == 3) { // Independent, Grouped // add new product by $productIdBySku $optionTotalQty = $customoptionsIsOnetime ? 1 : $item->getQty(); $request = new Varien_Object(); $request->setQty($optionTotalQty); $optionResourceModel = $optionModel->getResource(); $request->setSkuPolicyName($optionResourceModel->getTitle($optionId, $item->getStoreId())); //$item->getQuote() or Mage::getSingleton('checkout/cart') $result = $item->getQuote()->addProduct(Mage::getModel('catalog/product')->setStoreId($item->getStoreId())->load($productIdBySku)); if (!is_object($result)) { continue; } // remove option from item unset($post['options'][$optionId]); $item->removeOption('option_' . $optionId); $itemOptionIds = $item->getOptionByCode('option_ids'); $optionIds = $itemOptionIds->getValue(); if ($optionIds) { $optionIds = explode(',', $optionIds); $i = array_search($optionId, $optionIds); if ($i !== false) { unset($optionIds[$i]); } if ($optionIds) { $optionIds = implode(',', $optionIds); } } if ($optionIds) { $itemOptionIds->setValue($optionIds); $item->addOption($itemOptionIds); } else { $item->removeOption('option_ids'); } $infoBuyRequest = $item->getOptionByCode('info_buyRequest'); $infoBuyRequest->setValue(serialize($post)); $item->addOption($infoBuyRequest); // end remove option from item $itemChangesFlag = true; if ($skuPolicy == 3) { $itemRemoveFlag = true; } } elseif ($skuPolicy == 4) { $infoBuyRequest = $item->getOptionByCode('info_buyRequest'); $post['sku_policy_sku'] = $sku; $infoBuyRequest->setValue(serialize($post)); $item->addOption($infoBuyRequest); } break; } } } if ($itemRemoveFlag) { $itemsCollection = $item->getQuote()->getItemsCollection(); foreach ($itemsCollection as $key => $itm) { if ($itm === $item) { $itemsCollection->removeItemByKey($key); } } } elseif ($itemChangesFlag) { // update item $quote = $item->getQuote(); $itemsCollection = $quote->getItemsCollection(); $itemRemoveFlag = false; foreach ($itemsCollection as $key => $itm) { if ($itm->getProductId() == $item->getProductId() && $itm !== $item) { // get current $item - $options if (isset($post['options'])) { $options = $post['options']; } else { $options = false; } // get other $itm - $optns $prdct = $itm->getProduct(); // if bad magento)) if (is_null($prdct->getHasOptions())) { $prdct->load($prdct->getId()); } $optns = false; if ($prdct->getHasOptions()) { $post = $helper->getInfoBuyRequest($prdct); if (isset($post['options'])) { $optns = $post['options']; } } // compare options if ($optns === $options) { $itm->setQty($itm->getQty() + $item->getQty()); $itemRemoveFlag = true; } } if ($itemRemoveFlag && $itm === $item) { $itemsCollection->removeItemByKey($key); } } } } }
public function getRequest() { $request = new Varien_Object(); $request->setQty($this->proxyItem->getQty()); // grouped and downloadable products doesn't have options if ($this->proxyItem->getProduct()->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_GROUPED || $this->proxyItem->getProduct()->getTypeId() == Mage_Downloadable_Model_Product_Type::TYPE_DOWNLOADABLE) { return $request; } /** @var $magentoProduct Ess_M2ePro_Model_Magento_Product */ $magentoProduct = Mage::getModel('M2ePro/Magento_Product')->setProduct($this->getProduct()); $options = $this->proxyItem->getOptions(); if (empty($options)) { return $request; } if ($magentoProduct->isSimpleType()) { $request->setOptions($options); } else { if ($magentoProduct->isBundleType()) { $request->setBundleOption($options); } else { if ($magentoProduct->isConfigurableType()) { $request->setSuperAttribute($options); } } } return $request; }
/** * Fetch new orders from ChannelEngine. * Ran by cron. The cronjob is set in extension config file. * * @return bool */ public function fetchNewOrders() { /** * Check if client is initialized */ if (is_null($this->_client)) { return false; } foreach ($this->_client as $storeId => $_client) { /** * Retrieve new orders */ $orders = $_client->getOrders(array(Tritac_ChannelEngineApiClient_Enums_OrderStatus::NEW_ORDER)); /** * Check new orders existing */ if (is_null($orders) || $orders->count() == 0) { continue; } Mage::log("Received {$orders->count()} orders from ChannelEngine."); foreach ($orders as $order) { $billingAddress = $order->getBillingAddress(); $shippingAddress = $order->getShippingAddress(); if (empty($billingAddress)) { continue; } $lines = $order->getLines(); if (!empty($lines)) { // Initialize new quote $quote = Mage::getModel('sales/quote')->setStoreId($storeId); foreach ($lines as $item) { $productNo = $item->getMerchantProductNo(); $ids = explode('_', $productNo); $productId = $ids[0]; $productOptions = array(); if (count($ids) == 3) { $productOptions = array($ids[1] => intval($ids[2])); } // Load magento product $_product = Mage::getModel('catalog/product')->setStoreId($storeId); $_product->load($productId); if (!$_product->getId()) { // If the product can't be found by ID, fall back on the SKU. $productId = $_product->getIdBySku($productNo); $_product->load($productId); } // Prepare product parameters for quote $params = new Varien_Object(); $params->setQty($item->getQuantity()); $params->setOptions($productOptions); // Add product to quote try { $_quoteItem = $quote->addProduct($_product, $params); if (is_string($_quoteItem)) { // Magento sometimes returns a string when the method fails. -_-" Mage::throwException('Failed to create quote item: ' . $_quoteItem); } $_quoteItem->setChannelengineOrderLineId($item->getId()); } catch (Exception $e) { Mage::getModel('adminnotification/inbox')->addCritical("An order (#{$order->getId()}) could not be imported", "Reason: {$e->getMessage()} Please contact ChannelEngine support at <a href='mailto:support@channelengine.com'>support@channelengine.com</a> or +31(0)71-5288792"); Mage::logException($e); continue 2; } } } $phone = $order->getPhone(); if (empty($phone)) { $phone = '-'; } // Prepare billing and shipping addresses $billingData = array('firstname' => $billingAddress->getFirstName(), 'lastname' => $billingAddress->getLastName(), 'email' => $order->getEmail(), 'telephone' => $phone, 'country_id' => $billingAddress->getCountryIso(), 'postcode' => $billingAddress->getZipCode(), 'city' => $billingAddress->getCity(), 'street' => $billingAddress->getStreetName() . ' ' . $billingAddress->getHouseNr() . $billingAddress->getHouseNrAddition()); $shippingData = array('firstname' => $shippingAddress->getFirstName(), 'lastname' => $shippingAddress->getLastName(), 'email' => $order->getEmail(), 'telephone' => $phone, 'country_id' => $shippingAddress->getCountryIso(), 'postcode' => $shippingAddress->getZipCode(), 'city' => $shippingAddress->getCity(), 'street' => $shippingAddress->getStreetName() . ' ' . $shippingAddress->getHouseNr() . $shippingAddress->getHouseNrAddition()); // Register shipping cost. See Tritac_ChannelEngine_Model_Carrier_Channelengine::collectrates(); Mage::register('channelengine_shipping_amount', floatval($order->getShippingCostsInclVat())); // Set this value to make sure ChannelEngine requested the rates and not the frontend // because the shipping method has a fallback on 0,- and this will make it show up on the frontend Mage::register('channelengine_shipping', true); $quote->getBillingAddress()->addData($billingData); $quote->getShippingAddress()->addData($shippingData)->setSaveInAddressBook(0)->setCollectShippingRates(true)->setShippingMethod('channelengine_channelengine'); $quote->collectTotals(); // Set guest customer $quote->setCustomerId(null)->setCustomerEmail($quote->getBillingAddress()->getEmail())->setCustomerIsGuest(true)->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID); // Set custom payment method $quote->setIsSystem(true); $quote->getPayment()->importData(array('method' => 'channelengine')); // Save quote and convert it to new order try { $quote->save(); $service = Mage::getModel('sales/service_quote', $quote); $service->submitAll(); } catch (Exception $e) { Mage::getModel('adminnotification/inbox')->addCritical("An order (#{$order->getId()}) could not be imported", "Reason: {$e->getMessage()} Please contact ChannelEngine support at <a href='mailto:support@channelengine.com'>support@channelengine.com</a> or +31(0)71-5288792"); Mage::logException($e); continue; } $_order = $service->getOrder(); if ($_order->getIncrementId()) { /** * Create new invoice and save channel order */ try { // Initialize new invoice model $invoice = Mage::getModel('sales/service_order', $_order)->prepareInvoice(); // Add comment to invoice $invoice->addComment("Order paid on the marketplace.", false, true); // Register invoice. Register invoice items. Collect invoice totals. $invoice->register(); $invoice->getOrder()->setIsInProcess(true); // Initialize new channel order $_channelOrder = Mage::getModel('channelengine/order'); $_channelOrder->setOrderId($_order->getId())->setChannelOrderId($order->getId())->setChannelName($order->getChannelName())->setDoSendMails($order->getDoSendMails())->setCanShipPartial($order->getCanShipPartialOrderLines()); $invoice->getOrder()->setCanShipPartiallyItem($order->getCanShipPartialOrderLines())->setCanShipPartially($order->getCanShipPartialOrderLines()); // Start new transaction $transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder())->addObject($_channelOrder); $transactionSave->save(); } catch (Exception $e) { Mage::getModel('adminnotification/inbox')->addCritical("An invoice could not be created (order #{$_order->getIncrementId()}, channel order #{$order->getId()})", "Reason: {$e->getMessage()} Please contact ChannelEngine support at <a href='mailto:support@channelengine.com'>support@channelengine.com</a> or +31(0)71-5288792"); Mage::logException($e); continue; } Mage::log("Order #{$_order->getIncrementId()} was imported successfully."); } else { Mage::log("An order (#{$order->getId()}) could not be imported"); } } } return true; }
public function addAction() { $coreSession = Mage::getSingleton('core/session'); $data = $this->getRequest()->getPost(); //vd($data); $oemPageURL = $data['pageURL']; $oemBrands = Mage::getModel('arioem/source_oembrand'); $oemHelper = Mage::helper('arioem/OEM'); $commonHelper = Mage::helper('arioem'); $gainPercent = $commonHelper->getCustomerCostPercent(); $response = new Varien_Object(); $itemsAddedTotal = 0; $skusAdded = array(); $items = array(); foreach ($data['parts'] as $part) { $price = (double) trim(str_replace(',', '', $part['price']), ' $'); if ($gainPercent) { $cost = (double) $oemHelper->getOEMCost($part['brand'], $part['sku']); if ($cost) { $price = $cost * (100 + $gainPercent) / 100; } else { $coreSession->addWarning($this->__('No cost to apply custom price for Part #%s %s has been found, retail price used instead. Please confirm this with our customer support.', $part['sku'], $part['name'])); Vikont_ARIOEM_Model_Log::logError(sprintf('No cost for OEM product found: Brand=%s PartNumber=%s Name=%s Price=%s Qty=%d IP=%s CustomerId=%d URL=%s. Retail price used instead', $part['brand'], $part['sku'], $part['name'], $part['price'], $part['qty'], $_SERVER['REMOTE_ADDR'], Mage::getSingleton('customer/session')->getCustomerId(), $oemPageURL)); // continue; } } $items[] = array('brand' => $part['brand'], 'sku' => $part['sku'], 'name' => $part['name'], 'qty' => $part['qty'], 'price' => $price); } $checkoutSession = Mage::getSingleton('checkout/session'); $cart = Mage::getSingleton('checkout/cart'); $cart->getQuote()->setIsSuperMode(true); // TODO try { $productId = Vikont_ARIOEM_Helper_Cart::getOemProductId(); if (!$productId) { Mage::throwException($this->__('Cannot find OEM parent product')); } $customOptionId = Vikont_ARIOEM_Helper_Db::getTableValue('catalog/product_option', 'option_id', 'product_id=' . $productId); foreach ($items as $itemData) { $product = Mage::getModel('catalog/product')->load($productId); if (!$product->getId()) { Mage::log('ERROR: ARIOEM: No dummy OEM product found'); Mage::throwException($this->__('Cannot add product(s) to Cart')); break; } $addToCartParams = array('product' => $productId, 'options' => array($customOptionId => $itemData['sku']), 'qty' => $itemData['qty']); $itemCountBefore = count($cart->getItems()); $cart->addProduct($product, $addToCartParams); // $brandName = $oemBrands->getOptionText($itemData['brand']); $brandName = Vikont_ARIOEM_Model_Oem_Part::getBrandNameByShortname($itemData['brand']); if (!count($cart->getItems())) { $cart->save(); } // if the item was really added, but not just increased the qty of its copy that's been added before if ($itemCountBefore < count($cart->getItems())) { $cart->getItems()->getLastItem()->setSku($itemData['sku'])->setName($this->__('OEM %s | %s', $brandName, $itemData['name']))->setOriginalCustomPrice($itemData['price'])->setRedirectUrl($oemPageURL)->save(); } $itemsAddedTotal += $itemData['qty']; $skusAdded[] = $itemData['sku']; } $cart->getQuote()->setTotalsCollectedFlag(false); $cart->save(); $checkoutSession->setCartWasUpdated(true); Mage::dispatchEvent('checkout_cart_add_product_complete', array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())); if (!$cart->getQuote()->getHasError()) { $response->setError(0); $response->setProductsAdded($skusAdded); $response->setQty((string) (int) $cart->getSummaryQty()); $message = count($items) == 1 ? $this->__('Item %s was added to your shopping cart', $items[0]['name']) : $this->__('%d items were added to your shopping cart', $itemsAddedTotal); $response->setMessage($message); // $cartTopBlock = $this->getLayout()->createBlock('checkout/cart_sidebar'); // $topCartHtml = $cartTopBlock // ? $cartTopBlock // ->setTemplate('checkout/cart/cartheader.phtml') // ->setIsAjax(true) // ->toHtml() // : ''; // $response->setCartTop($topCartHtml); } else { $response->setError(1); $response->setMessage($this->__('Some error has occurred while adding to Cart')); } } catch (Exception $e) { Mage::logException($e); $response->setError(1); $response->setMessage($this->__('Cannot add the item to shopping cart, reason: %s', $e->getMessage())); } $this->getResponse()->setBody($response->toJson()); }
/** * Function used to return the booked object in the required format check phpdoc on getAllBookedQtyForProduct * * @param $reservedCollection * @param $isOrder * @param null $booked * * @return array|null */ private static function getBooked($reservedCollection, $isOrder, $booked = null) { if (is_null($booked)) { $booked = array(); } $configHelper = Mage::helper('payperrentals/config'); foreach ($reservedCollection as $iReserved) { $start = strtotime($iReserved->getStartTurnoverBefore()); $end = strtotime($iReserved->getEndTurnoverAfter()); if (Mage::helper('payperrentals/config')->useReserveInventoryDropoffPickup()) { if ($iReserved->getDropoff()) { $start = strtotime($iReserved->getDropoff()); } if ($iReserved->getPickup()) { $end = strtotime($iReserved->getPickup()); } } if (Mage::helper('payperrentals/config')->useReserveInventorySendReturn()) { $sendReturnCollection = Mage::getModel('payperrentals/sendreturn')->getCollection(); $sendReturnCollection->addSelectFilter("resorder_id=" . $iReserved->getId()); $sendReturnCollection->addSelectFilter("return_date <= '" . ITwebexperts_Payperrentals_Helper_Date::toDbDate($end, true) . "' AND return_date <> '0000-00-00 00:00:00'"); $sendReturnCollection->getSelect()->order('main_table.return_date DESC'); } //a required option for bundle products is to have prices defined when times is enabled. //So use times and prices should be defined for all components of bundle products. $useTimes = ITwebexperts_Payperrentals_Helper_Data::useTimes($iReserved->getProductId()) == 2; if ($useTimes && (date('H:i:s', $start) != '00:00:00' || date('H:i:s', $end) != '23:59:00' && date('H:i:s', $end) != '23:58:59')) { $timeIncrement = $configHelper->getTimeIncrement() * 60; } else { $timeIncrement = 3600 * 24; } $returnsArray = array(); if (isset($sendReturnCollection)) { foreach ($sendReturnCollection as $sendReturnItem) { if ($timeIncrement !== 3600 * 24) { $dateReturn = date('Y-m-d H:i', strtotime($sendReturnItem->getReturnDate())); } else { $dateReturn = date('Y-m-d', strtotime($sendReturnItem->getReturnDate())) . ' 00:00'; } if (strtotime($dateReturn) < $start) { $dateReturn = date('Y-m-d', $start) . ' 00:00'; } if (!isset($returnsArray[$sendReturnItem->getProductId()][$dateReturn])) { $returnsArray[$sendReturnItem->getProductId()][$dateReturn] = $sendReturnItem->getQty(); } else { $returnsArray[$sendReturnItem->getProductId()][$dateReturn] += $sendReturnItem->getQty(); } } } $qtyReturnedArray = array(); while ($start < $end) { if ($timeIncrement !== 3600 * 24) { $dateFormatted = date('Y-m-d H:i', $start); } else { $dateFormatted = date('Y-m-d', $start) . ' 00:00'; } if (!isset($qtyReturnedArray[$iReserved->getProductId()])) { $qtyReturnedArray[$iReserved->getProductId()] = 0; } if (isset($returnsArray[$iReserved->getProductId()]) && array_key_exists($dateFormatted, $returnsArray[$iReserved->getProductId()]) !== false) { $qtyReturnedArray[$iReserved->getProductId()] = $returnsArray[$sendReturnItem->getProductId()][$dateFormatted]; } if (!isset($booked[$iReserved->getProductId()][$dateFormatted])) { $vObject = new Varien_Object(); $vObject->setQty($iReserved->getQty() - $qtyReturnedArray[$iReserved->getProductId()]); if ($isOrder) { $vObject->setOrders(array($iReserved->getOrderId())); } $booked[$iReserved->getProductId()][$dateFormatted] = $vObject; } else { $vObject = $booked[$iReserved->getProductId()][$dateFormatted]; $vObject->setQty($vObject->getQty() + $iReserved->getQty() - $qtyReturnedArray[$iReserved->getProductId()]); if ($isOrder) { $orderArr = $vObject->getOrders(); $orderArr = array_merge($orderArr, array($iReserved->getOrderId())); array_unique($orderArr); $vObject->setOrders($orderArr); } $booked[$iReserved->getProductId()][$dateFormatted] = $vObject; } $start += $timeIncrement; } } /** * Event used to complete the booked object with specific dates. Needed in case of maintenance module */ $resultObject = new Varien_Object(); $resultObject->setBooked($booked); Mage::dispatchEvent('after_booked', array('result' => $resultObject, 'reserved_collection' => $reservedCollection, 'is_order' => $isOrder)); return $resultObject->getBooked(); }
/** * for old magento * * @param $itemId * @param null $requestInfo * @param null $updatingParams * @return Mage_Sales_Model_Quote_Item|string */ protected function _updateItem($itemId, $requestInfo = null, $updatingParams = null) { $cart = $this->_getCart(); try { $item = $cart->getQuote()->getItemById($itemId); if (!$item) { Mage::throwException(Mage::helper('checkout')->__('Quote item does not exist.')); } $productId = $item->getProduct()->getId(); $product = $product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($productId); $currentWebsiteId = Mage::app()->getStore()->getWebsiteId(); if (!$product->getId() || !is_array($product->getWebsiteIds()) || !in_array($currentWebsiteId, $product->getWebsiteIds())) { Mage::throwException(Mage::helper('checkout')->__('The product could not be found.')); } if ($requestInfo instanceof Varien_Object) { $request = $requestInfo; } elseif (is_numeric($requestInfo)) { $request = new Varien_Object(array('qty' => $requestInfo)); } else { $request = new Varien_Object($requestInfo); } if (!$request->hasQty()) { $request->setQty(1); } if ($product->getStockItem()) { $minimumQty = $product->getStockItem()->getMinSaleQty(); // If product was not found in cart and there is set minimal qty for it if ($minimumQty && $minimumQty > 0 && $request->getQty() < $minimumQty && !$cart->getQuote()->hasProductId($productId)) { $request->setQty($minimumQty); } } if (method_exists($cart->getQuote(), 'updateItem')) { $result = $cart->getQuote()->updateItem($itemId, $request, $updatingParams); } else { $result = $this->_updateQuoteItem($itemId, $request, $updatingParams); } } catch (Mage_Core_Exception $e) { $cart->getCheckoutSession()->setUseNotice(false); $result = $e->getMessage(); } /** * We can get string if updating process had some errors */ if (is_string($result)) { if ($cart->getCheckoutSession()->getUseNotice() === null) { $cart->getCheckoutSession()->setUseNotice(true); } Mage::throwException($result); } Mage::dispatchEvent('checkout_cart_product_update_after', array('quote_item' => $result, 'product' => $product)); $cart->getCheckoutSession()->setLastAddedProductId($productId); return $result; }
/** * Add product to current order quote * $product can be either product id or product model * $config can be either buyRequest config, or just qty * * @param int|Mage_Catalog_Model_Product $product * @param float|array|Varien_Object $config * @return Mage_Adminhtml_Model_Sales_Order_Create */ public function addProduct($product, $config = 1) { if (!is_array($config) && !$config instanceof Varien_Object) { $config = array('qty' => $config); } $config = new Varien_Object($config); /* $aChildQuoteItems = Mage::getModel("sales/quote_item") ->getCollection() ->addFieldToFilter("quote_id", 42); Mage::log("qry = ".$aChildQuoteItems->getSelect()); Mage::log("all items = ".serialize($aChildQuoteItems)); */ if (!$product instanceof Mage_Catalog_Model_Product) { $productId = $product; $product = Mage::getModel('catalog/product')->setStore($this->getSession()->getStore())->setStoreId($this->getSession()->getStoreId())->load($product); if (!$product->getId()) { Mage::throwException(Mage::helper('adminhtml')->__('Failed to add a product to cart by id "%s".', $productId)); } } $stockItem = $product->getStockItem(); if ($stockItem && $stockItem->getIsQtyDecimal()) { $product->setIsQtyDecimal(1); } else { $config->setQty((int) $config->getQty()); } $product->setCartQty($config->getQty()); $item = $this->getQuote()->addProductAdvanced($product, $config, Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_FULL); if (is_string($item)) { if ($product->getTypeId() != Mage_Catalog_Model_Product_Type_Grouped::TYPE_CODE) { $item = $this->getQuote()->addProductAdvanced($product, $config, Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_LITE); } if (is_string($item)) { Mage::throwException($item); } } if (isset($config['pck_option']) && $config['pck_option'] != '') { $pck_sku = Mage::getModel('catalog/product')->load($config['pck_id'])->getSku(); $item->setPckOption($config['pck_option']); $item->setPckSku($pck_sku); $item->setPckQty((int) $config->getQty()); } $item->checkData(); $this->setRecollect(true); return $this; }
public function writeTempFile($curr_page = 0, $length = 50, $filename = '') { $products = $this->getFeed()->getProductsCollection('', $curr_page, $length); $stock_collection = Mage::getResourceModel('cataloginventory/stock_item_collection'); $content = file_get_contents($this->getFeed()->getDirPath() . '/feed-' . $this->getFeed()->getId() . '-xml-product-block-template.tmp'); $fp = fopen($this->getFeed()->getTempFilePath(), 'a'); $log_fp = fopen(sprintf('%s/productsfeed/%s', Mage::getBaseDir('media'), 'log-' . $this->getFeed()->getId() . '.txt'), 'a'); $log_content = date("F j, Y, g:i:s a") . ', page:' . $curr_page . ', items selected:' . count($products) . "\n"; fwrite($log_fp, $log_content); fclose($log_fp); $store = Mage::getModel('core/store')->load($this->getFeed()->getStoreId()); $root_category = Mage::getModel('catalog/category')->load($store->getRootCategoryId()); if (Mage::getStoreConfig('gomage_feedpro/imagesettings/enable')) { $image_width = intval(Mage::getStoreConfig('gomage_feedpro/imagesettings/width')); $image_height = intval(Mage::getStoreConfig('gomage_feedpro/imagesettings/height')); } else { $image_width = 0; $image_height = 0; } foreach ($products as $_product) { $category_path = array(); $category = null; foreach ($_product->getCategoryIds() as $id) { $_category = $this->getFeed()->getCategoriesCollection()->getItemById($id); if (is_null($category) || $category && $_category && $category->getLevel() < $_category->getLevel()) { $category = $_category; } } if ($category) { $category_path = array($category->getName()); $parent_id = $category->getParentId(); if ($category->getLevel() > $root_category->getLevel()) { while ($_category = $this->getFeed()->getCategoriesCollection()->getItemById($parent_id)) { if ($_category->getLevel() <= $root_category->getLevel()) { break; } $category_path[] = $_category->getName(); $parent_id = $_category->getParentId(); } } } $product = new Varien_Object(); if ($category) { $product->setCategory($category->getName()); $product->setCategoryId($category->getEntityId()); $product->setCategorySubcategory(implode(' -> ', array_reverse($category_path))); } else { $product->setCategory(''); $product->setCategorySubcategory(''); } $template_attributes = $this->getAllVars($content); $custom_attributes = Mage::getResourceModel('gomage_feed/custom_attribute_collection'); $custom_attributes->load(); foreach ($template_attributes as $attribute_code) { $value = null; switch ($attribute_code) { case 'parent_sku': if (($parent_product = $this->getFeed()->getParentProduct($_product, $products)) && $parent_product->getEntityId() > 0) { $value = $parent_product->getSku(); } else { $value = ''; } break; case 'parent_base_image': if (($parent_product = $this->getFeed()->getParentProduct($_product, $products)) && $parent_product->getEntityId() > 0) { $_prod = Mage::getModel('catalog/product')->load($parent_product->getId()); } else { $_prod = Mage::getModel('catalog/product')->load($_product->getId()); } try { if ($image_width || $image_height) { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image')->resize($image_width, $image_height); } else { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image'); } } catch (Exception $e) { $image_url = ''; } $value = $image_url; break; case 'price': if (in_array($_product->getTypeId(), array(Mage_Catalog_Model_Product_Type::TYPE_GROUPED, Mage_Catalog_Model_Product_Type::TYPE_BUNDLE))) { $value = $store->convertPrice($_product->getMinimalPrice(), false, false); } else { $value = $store->convertPrice($_product->getPrice(), false, false); } break; case 'store_price': case 'final_price': $value = $store->convertPrice($_product->getFinalPrice(), false, false); break; case 'image': case 'gallery': case 'media_gallery': $_prod = Mage::getModel('catalog/product')->load($_product->getId()); try { if ($image_width || $image_height) { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image')->resize($image_width, $image_height); } else { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image'); } } catch (Exception $e) { $image_url = ''; } $product->setData($attribute_code, $image_url); break; case 'image_2': case 'image_3': case 'image_4': case 'image_5': if (!$_product->hasData('media_gallery_images')) { $_prod = Mage::getModel('catalog/product')->load($_product->getId()); $_product->setData('media_gallery_images', $_prod->getMediaGalleryImages()); } $i = 0; foreach ($_product->getMediaGalleryImages() as $_image) { $i++; if ('image_' . $i == $attribute_code) { if ($image_width || $image_height) { $product->setData($attribute_code, (string) Mage::helper('catalog/image')->init($_product, 'image', $_image->getFile())->resize($image_width, $image_height)); } else { $product->setData($attribute_code, $_image['url']); } } } break; case 'parent_url': if (($parent_product = $this->getFeed()->getParentProduct($_product, $products)) && $parent_product->getEntityId() > 0) { $product->setParentUrl($parent_product->getProductUrl(false)); break; } $product->setParentUrl($_product->getProductUrl(false)); break; case 'url': $product->setUrl($_product->getProductUrl(false)); break; default: if (strpos($attribute_code, 'custom:') === 0) { $custom_code = trim(str_replace('custom:', '', $attribute_code)); if ($custom_attribute = $custom_attributes->getItemByColumnValue('code', $custom_code)) { $options = Zend_Json::decode($custom_attribute->getData('data')); foreach ($options as $option) { foreach ($option['condition'] as $condition) { switch ($condition['attribute_code']) { case 'product_type': $attr_value = $_product->getTypeId(); break; case 'price': if (in_array($_product->getTypeId(), array(Mage_Catalog_Model_Product_Type::TYPE_GROUPED, Mage_Catalog_Model_Product_Type::TYPE_BUNDLE))) { $attr_value = $store->convertPrice($_product->getMinimalPrice(), false, false); } else { $attr_value = $store->convertPrice($_product->getPrice(), false, false); } break; case 'store_price': $attr_value = $store->convertPrice($_product->getFinalPrice(), false, false); break; case 'parent_url': if (($parent_product = $this->getFeed()->getParentProduct($_product, $products)) && $parent_product->getEntityId() > 0) { $attr_value = $parent_product->getProductUrl(false); break; } $attr_value = $_product->getProductUrl(false); break; case 'image': case 'gallery': case 'media_gallery': if (!$_product->hasData('product_base_image')) { $_prod = Mage::getModel('catalog/product')->load($_product->getId()); try { if ($image_width || $image_height) { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image')->resize($image_width, $image_height); } else { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image'); } } catch (Exception $e) { $image_url = ''; } $_product->setData('product_base_image', $image_url); $attr_value = $image_url; } else { $attr_value = $_product->getData('product_base_image'); } break; case 'url': $attr_value = $_product->getProductUrl(false); break; case 'qty': if ($stock_item = $stock_collection->getItemByColumnValue('product_id', $_product->getId())) { $attr_value = ceil($stock_collection->getItemByColumnValue('product_id', $_product->getId())->getQty()); } else { $attr_value = 0; } break; case 'is_in_stock': $attr_value = ceil(Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getIsInStock()); if (!$attr_value || $attr_value == '' || $attr_value == null) { $attr_value = 0; } // if($stock_item = $stock_collection->getItemByColumnValue('product_id', $_product->getId())){ // // $attr_value = $stock_collection->getItemByColumnValue('product_id', $_product->getId())->getData('is_in_stock'); // // }else{ // // $attr_value = 0; // // } break; case 'category': $attr_value = $product->getCategory(); break; case 'category_id': $attr_value = $_product->getCategoryIds(); break; default: $attr_value = $_product->getData($condition['attribute_code']); } $cond_value = $condition['value']; $is_multi = false; if ($product_attribute = $_product->getResource()->getAttribute($condition['attribute_code'])) { if ($product_attribute->getFrontendInput() == 'multiselect') { $is_multi = true; $attr_value = explode(',', $attr_value); } } if ($condition['attribute_code'] == 'category_id') { $is_multi = true; } switch ($condition['condition']) { case 'eq': if (!$is_multi && $attr_value == $cond_value || $is_multi && in_array($cond_value, $attr_value)) { continue 2; } else { continue 3; } break; case 'neq': if (!$is_multi && $attr_value != $cond_value || $is_multi && !in_array($cond_value, $attr_value)) { continue 2; } else { continue 3; } break; case 'gt': if ($attr_value > $cond_value) { continue 2; } else { continue 3; } break; case 'lt': if ($attr_value < $cond_value) { continue 2; } else { continue 3; } break; case 'gteq': if ($attr_value >= $cond_value) { continue 2; } else { continue 3; } break; case 'lteq': if ($attr_value <= $cond_value) { continue 2; } else { continue 3; } break; case 'like': if (strpos($attr_value, $cond_value) !== false) { continue 2; } else { continue 3; } break; case 'nlike': if (strpos($attr_value, $cond_value) === false) { continue 2; } else { continue 3; } break; } } if (in_array($option['value_type'], array('percent', 'attribute'))) { switch ($option['value_type_attribute']) { case 'price': if (in_array($_product->getTypeId(), array(Mage_Catalog_Model_Product_Type::TYPE_GROUPED, Mage_Catalog_Model_Product_Type::TYPE_BUNDLE))) { $attribute_value = $store->convertPrice($_product->getMinimalPrice(), false, false); } else { $attribute_value = $store->convertPrice($_product->getPrice(), false, false); } break; case 'store_price': $attribute_value = $store->convertPrice($_product->getFinalPrice(), false, false); break; case 'parent_url': if (($parent_product = $this->getFeed()->getParentProduct($_product, $products)) && $parent_product->getEntityId() > 0) { $attribute_value = $parent_product->getProductUrl(false); break; } $attribute_value = $_product->getProductUrl(false); break; case 'image': case 'gallery': case 'media_gallery': if (!$_product->hasData('product_base_image')) { $_prod = Mage::getModel('catalog/product')->load($_product->getId()); try { if ($image_width || $image_height) { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image')->resize($image_width, $image_height); } else { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image'); } } catch (Exception $e) { $image_url = ''; } $_product->setData('product_base_image', $image_url); $attribute_value = $image_url; } else { $attribute_value = $_product->getData('product_base_image'); } break; case 'url': $attribute_value = $_product->getProductUrl(false); break; case 'qty': $attribute_value = ceil(Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()); if (!$attribute_value || $attribute_value == '' || $attribute_value == null) { $attribute_value = 0; } // if($stock_item = $stock_collection->getItemByColumnValue('product_id', $_product->getId())){ // // $attribute_value = ceil($stock_collection->getItemByColumnValue('product_id', $_product->getId())->getQty()); // // }else{ // // $attribute_value = 0; // // } break; case 'category': $attribute_value = $product->getCategory(); break; default: $attribute_value = $_product->getData($option['value_type_attribute']); } } if ($option['value_type'] == 'percent') { $value = floatval($attribute_value) / 100 * floatval($option['value']); } elseif ($option['value_type'] == 'attribute') { $value = $attribute_value; } else { $value = $option['value']; } break; } if ($value === null && $custom_attribute->getDefaultValue()) { switch ($custom_attribute->getDefaultValue()) { case 'price': if (in_array($_product->getTypeId(), array(Mage_Catalog_Model_Product_Type::TYPE_GROUPED, Mage_Catalog_Model_Product_Type::TYPE_BUNDLE))) { $value = $store->convertPrice($_product->getMinimalPrice(), false, false); } else { $value = $store->convertPrice($_product->getPrice(), false, false); } break; case 'store_price': $value = $store->convertPrice($_product->getFinalPrice(), false, false); break; case 'parent_url': if (($parent_product = $this->getFeed()->getParentProduct($_product, $products)) && $parent_product->getEntityId() > 0) { $value = $parent_product->getProductUrl(false); break; } $value = $_product->getProductUrl(false); break; case 'image': case 'gallery': case 'media_gallery': if (!$_product->hasData('product_base_image')) { $_prod = Mage::getModel('catalog/product')->load($_product->getId()); try { if ($image_width || $image_height) { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image')->resize($image_width, $image_height); } else { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image'); } } catch (Exception $e) { $image_url = ''; } $_product->setData('product_base_image', $image_url); $value = $image_url; } else { $value = $_product->getData('product_base_image'); } break; case 'url': $value = $_product->getProductUrl(false); break; case 'qty': $value = ceil(Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()); if (!$value || $value == '' || $value == null) { $value = 0; } // if($stock_item = $stock_collection->getItemByColumnValue('product_id', $_product->getId())){ // // $value = ceil($stock_collection->getItemByColumnValue('product_id', $_product->getId())->getQty()); // // }else{ // // $value = 0; // // } break; case 'category': $value = $product->getCategory(); break; default: $value = $_product->getData($custom_attribute->getDefaultValue()); } } } } elseif ($attribute_model = $_product->getResource()->getAttribute($attribute_code)) { switch ($attribute_model->getFrontendInput()) { case 'select': case 'multiselect': $value = implode(', ', (array) $_product->getAttributeText($attribute_code)); break; default: $value = $_product->getData($attribute_code); break; } } break; } if ($value && !$product->getData($attribute_code)) { $product->setData($attribute_code, $value); } } $product->setDescription(strip_tags(preg_replace('/<br.*?>/s', "\r\n", $_product->getDescription()))); $product->setShortDescription(strip_tags(preg_replace('/<br.*?>/s', "\r\n", $_product->getShortDescription()))); $product->setQty(ceil(Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty())); fwrite($fp, parent::setVars($content, $product) . "\r\n"); } fclose($fp); }
/** * Add product to current order quote * $product can be either product id or product model * $config can be either buyRequest config, or just qty * * @param int|Mage_Catalog_Model_Product $product * @param float|array|Varien_Object $config * @return Mage_Adminhtml_Model_Sales_Order_Create */ public function addProduct($product, $config = 1) { if (!is_array($config) && !$config instanceof Varien_Object) { $config = array('qty' => $config); } $config = new Varien_Object($config); if (!$product instanceof Mage_Catalog_Model_Product) { $productId = $product; $product = Mage::getModel('catalog/product')->setStore($this->getSession()->getStore())->setStoreId($this->getSession()->getStoreId())->load($product); if (!$product->getId()) { Mage::throwException(Mage::helper('adminhtml')->__('Failed to add a product to cart by id "%s".', $productId)); } } $stockItem = $product->getStockItem(); if ($stockItem && $stockItem->getIsQtyDecimal()) { $product->setIsQtyDecimal(1); } else { $config->setQty((int) $config->getQty()); } $product->setCartQty($config->getQty()); $item = $this->getQuote()->addProductAdvanced($product, $config, Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_FULL); if (is_string($item)) { if ($product->getTypeId() != Mage_Catalog_Model_Product_Type_Grouped::TYPE_CODE) { $item = $this->getQuote()->addProductAdvanced($product, $config, Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_LITE); } if (is_string($item)) { Mage::throwException($item); } } $item->checkData(); $this->setRecollect(true); return $this; }
/** * Add quote request to shoppping cart */ public function orderAction() { $quoteId = (int) $this->getRequest()->getParam('quote_id'); $checkoutSession = Mage::getSingleton('checkout/session'); if ($quoteId) { $quote = Mage::getModel('request4quote/quote')->loadByIdWithoutStore($quoteId); if ($quote->getId()) { $cart = Mage::getSingleton('checkout/cart'); if ($quote->getStoreId()) { $quotestore = $quote->getStoreId(); } else { $quotestore = Mage::app()->getStore()->getId(); } foreach ($quote->getAllItems() as $item) { if ($item->getParentItem()) { continue; } $product = $item->getProduct(); if ($product) { $product = Mage::getModel('catalog/product')->setStoreId($quotestore)->load($product->getId()); $info = $item->getOptionByCode('info_buyRequest'); if ($info) { $infoBuyReqest = new Varien_Object(unserialize($info->getValue())); } else { $infoBuyReqest = new Varien_Object(array('qty' => 1)); } $infoBuyReqest->setQty($item->getQty()); $infoBuyReqest->setData(ITwebexperts_Request4quote_Model_Quote::PRICE_PROPOSAL_OPTION, $item->getR4qPriceProposal()); $infoBuyReqest->setData(ITwebexperts_Request4quote_Model_Quote::QUOTE_ID_OPTION, $quote->getId()); try { $cart->addProduct($product, $infoBuyReqest); if ($quote->getCouponCode()) { $cart->getQuote()->setCouponCode($quote->getCouponCode()); } } catch (Exception $e) { $checkoutSession->addError($this->__($e->getMessage())); } } else { $checkoutSession->addError($this->__('Product does not exists anymore.')); } } $cart->save(); Mage::getSingleton('checkout/session')->setCartWasUpdated(true); Mage::dispatchEvent('after_request4quote_order', array('quote' => $quote, 'cart' => $cart)); } else { $checkoutSession->addError($this->__('Wrong quote id.')); } } else { $checkoutSession->addError($this->__('Wrong quote id.')); } $this->_redirect('checkout/cart/index'); }
/** * Get request for product add to cart procedure * * @see Mage_Checkout_Model_Cart::_getProductRequest() * @param mixed $requestInfo * @return Varien_Object */ protected function _getProductRequest($info) { if ($info instanceof Varien_Object) { $request = $info; } else { if (is_numeric($info)) { $request = new Varien_Object(array('qty' => $info)); } else { $request = new Varien_Object($info); } } if (!$request->hasQty()) { $request->setQty(1); } return $request; }
/** * Convert multidimensional array to object * @param $arr * * @return object */ public static function arrayToObject($arr) { $finalArrObj = array(); foreach ($arr as $arrDate => $arrObj) { $vObject = new Varien_Object(); if (isset($arrObj['q'])) { $vObject->setQty($arrObj['q']); } if (isset($arrObj['o'])) { $vObject->setOrders($arrObj['o']); } $finalArrObj[$arrDate] = $vObject; } return $finalArrObj; }