/** * Add the items from the given order to the Order Sync queue. Does nothing if * Order Sync is disabled for the store that the order was placed in. * * @param Mage_Sales_Model_Order $order * @param bool $force Skip enabled check * * @return $this */ public function addOrderToQueue(Mage_Sales_Model_Order $order, $force = false) { if (!$this->isEnabled($order->getStoreId()) && !$force) { return $this; } $items = array(); foreach ($order->getAllVisibleItems() as $item) { /** @var Mage_Sales_Model_Order_Item $item */ // For configurable products add children items only, for all other products add parents if ($item->getProductType() == Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) { foreach ($item->getChildrenItems() as $child) { if ($child->getId() != null) { $items[] = $child->getId(); } } } else { if ($item->getId() != null) { $items[] = $item->getId(); } } } // in case of multiple addresses used for shipping // its possible that items object here is empty // if so, we do not add to the item. if (!empty($items)) { $this->addItemsToQueue($items); } return $this; }
public function generateAcceptedOfferArray(Mage_Sales_Model_Order $order) { $array = array(); foreach ($order->getAllVisibleItems() as $item) { $_offer = array('@type' => 'Offer', 'itemOffered' => array('@type' => 'Product', 'name' => $item->getName(), 'sku' => $item->getSku(), 'image' => $item->getImageUrl()), 'price' => (string) number_format($item->getPrice(), 2), 'priceCurrency' => $order->getBaseCurrency()->getCurrencyCode(), 'eligibleQuantity' => array('@type' => 'QuantitativeValue', 'value' => $item->getQtyOrdered())); $array[] = $_offer; } return $array; }
/** * Collect options selected at checkout and calculate type consignment * * @return string */ public function getCheckoutOptionsHtml() { $html = false; $pgAddress = $this->_helper->getPgAddress($this->_order); /** @var object $data Data from checkout */ $data = $this->_order->getMyparcelData() !== null ? json_decode($this->_order->getMyparcelData(), true) : false; $shippingMethod = $this->_order->getShippingMethod(); if ($pgAddress && $this->_helper->shippingMethodIsPakjegemak($shippingMethod)) { if (is_array($data) && key_exists('location', $data)) { $dateTime = date('d-m-Y H:i', strtotime($data['date'] . ' ' . $data['start_time'])); $html .= $this->__('PostNL location:') . ' ' . $dateTime; if ($data['price_comment'] != 'retail') { $html .= ', ' . $this->__('TYPE_' . $data['price_comment']); } $html .= ', ' . $data['location'] . ', ' . $data['city'] . ' (' . $data['postal_code'] . ')'; } else { /** Old data from orders before version 1.6.0 */ $html .= $this->__('PostNL location:') . ' ' . $pgAddress->getCompany() . ' ' . $pgAddress->getCity(); } } else { // Get package type $totalWeight = $this->_helper->getTotalWeight($this->_order->getAllVisibleItems()); if ($totalWeight !== false) { $html .= $this->_helper->getPackageType($totalWeight, $this->_order->getShippingAddress()->getCountryId(), true) . ' '; if (is_array($data) && key_exists('date', $data)) { $dateTime = date('d-m-Y H:i', strtotime($data['date'] . ' ' . $data['time'][0]['start'])); $html .= $this->__('deliver:') . ' ' . $dateTime; if ($data['time'][0]['price_comment'] != 'standard') { $html .= ', ' . $this->__('TYPE_' . $data['time'][0]['price_comment']); } if (key_exists('home_address_only', $data) && $data['home_address_only']) { $html .= ', ' . strtolower($this->__('Home address only')); } if (key_exists('signed', $data) && $data['signed']) { $html .= ', ' . strtolower($this->__('Signature on receipt')); } } } } if (is_array($data) && key_exists('browser', $data)) { $html = ' <span title="' . $data['browser'] . '"">' . $html . '</span>'; } return $html !== false ? '<br>' . $html : ''; }
public static function crateFromOrder(Mage_Sales_Model_Order $order) { $aOrder = new self(); $aOrder->id = $order->getIncrementId(); $aOrder->currency = $order->getOrderCurrencyCode(); $aOrder->total_amount = Aplazame_Sdk_Serializer_Decimal::fromFloat($order->getTotalDue()); $aOrder->articles = array_map(array('Aplazame_Aplazame_BusinessModel_Article', 'crateFromOrderItem'), $order->getAllVisibleItems()); if (($discounts = $order->getDiscountAmount()) !== null) { $aOrder->discount = Aplazame_Sdk_Serializer_Decimal::fromFloat(-$discounts); } return $aOrder; }
/** * Return items information, to be send to API * @param Mage_Sales_Model_Order $order * @return array */ public function getItemsParams(Mage_Sales_Model_Order $order) { $return = array(); if ($items = $order->getAllVisibleItems()) { for ($x = 1, $y = 0, $c = count($items); $x <= $c; $x++, $y++) { $return['itemId' . $x] = $items[$y]->getId(); $return['itemDescription' . $x] = substr($items[$y]->getName(), 0, 100); $return['itemAmount' . $x] = number_format($items[$y]->getPrice(), 2, '.', ''); $return['itemQuantity' . $x] = $items[$y]->getQtyOrdered(); } } return $return; }
/** * Notify Sailthru that a purchase has been made. This automatically cancels * any scheduled abandoned cart email. * */ public function sendOrder(Mage_Sales_Model_Order $order) { try { $this->_eventType = 'placeOrder'; $data = array('email' => $order->getCustomerEmail(), 'items' => $this->_getItems($order->getAllVisibleItems()), 'adjustments' => $this->_getAdjustments($order), 'message_id' => $this->getMessageId(), 'send_template' => 'Purchase Receipt', 'tenders' => $this->_getTenders($order)); /** * Send order data to purchase API */ $responsePurchase = $this->apiPost('purchase', $data); /** * Send customer data to user API */ //$responseUser = Mage::getModel('sailthruemail/client_user')->sendCustomerData($customer); } catch (Exception $e) { Mage::logException($e); return false; } }
/** * @return array */ protected function _prepareOrderItems() { /** @var Mage_Sales_Model_Order_Item[] $items */ $items = $this->_order->getAllVisibleItems(); $data = array(); /** @var Mage_Catalog_Model_Product_Media_Config $productMediaConfig */ $productMediaConfig = Mage::getModel('catalog/product_media_config'); if ($items) { foreach ($items as $item) { /** @var Mage_Catalog_Model_Product $product */ $product = Mage::getModel('catalog/product')->load($item->getProductId()); $smallImageUrl = $productMediaConfig->getMediaUrl($product->getData('small_image')); $item_data = array_filter(array('item_id' => $item->getId(), 'product_id' => $item->getProductId(), 'name' => $item->getName(), 'sku' => $item->getSku(), 'url' => $product->getProductUrl(), 'image_url' => $smallImageUrl, 'details' => $product->getData('short_description'), 'details_full' => $product->getData('description'), 'is_virtual' => $item->getIsVirtual(), 'quantity' => $item->getQtyOrdered(), 'quantity_is_decimal' => $item->getIsQtyDecimal(), 'item_subtotal_with_tax' => $item->getPriceInclTax(), 'item_subtotal' => $item->getPrice(), 'item_tax' => $item->getTaxAmount(), 'item_hidden_tax' => $item->getHiddenTaxAmount(), 'item_tax_before_discount' => $item->getTaxBeforeDiscount(), 'item_shipping_with_tax' => null, 'item_shipping' => null, 'item_discount' => $item->getDiscountAmount(), 'item_discount_with_tax' => null, 'item_total' => $item->getRowTotal(), 'item_total_with_tax' => $item->getRowTotalInclTax())); $data[] = $item_data; unset($item); } } return $data; }
/** * Add the items from the given order to the Order Sync queue. Does nothing if * Order Sync is disabled for the store that the order was placed in. * * @param Mage_Sales_Model_Order $order * @param bool $force Skip enabled check * * @return $this */ public function addOrderToQueue(Mage_Sales_Model_Order $order, $force = false) { if (!$this->isEnabled($order->getStoreId()) && !$force) { return $this; } $items = array(); foreach ($order->getAllVisibleItems() as $item) { /** @var Mage_Sales_Model_Order_Item $item */ // For configurable products add children items only, for all other products add parents if ($item->getProductType() == Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) { foreach ($item->getChildrenItems() as $child) { $items[] = $child->getId(); } } else { $items[] = $item->getId(); } } $this->addItemsToQueue($items); return $this; }
/** * Add the items from the given order to the Order Sync queue. Does nothing if * Order Sync is disabled for the store that the order was placed in. * * @param Mage_Sales_Model_Order $order * @param bool $force Skip enabled check * * @return $this */ public function addOrderToQueue(Mage_Sales_Model_Order $order, $force = false) { if (!$this->isEnabled($order->getStoreId()) && !$force) { return $this; } $items = array(); $order_date = Mage::helper("klevu_search/compat")->now(); $session_id = session_id(); $ip_address = Mage::helper("klevu_search")->getIp(); $order_email = 'unknown'; if ($order->getCustomerId()) { $order_email = $order->getCustomer()->getEmail(); //logged in customer } else { $order_email = $order->getBillingAddress()->getEmail(); //not logged in customer } foreach ($order->getAllVisibleItems() as $item) { /** @var Mage_Sales_Model_Order_Item $item */ // For configurable products add children items only, for all other products add parents if ($item->getProductType() == Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) { foreach ($item->getChildrenItems() as $child) { if ($child->getId() != null) { $items[] = array($child->getId(), $session_id, $ip_address, $order_date, $order_email); } } } else { if ($item->getId() != null) { $items[] = array($item->getId(), $session_id, $ip_address, $order_date, $order_email); } } } // in case of multiple addresses used for shipping // its possible that items object here is empty // if so, we do not add to the item. if (!empty($items)) { $this->addItemsToQueue($items); } return $this; }
/** * @param array $data * @param Mage_Sales_Model_Quote|Mage_Sales_Model_Order $object */ private function _fillCartInformation(&$data, $object) { $productIids = array(); $productQtys = array(); $productStyleIds = array(); /** @var Mage_Sales_Model_Quote_Item|Mage_Sales_Model_Order_Item $item */ foreach ($object->getAllVisibleItems() as $item) { $productIids[] = $item->getProduct()->getIid(); $productQtys[] = is_null($item->getQtyOrdered()) ? (int) $item->getQty() : (int) $item->getQtyOrdered(); $productStyleIds[] = $item->getProduct()->getNumber() . '-' . $item->getProduct()->getColorCode(); } $data['productStyleId'] = implode(',', $productStyleIds); $data['cartProductIds'] = implode(',', $productIids); $data['cartProductQtys'] = implode(',', $productQtys); $data['cartTotalNetto'] = round($object->getBaseSubtotal(), 2); $data['cartTotalBrutto'] = round($object->getBaseGrandTotal(), 2); $data['customerId'] = (int) $object->getCustomerId(); // For zanox tracking if (array_key_exists('zanpid', $_COOKIE) && $_COOKIE['zanpid'] != '') { $data['zanpid'] = $_COOKIE['zanpid']; } }
/** * @return self */ public function process() { $orderId = $this->_payload->getCustomerOrderId(); $this->_order = $this->_getOrder($orderId); $logData = ['order_id' => $orderId]; if (!$this->_order) { $logMessage = 'Order ({order_id}) not found in Magento. Could not process that order.'; $this->_logger->warning($logMessage, $this->_context->getMetaData(__CLASS__, $logData)); return $this; } if (!$this->_order->canCreditMemo()) { $logMessage = 'Credit memo cannot be created for order {order_id}'; $this->_logger->warning($logMessage, $this->_context->getMetaData(__CLASS__, $logData)); return $this; } $this->_order->getAllVisibleItems(); if ($this->_order->hasInvoices()) { $this->_processInvoicedCreditMemos(); } else { $this->_processCreditMemo(); } return $this; }
public function notifyAction() { //header( 'Content-Type:text/html; charset=UTF-8' ); $idLog = generateIdLog(); $logActivo = Mage::getStoreConfig('payment/redsys/logactivo', Mage::app()->getStore()); $mantenerPedidoAnteError = Mage::getStoreConfig('payment/redsys/errorpedido', Mage::app()->getStore()); $orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId(); $this->escribirLog($idLog . " -- " . "Notificando desde Redsys ", $logActivo); if (!empty($_POST)) { //URL RESP. ONLINE /** Recoger datos de respuesta * */ $version = $_POST["Ds_SignatureVersion"]; $datos = $_POST["Ds_MerchantParameters"]; $firma_remota = $_POST["Ds_Signature"]; $this->escribirLog($idLog . " -- " . "Ds_SignatureVersion: " . $version, $logActivo); $this->escribirLog($idLog . " -- " . "Ds_MerchantParameters: " . $datos, $logActivo); $this->escribirLog($idLog . " -- " . "Ds_Signature: " . $firma_remota, $logActivo); // Se crea Objeto $miObj = new RedsysAPI(); /** Se decodifican los datos enviados y se carga el array de datos * */ $decodec = $miObj->decodeMerchantParameters($datos); /** Clave * */ $kc = Mage::getStoreConfig('payment/redsys/clave256', Mage::app()->getStore()); /** Se calcula la firma * */ $firma_local = $miObj->createMerchantSignatureNotif($kc, $datos); /** Extraer datos de la notificación * */ $total = $miObj->getParameter('Ds_Amount'); $pedido = $miObj->getParameter('Ds_Order'); $codigo = $miObj->getParameter('Ds_MerchantCode'); $terminal = $miObj->getParameter('Ds_Terminal'); $moneda = $miObj->getParameter('Ds_Currency'); $respuesta = $miObj->getParameter('Ds_Response'); $fecha = $miObj->getParameter('Ds_Date'); $hora = $miObj->getParameter('Ds_Hour'); $id_trans = $miObj->getParameter('Ds_AuthorisationCode'); $tipoTrans = $miObj->getParameter('Ds_TransactionType'); // Recogemos los datos del comercio $codigoOrig = Mage::getStoreConfig('payment/redsys/num', Mage::app()->getStore()); $terminalOrig = Mage::getStoreConfig('payment/redsys/terminal', Mage::app()->getStore()); $monedaOrig = Mage::getStoreConfig('payment/redsys/moneda', Mage::app()->getStore()); $tipoTransOrig = Mage::getStoreConfig('payment/redsys/trans', Mage::app()->getStore()); // Obtenemos el código ISO del tipo de moneda if ($monedaOrig == "0") { $monedaOrig = "978"; } else { $monedaOrig = "840"; } // INI MOD #7375 // Limpiamos 0 por delante agregados para pasarlo como parámetro $pedido = ltrim($pedido, '0'); // FIN MOD #7375 // Inicializamos el valor del status del pedido $status = ""; // Validacion de firma y parámetros if ($firma_local === $firma_remota && checkImporte($total) && checkPedidoNum($pedido) && checkFuc($codigo) && checkMoneda($moneda) && checkRespuesta($respuesta) && $tipoTrans == $tipoTransOrig && $codigo == $codigoOrig && intval(strval($terminalOrig)) == intval(strval($terminal))) { // Respuesta cumple las validaciones $respuesta = intval($respuesta); $this->escribirLog($idLog . " - Código de respuesta: " . $respuesta, $logActivo); if ($respuesta < 101) { //Mage::log('Redsys: Pago aceptado'); $this->escribirLog($idLog . " - Pago aceptado.", $logActivo); //Correo electrónico $correo = Mage::getStoreConfig('payment/redsys/correo', Mage::app()->getStore()); $mensaje = Mage::getStoreConfig('payment/redsys/mensaje', Mage::app()->getStore()); $nombreComercio = Mage::getStoreConfig('payment/redsys/nombre', Mage::app()->getStore()); //Datos del cliente $customer = Mage::getSingleton('customer/session')->getCustomer(); if ($correo != "0") { $email_to = $customer->getEmail(); $email_subject = "-MAGENTO- Pedido realizado"; if (mail($email_to, $email_subject, $mensaje, "From:" . $nombreComercio)) { echo "Correo enviado"; } else { echo "No se puedo enviar el correo"; } } //Fin de correo //Id pedido $ord = $pedido; $orde = $ord; $this->escribirLog($idLog . " - Order increment id " . $orde, $logActivo); $order = Mage::getModel('sales/order')->loadByIncrementId($orde); $transaction_amount = number_format($order->getBaseGrandTotal(), 2, '', ''); $amountOrig = (double) $transaction_amount; if ($amountOrig != $total) { $this->escribirLog($idLog . " -- " . "El importe total no coincide.", $logActivo); //Mage::log('Redsys: Diferente importe'); // Diferente importe $state = 'new'; $status = 'canceled'; $comment = 'Redsys ha actualizado el estado del pedido con el valor "' . $status . '"'; $isCustomerNotified = true; $order->setState($state, $status, $comment, $isCustomerNotified); $order->registerCancellation("")->save(); $order->save(); //$this->_redirect('checkout/onepage/failure'); $this->escribirLog($idLog . " -- " . "El pedido con ID de carrito " . $orde . " es inválido.", $logActivo); } try { if (!$order->canInvoice()) { $order->addStatusHistoryComment('Redsys, imposible generar Factura.', false); $order->save(); } //START Handle Invoice $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice(); $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE); $invoice->register(); $invoice->getOrder()->setCustomerNoteNotify(true); $invoice->getOrder()->setIsInProcess(true); $order->addStatusHistoryComment('Redsys ha generado la Factura del pedido', false); $transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder()); $transactionSave->save(); //END Handle Invoice //START Handle Shipment //$shipment = $order->prepareShipment(); //$shipment->register(); //$order->setIsInProcess(true); //$order->addStatusHistoryComment('Redsys ENVIO.', false); //$transactionSave = Mage::getModel('core/resource_transaction') // ->addObject($shipment) // ->addObject($shipment->getOrder()) // ->save(); //END Handle Shipment //Email al cliente $order->sendNewOrderEmail(); echo "Pedido: {$ord} se ha enviado correctamente\n"; //Se actualiza el pedido $state = 'new'; $status = 'processing'; $comment = 'Redsys ha actualizado el estado del pedido con el valor "' . $status . '"'; $isCustomerNotified = true; $order->setState($state, $status, $comment, $isCustomerNotified); $order->save(); $this->escribirLog($idLog . " -- " . "El pedido con ID de carrito " . $orderId . " es válido y se ha registrado correctamente.", $logActivo); // INI MOD #7375 Borramos el carrito porque el módulo no lo hacía $session->setQuoteId($order->getQuoteId()); $session->getQuote()->setIsActive(false)->save(); // FIN MOD #7375 // //$this->_redirect('checkout/onepage/success'); } catch (Exception $e) { $order->addStatusHistoryComment('Redsys: Exception message: ' . $e->getMessage(), false); $order->save(); } } else { $this->escribirLog($idLog . " - Pago no aceptado", $logActivo); $ord = $pedido; $orde = $ord; $order = Mage::getModel('sales/order')->loadByIncrementId($orde); $state = 'new'; $status = 'canceled'; $comment = 'Redsys ha actualizado el estado del pedido con el valor "' . $status . '"'; $this->escribirLog($idLog . " - Actualizado el estado del pedido con el valor " . $status, $logActivo); $isCustomerNotified = true; $order->setState($state, $status, $comment, $isCustomerNotified); $order->registerCancellation("")->save(); $order->save(); //$this->_redirect('checkout/onepage/failure'); } } else { $this->escribirLog($idLog . " - Validaciones NO superadas", $logActivo); $ord = $pedido; $orde = $ord; $order = Mage::getModel('sales/order')->loadByIncrementId($orde); $state = 'new'; $status = 'canceled'; $comment = 'Redsys ha actualizado el estado del pedido con el valor "' . $status . '"'; $isCustomerNotified = true; $order->setState($state, $status, $comment, $isCustomerNotified); $order->registerCancellation("")->save(); $order->save(); //$this->_redirect('checkout/onepage/failure'); } } else { if (!empty($_GET)) { //URL OK Y KO /** Recoger datos de respuesta * */ $version = $_GET["Ds_SignatureVersion"]; $datos = $_GET["Ds_MerchantParameters"]; $firma_remota = $_GET["Ds_Signature"]; // Se crea Objeto $miObj = new RedsysAPI(); /** Se decodifican los datos enviados y se carga el array de datos * */ $decodec = $miObj->decodeMerchantParameters($datos); /** Clave * */ $kc = Mage::getStoreConfig('payment/redsys/clave256', Mage::app()->getStore()); /** Se calcula la firma * */ $firma_local = $miObj->createMerchantSignatureNotif($kc, $datos); /** Extraer datos de la notificación * */ $total = $miObj->getParameter('Ds_Amount'); $pedido = $miObj->getParameter('Ds_Order'); $codigo = $miObj->getParameter('Ds_MerchantCode'); $terminal = $miObj->getParameter('Ds_Terminal'); $moneda = $miObj->getParameter('Ds_Currency'); $respuesta = $miObj->getParameter('Ds_Response'); $fecha = $miObj->getParameter('Ds_Date'); $hora = $miObj->getParameter('Ds_Hour'); $id_trans = $miObj->getParameter('Ds_AuthorisationCode'); $tipoTrans = $miObj->getParameter('Ds_TransactionType'); // Recogemos los datos del comercio $codigoOrig = Mage::getStoreConfig('payment/redsys/num', Mage::app()->getStore()); $terminalOrig = Mage::getStoreConfig('payment/redsys/terminal', Mage::app()->getStore()); $monedaOrig = Mage::getStoreConfig('payment/redsys/moneda', Mage::app()->getStore()); $tipoTransOrig = Mage::getStoreConfig('payment/redsys/trans', Mage::app()->getStore()); // Obtenemos el código ISO del tipo de moneda if ($monedaOrig == "0") { $monedaOrig = "978"; } else { $monedaOrig = "840"; } // INI MOD #7375 // Limpiamos 0 por delante agregados para pasarlo como parámetro $pedido = ltrim($pedido, '0'); // FIN MOD #7375 if ($firma_local === $firma_remota && checkImporte($total) && checkPedidoNum($pedido) && checkFuc($codigo) && checkMoneda($moneda) && checkRespuesta($respuesta) && $tipoTrans == $tipoTransOrig && $codigo == $codigoOrig && intval(strval($terminalOrig)) == intval(strval($terminal))) { $respuesta = intval($respuesta); $orde = $pedido; $order = Mage::getModel('sales/order')->loadByIncrementId($orde); if ($respuesta < 101) { $transaction_amount = number_format($order->getBaseGrandTotal(), 2, '', ''); $amountOrig = (double) $transaction_amount; if ($amountOrig != $total) { $this->_redirect('checkout/onepage/failure'); } else { $this->_redirect('checkout/onepage/success'); } } else { if (strval($mantenerPedidoAnteError) == 1) { $_order = new Mage_Sales_Model_Order(); $orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId(); $_order->loadByIncrementId($orderId); $items = $_order->getAllVisibleItems(); $cart = Mage::getSingleton('checkout/cart'); foreach ($items as $itemId => $item) { $this->escribirLog($idLog . " - Cargado carrito con " . $item->getName(), $logActivo); $cart->addOrderItem($item); } $cart->save(); } $this->_redirect('checkout/onepage/failure'); } } else { $this->_redirect('checkout/onepage/failure'); } } else { echo 'No hay respuesta por parte de Redsys!'; } } }
/** * Initializes the payment. * @param Mage_Sales_Model_Order * @param Mage_Shipping_Model_Shipping * @return array */ public function orderCreateRequest(Mage_Sales_Model_Order $order, $allShippingRates) { $this->_order = $order; $orderCurrencyCode = $this->_order->getOrderCurrencyCode(); $orderCountryCode = $this->_order->getBillingAddress()->getCountry(); $shippingCostList = array(); if (empty($allShippingRates) || Mage::getSingleton('customer/session')->isLoggedIn()) { if ($order->getShippingInclTax() > 0) { $shippingCostList['shippingMethods'][] = array('name' => $order->getShippingDescription(), 'country' => $orderCountryCode, 'price' => $this->toAmount($order->getShippingInclTax())); } $grandTotal = $this->_order->getGrandTotal() - $order->getShippingInclTax(); } else { $firstPrice = 0; foreach ($allShippingRates as $key => $rate) { $gross = $this->toAmount($rate->getPrice()); if ($key == 0) { $firstPrice = $rate->getPrice(); } $shippingCostList['shippingMethods'][] = array('name' => $rate->getMethodTitle(), 'country' => $orderCountryCode, 'price' => $gross); } $grandTotal = $this->_order->getGrandTotal() - $firstPrice; } $shippingCost = array('countryCode' => $orderCountryCode, 'shipToOtherCountry' => 'true', 'shippingCostList' => $shippingCostList); $orderItems = $this->_order->getAllVisibleItems(); $items = array(); $productsTotal = 0; $is_discount = false; foreach ($orderItems as $key => $item) { $itemInfo = $item->getData(); if ($itemInfo['discount_amount'] > 0) { $itemInfo['price_incl_tax'] = $itemInfo['price_incl_tax'] - $itemInfo['discount_amount']; $is_discount = true; } else { if ($itemInfo['discount_percent'] > 0) { $itemInfo['price_incl_tax'] = $itemInfo['price_incl_tax'] * (100 - $itemInfo['discount_percent']) / 100; } } // Check if the item is countable one if ($this->toAmount($itemInfo['price_incl_tax']) > 0) { $items['products'][] = array('quantity' => (int) $itemInfo['qty_ordered'], 'name' => $itemInfo['name'], 'unitPrice' => $this->toAmount($itemInfo['price_incl_tax'])); $productsTotal += $itemInfo['price_incl_tax'] * $itemInfo['qty_ordered']; } } //if($this->_order->getShippingAmount () > 0 && !empty ( $shippingCostList['shippingMethods'][0] ) ){ // $items ['products'] ['products'] [] = array ( // 'quantity' => 1 ,'name' => Mage::helper ( 'payu_account' )->__('Shipping costs') . " - " . $shippingCostList['shippingMethods'][0]['name'] ,'unitPrice' => $this->toAmount ( $this->_order->getShippingAmount () )); //} // assigning the shopping cart $shoppingCart = array('grandTotal' => $this->toAmount($grandTotal), 'CurrencyCode' => $orderCurrencyCode, 'ShoppingCartItems' => $items); $orderInfo = array('merchantPosId' => OpenPayU_Configuration::getMerchantPosId(), 'orderUrl' => Mage::getBaseUrl() . 'sales/order/view/order_id/' . $this->_order->getId() . '/', 'description' => 'Order no ' . $this->_order->getRealOrderId(), 'validityTime' => $this->_config->getOrderValidityTime()); if ($is_discount) { $items['products'] = array(); $items['products'][] = array('quantity' => 1, 'name' => Mage::helper('payu_account')->__('Order # ') . $this->_order->getId(), 'unitPrice' => $this->toAmount($grandTotal)); } $OCReq = $orderInfo; $OCReq['products'] = $items['products']; $OCReq['customerIp'] = Mage::app()->getFrontController()->getRequest()->getClientIp(); $OCReq['notifyUrl'] = $this->_myUrl . 'orderNotifyRequest'; $OCReq['cancelUrl'] = $this->_myUrl . 'cancelPayment'; $OCReq['continueUrl'] = $this->_myUrl . 'continuePayment'; $OCReq['currencyCode'] = $orderCurrencyCode; $OCReq['totalAmount'] = $shoppingCart['grandTotal']; $OCReq['extOrderId'] = $this->_order->getId() . '-' . microtime(); if (!empty($shippingCostList)) { $OCReq['shippingMethods'] = $shippingCostList['shippingMethods']; } unset($OCReq['shoppingCart']); $customer_sheet = array(); $billingAddressId = $this->_order->getBillingAddressId(); if (!empty($billingAddressId)) { $billingAddress = $this->_order->getBillingAddress(); $customer_mail = $billingAddress->getEmail(); if (!empty($customer_mail)) { $customer_sheet = array('email' => $billingAddress->getEmail(), 'phone' => $billingAddress->getTelephone(), 'firstName' => $billingAddress->getFirstname(), 'lastName' => $billingAddress->getLastname()); $shippingAddressId = $this->_order->getShippingAddressId(); if (!empty($shippingAddressId)) { $shippingAddress = $this->_order->getShippingAddress(); } if (!$this->_order->getIsVirtual()) { $customer_sheet['delivery'] = array('street' => trim(implode(' ', $shippingAddress->getStreet())), 'postalCode' => $shippingAddress->getPostcode(), 'city' => $shippingAddress->getCity(), 'countryCode' => $shippingAddress->getCountry(), 'recipientName' => trim($shippingAddress->getFirstname() . ' ' . $shippingAddress->getLastname()), 'recipientPhone' => $shippingAddress->getTelephone(), 'recipientEmail' => $shippingAddress->getEmail()); } $OCReq['buyer'] = $customer_sheet; } } $result = OpenPayU_Order::create($OCReq); if ($result->getStatus() == 'SUCCESS') { // store session identifier in session info Mage::getSingleton('core/session')->setPayUSessionId($result->getResponse()->orderId); // assign current transaction id $this->_transactionId = $result->getResponse()->orderId; $order->getPayment()->setLastTransId($this->_transactionId); $locale = Mage::getStoreConfig('general/locale/code', Mage::app()->getStore()->getId()); $lang_code = explode('_', $locale, 2); $ret = array('redirectUri' => $result->getResponse()->redirectUri, 'url' => OpenPayu_Configuration::getSummaryUrl(), 'sessionId' => $result->getResponse()->orderId, 'lang' => strtolower($lang_code[1])); $customer = Mage::getModel('customer/customer'); if ($this->_order->getCustomerIsGuest()) { $email = $billingAddress->getEmail(); $customer->setWebsiteId(Mage::app()->getWebsite()->getId()); $customer->loadByEmail($email); } else { $customer->load($this->_order->getCustomerId()); } if (!$customer->getId()) { $this->_order->setCustomerEmail($email); } $this->_order->sendNewOrderEmail(); $this->_order->save(); } else { Mage::throwException(Mage::helper('payu_account')->__('There was a problem with initializing the payment, please contact the store administrator. ' . $result->getError())); } return $ret; }
/** * Generate Invoice Print XML * @param Mage_Sales_Model_Order $order * @return mixed */ public function getInvoiceExtraPrintBlocksXML($order) { $dom = new DOMDocument('1.0', 'utf-8'); $OnlineInvoice = $dom->createElement('OnlineInvoice'); $dom->appendChild($OnlineInvoice); $OnlineInvoice->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $OnlineInvoice->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsd', 'http://www.w3.org/2001/XMLSchema'); $OrderLines = $dom->createElement('OrderLines'); $OnlineInvoice->appendChild($OrderLines); // Add Order Lines $items = $order->getAllVisibleItems(); /** @var $item Mage_Sales_Model_Order_Item */ foreach ($items as $item) { // @todo Calculate prices using Discount Rules // @todo Get children products from bundle //if (!$item->getNoDiscount()) { // Mage::helper('partpayment/tools')->addToDebug('Warning: The product has a discount. There might be problems.', $order->getIncrementId()); //} $itemQty = (int) $item->getQtyOrdered(); //$taxPrice = $item->getTaxAmount(); $taxPrice = $itemQty * $item->getPriceInclTax() - $itemQty * $item->getPrice(); $taxPercent = $item->getTaxPercent(); $priceWithTax = $itemQty * $item->getPriceInclTax(); // Calculate tax percent for Bundle products if ($item->getProductType() === Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) { $taxPercent = $taxPrice > 0 ? round(100 / (($priceWithTax - $taxPrice) / $taxPrice)) : 0; } $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $item->getName())); $OrderLine->appendChild($dom->createElement('Qty', $itemQty)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $item->getPrice()))); $OrderLine->appendChild($dom->createElement('VatRate', sprintf("%.2f", $taxPercent))); $OrderLine->appendChild($dom->createElement('VatAmount', sprintf("%.2f", $taxPrice))); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $priceWithTax))); $OrderLines->appendChild($OrderLine); } // Add Shipping Line if (!$order->getIsVirtual()) { $shipping = $order->getShippingAmount(); //$shippingIncTax = $order->getShippingInclTax(); $shippingTax = $order->getShippingTaxAmount(); $shippingTaxPercent = $shipping != 0 ? (int) (100 * $shippingTax / $shipping) : 0; $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $order->getShippingDescription())); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $shipping))); $OrderLine->appendChild($dom->createElement('VatRate', sprintf("%.2f", $shippingTaxPercent))); $OrderLine->appendChild($dom->createElement('VatAmount', sprintf("%.2f", $shippingTax))); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $shipping + $shippingTax))); $OrderLines->appendChild($OrderLine); } // add Payment Fee $fee = $order->getPartpaymentPaymentFee(); if ($fee > 0) { $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', Mage::helper('partpayment')->__('Payment fee'))); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $fee))); $OrderLine->appendChild($dom->createElement('VatRate', 0)); $OrderLine->appendChild($dom->createElement('VatAmount', 0)); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $fee))); $OrderLines->appendChild($OrderLine); } // add Discount $discount = $order->getDiscountAmount() + $order->getShippingDiscountAmount(); if (abs($discount) > 0) { $discount_description = $order->getDiscountDescription() !== null ? Mage::helper('sales')->__('Discount (%s)', $order->getDiscountDescription()) : Mage::helper('sales')->__('Discount'); $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $discount_description)); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $discount))); $OrderLine->appendChild($dom->createElement('VatRate', 0)); $OrderLine->appendChild($dom->createElement('VatAmount', 0)); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $discount))); $OrderLines->appendChild($OrderLine); } // Add reward points if ((double) $order->getBaseRewardCurrencyAmount() > 0) { $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', Mage::helper('partpayment')->__('Reward points'))); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', -1 * $order->getBaseRewardCurrencyAmount())); $OrderLine->appendChild($dom->createElement('VatRate', 0)); $OrderLine->appendChild($dom->createElement('VatAmount', 0)); $OrderLine->appendChild($dom->createElement('Amount', -1 * $order->getBaseRewardCurrencyAmount())); $OrderLines->appendChild($OrderLine); } return str_replace("\n", '', $dom->saveXML()); }
/** * Function to persist orders to be flushed to Bronto * * @param Mage_Sales_Model_Order $order * @param Bronto_Api_Order $brontoOrder * @param Bronto_Order_Model_Queue $orderRow * @param array $context */ protected function _persistOrder($order, $brontoOrder, $orderRow, $context) { extract($context); // Get visible items from order $items = $order->getAllVisibleItems(); // Keep product order by using a new array $fullItems = array(); $brontoOrderItems = array(); // loop through the items. if it's a bundled item, // replace the parent item with the child items. foreach ($items as $item) { $itemProduct = Mage::getModel('catalog/product')->load($item->getProductId()); // Handle product based on product type switch ($itemProduct->getTypeId()) { // Bundled products need child items case Mage_Catalog_Model_Product_Type::TYPE_BUNDLE: if (count($item->getChildrenItems()) > 0) { foreach ($item->getChildrenItems() as $childItem) { if ($childItem->getPrice() != 0) { $item->setPrice(0); } $fullItems[] = $childItem; } } $fullItems[] = $item; break; // Configurable products just need simple config item // Configurable products just need simple config item case Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE: $childItems = $item->getChildrenItems(); if (1 === count($childItems)) { $childItem = $childItems[0]; // Collect options applicable to the configurable product $productAttributeOptions = $itemProduct->getTypeInstance(true)->getConfigurableAttributesAsArray($itemProduct); // Build Selected Options Name $nameWithOptions = array(); foreach ($productAttributeOptions as $productAttribute) { $itemValue = $productHelper->getProductAttribute($childItem->getProductId(), $productAttribute['attribute_code'], $storeId); $nameWithOptions[] = $productAttribute['label'] . ': ' . $itemValue; } // Set parent product name to include selected options $parentName = $item->getName() . ' [' . implode(', ', $nameWithOptions) . ']'; $item->setName($parentName); } $fullItems[] = $item; break; // Grouped products need parent and child items // Grouped products need parent and child items case Mage_Catalog_Model_Product_Type::TYPE_GROUPED: // This condition probably never gets hit, parent grouped items don't show in order $fullItems[] = $item; foreach ($item->getChildrenItems() as $child_item) { $fullItems[] = $child_item; } break; // Anything else (namely simples) just get added to array // Anything else (namely simples) just get added to array default: $fullItems[] = $item; break; } } // Cycle through newly created array of products foreach ($fullItems as $item) { // If product has a parent, get that parent product $parent = false; if ($item->getParentItem()) { $parent = Mage::getModel('catalog/product')->setStoreId($storeId)->load($item->getParentItem()->getProductId()); } /* @var $product Mage_Catalog_Model_Product */ $product = Mage::getModel('catalog/product')->setStoreId($storeId)->load($item->getProductId()); // If there is a parent product, use that to get category ids if ($parent) { $categoryIds = $parent->getCategoryIds(); } else { $categoryIds = $product->getCategoryIds(); } // If the product type is simple and the description // is empty, then attempt to find a parent product // to backfill the description. $parentProduct = $productHelper->getConfigurableProduct($product); if (!$product->getData($descriptionAttr)) { $product->setData($descriptionAttr, $parentProduct->getData($descriptionAttr)); } if (empty($categoryIds)) { $categoryIds = $parentProduct->getCategoryIds(); } // Cycle through category ids to pull category details $categories = array(); foreach ($categoryIds as $categoryId) { /* @var $category Mage_Catalog_Model_Category */ $category = Mage::getModel('catalog/category')->load($categoryId); $parent = $category->getParentCategory(); $categories[] = $parent->getUrlKey() ? $parent->getUrlKey() : $parent->formatUrlKey($parent->getName()); $categories[] = $category->getUrlKey() ? $category->getUrlKey() : $category->formatUrlKey($category->getName()); } // Check to ensure there are no duplicate categories $categories = array_unique($categories); // Write orderItem $brontoOrderItems[] = array('id' => $item->getId(), 'sku' => $item->getSku(), 'name' => $item->getName(), 'description' => $product->getData($descriptionAttr), 'category' => implode(' ', $categories), 'image' => $this->_helper->getItemImg($item, $product, $storeId), 'url' => $this->_helper->getItemUrl($item, $product, $storeId), 'quantity' => (int) $item->getQtyOrdered(), 'price' => $this->_helper->getItemPrice($item, $basePrefix, $inclTaxes, $inclDiscounts)); } if ($inclShipping && $order->getState() == Mage_Sales_Model_Order::STATE_COMPLETE && $order->hasShipments()) { $shippingObject = new Varien_Object(array('qty_ordered' => 1, 'base_row_total' => $order->getBaseShippingAmount(), 'row_total' => $order->getShippingAmount(), 'base_tax_amount' => $order->getBaseShippingTaxAmount(), 'tax_amount' => $order->getShippingTaxAmount(), 'base_discount_amount' => $order->getBaseShippingDiscountAmount(), 'discount_amount' => $order->getShippingDiscountAmount())); $descriptions = array(); foreach ($order->getTracksCollection() as $track) { if ($track->hasTrackNumber() && $track->hasTitle()) { $descriptions[] = "{$track->getTitle()} - {$track->getTrackNumber()}"; } } $shipmentItem = array('sku' => 'SHIPPING', 'name' => $order->getShippingDescription(), 'description' => implode("<br/>", $descriptions), 'quantity' => 1, 'price' => $this->_helper->getItemPrice($shippingObject, $basePrefix, $inclTaxes, $inclDiscounts)); $brontoOrderItems[] = $shipmentItem; } $brontoOrder->products = $brontoOrderItems; $brontoOrder->persist(); }
/** * Convert an order to a LinkShare refund row. * * @param Mage_Sales_Model_Order $order * @return array */ public function orderToFeed(Mage_Sales_Model_Order $order) { $orderDate = new Zend_Date($order->getCreatedAt(), Varien_Date::DATETIME_INTERNAL_FORMAT); $orderDate = $orderDate->toString('yyyy-MM-dd'); $transDate = Mage::getModel('core/date')->date('Y-m-d'); $rows = array(); foreach ($order->getAllVisibleItems() as $item) { /* @var $item Mage_Sales_Model_OrderItem */ if ($item->getQtyCanceled() > 0) { $rows[] = array('order_id' => $order->getIncrementId(), 'site_id' => '', 'order_date' => $orderDate, 'transaction_date' => $transDate, 'sku' => $item->getSku(), 'quantity' => round($item->getQtyCanceled()), 'amount' => ($item->getBaseRowTotal() - $item->getBaseDiscountAmount()) * -100, 'currency' => $order->getBaseCurrencyCode(), 'blank' => '', 'blank' => '', 'blank' => '', 'product_name' => ''); } } return $rows; }
/** * Generates a textual description of the applied discount rules * * @param Mage_Sales_Model_Order $order * @return string discount description */ protected function buildDiscountRuleDescription(Mage_Sales_Model_Order $order) { try { $appliedRules = array(); foreach ($order->getAllVisibleItems() as $item) { $itemAppliedRules = $item->getAppliedRuleIds(); if (empty($itemAppliedRules)) { continue; } $ruleIds = explode(',', $item->getAppliedRuleIds()); foreach ($ruleIds as $ruleId) { $rule = Mage::getModel('salesrule/rule')->load($ruleId); $appliedRules[$ruleId] = $rule->getName(); } } if (count($appliedRules) == 0) { $appliedRules[] = 'unknown rule'; } $discountTxt = sprintf('Discount (%s)', implode(', ', $appliedRules)); } catch (\Exception $e) { $discountTxt = 'Discount (error)'; } return $discountTxt; }
/** * Generate Invoice Print XML * (only used for Factoring & PartPayment) * @param Mage_Sales_Model_Order $order * @return mixed */ public function getInvoiceExtraPrintBlocksXML($order) { $dom = new DOMDocument('1.0', 'utf-8'); $OnlineInvoice = $dom->createElement('OnlineInvoice'); $dom->appendChild($OnlineInvoice); $OnlineInvoice->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $OnlineInvoice->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsd', 'http://www.w3.org/2001/XMLSchema'); $OrderLines = $dom->createElement('OrderLines'); $OnlineInvoice->appendChild($OrderLines); // Add Order Lines $items = $order->getAllVisibleItems(); /** @var $item Mage_Sales_Model_Order_Item */ foreach ($items as $item) { $itemQty = (int) $item->getQtyOrdered(); $priceWithTax = $item->getRowTotalInclTax(); $priceWithoutTax = $item->getRowTotal(); $taxPercent = ($priceWithTax / $priceWithoutTax - 1) * 100; // works for all types $taxPrice = $priceWithTax - $priceWithoutTax; mb_regex_encoding("utf-8"); $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', trim(mb_ereg_replace('[^a-zA-Z0-9_:!#=?\\[\\]@{}´ %-\\/À-ÖØ-öø-ú]', "-", $item->getName())))); $OrderLine->appendChild($dom->createElement('Qty', $itemQty)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $priceWithoutTax / $itemQty))); $OrderLine->appendChild($dom->createElement('VatRate', sprintf("%.2f", $taxPercent))); $OrderLine->appendChild($dom->createElement('VatAmount', sprintf("%.2f", $taxPrice))); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $priceWithTax))); $OrderLines->appendChild($OrderLine); } // Add Shipping Line if (!$order->getIsVirtual()) { $shippingExclTax = $order->getShippingAmount(); $shippingIncTax = $order->getShippingInclTax(); $shippingTax = $shippingIncTax - $shippingExclTax; // find out tax-rate for the shipping if ((double) $shippingIncTax && (double) $shippingExclTax) { $shippingTaxRate = ($shippingIncTax / $shippingExclTax - 1) * 100; } else { $shippingTaxRate = 0; } $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $order->getShippingDescription())); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $shippingExclTax))); $OrderLine->appendChild($dom->createElement('VatRate', sprintf("%.2f", $shippingTaxRate))); $OrderLine->appendChild($dom->createElement('VatAmount', sprintf("%.2f", $shippingTax))); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $shippingIncTax))); $OrderLines->appendChild($OrderLine); } // add Payment Fee $fee = $order->getPartpaymentPaymentFee(); if ($fee > 0) { $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $this->getHelper()->__('Payment fee'))); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", $fee))); $OrderLine->appendChild($dom->createElement('VatRate', 0)); $OrderLine->appendChild($dom->createElement('VatAmount', 0)); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", $fee))); $OrderLines->appendChild($OrderLine); } // add Discount /** @var AAIT_Shared_Helper_Discount $discountHelper */ $discountHelper = Mage::helper("payexshared/discount"); $discountData = $discountHelper->getOrderDiscountData($order); $discountInclTax = $discountData->getDiscountInclTax(); $discountExclTax = $discountData->getDiscountExclTax(); $discountVatAmount = $discountInclTax - $discountExclTax; $discountVatPercent = ($discountInclTax / $discountExclTax - 1) * 100; if (abs($discountInclTax) > 0) { $discount_description = $order->getDiscountDescription() !== null ? Mage::helper('sales')->__('Discount (%s)', $order->getDiscountDescription()) : Mage::helper('sales')->__('Discount'); $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $discount_description)); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', sprintf("%.2f", -1 * $discountExclTax))); $OrderLine->appendChild($dom->createElement('VatRate', sprintf("%.2f", $discountVatPercent))); $OrderLine->appendChild($dom->createElement('VatAmount', sprintf("%.2f", -1 * $discountVatAmount))); $OrderLine->appendChild($dom->createElement('Amount', sprintf("%.2f", -1 * $discountInclTax))); $OrderLines->appendChild($OrderLine); } // Add reward points if ((double) $order->getBaseRewardCurrencyAmount() > 0) { $OrderLine = $dom->createElement('OrderLine'); $OrderLine->appendChild($dom->createElement('Product', $this->getHelper()->__('Reward points'))); $OrderLine->appendChild($dom->createElement('Qty', 1)); $OrderLine->appendChild($dom->createElement('UnitPrice', -1 * $order->getBaseRewardCurrencyAmount())); $OrderLine->appendChild($dom->createElement('VatRate', 0)); $OrderLine->appendChild($dom->createElement('VatAmount', 0)); $OrderLine->appendChild($dom->createElement('Amount', -1 * $order->getBaseRewardCurrencyAmount())); $OrderLines->appendChild($OrderLine); } return str_replace("\n", '', $dom->saveXML()); }
/** * Is one of the order items canceled * * @param Mage_Sales_Model_Order * @return boolean */ public function isOrderCanceled(Mage_Sales_Model_Order $order) { foreach ($order->getAllVisibleItems() as $item) { if ($item->getQtyCanceled() > 0) { return true; } } return false; }
/** * Create subscription(s) for given order. * * Order items that have the same term and term type are saved * in the same subscription. * * @param Mage_Sales_Model_Order $order * @return array */ public function createSubscription(Mage_Sales_Model_Order $order) { Mage::dispatchEvent('adyen_subscription_order_createsubscription_before', array('order' => $order)); $subscriptions = array(); if ($order->getSubscriptionId()) { $msg = "Don't create subscription, since this order %s is created by a subscription"; Mage::helper('adyen_subscription')->logSubscriptionCron(sprintf($msg, $order->getIncrementId())); return $subscriptions; } $productTerms = array(); foreach ($order->getAllVisibleItems() as $orderItem) { /** @var Mage_Sales_Model_Order_Item $orderItem */ /** @var Adyen_Subscription_Model_Product_Subscription $productSubscription */ $productSubscription = $this->_getProductSubscription($orderItem); if (!$productSubscription) { Mage::helper('adyen_subscription')->logSubscriptionCron(sprintf("No subscription found for order %s with orderItem %s", $order->getIncrementId(), $orderItem->getSku())); continue; } $arrayKey = $productSubscription->getTerm() . $productSubscription->getTermType(); $productTerms[$arrayKey]['term'] = $productSubscription->getTerm(); $productTerms[$arrayKey]['type'] = $productSubscription->getTermType(); $productTerms[$arrayKey]['order_items'][] = $orderItem; } // Create a subscription for each term foreach ($productTerms as $productTerm) { $billingAgreement = $this->_getBillingAgreement($order); $stockId = $order->getStockId() ?: 1; $createdAt = $order->getScheduledAt() ?: $order->getCreatedAt(); // Create subscription /** @var Adyen_Subscription_Model_Subscription $subscription */ $subscription = Mage::getModel('adyen_subscription/subscription')->setCreatedAt($createdAt)->setStatus(Adyen_Subscription_Model_Subscription::STATUS_ACTIVE)->setStockId($stockId)->setCustomerId($order->getCustomerId())->setCustomerName($order->getCustomerName())->setOrderId($order->getId())->setBillingAgreementId($billingAgreement ? $billingAgreement->getId() : null)->setStoreId($order->getStoreId())->setTerm($productTerm['term'])->setTermType($productTerm['type'])->setShippingMethod($order->getShippingMethod())->setUpdatedAt(now()); if (!$billingAgreement) { Mage::helper('adyen_subscription')->logSubscriptionCron(sprintf("No billing agreement could be found, subscription is created but with error")); // but set subscription directly to error $subscription->setErrorMessage(Mage::helper('adyen_subscription')->__('No billing agreement found')); $subscription->setStatus($subscription::STATUS_SUBSCRIPTION_ERROR); } $subscription->save(); $transactionItems = array(); foreach ($productTerm['order_items'] as $orderItem) { /** @var Adyen_Subscription_Model_Product_Subscription $productSubscription */ $productSubscription = $this->_getProductSubscription($orderItem); // Ordered qty is divided by product subscription qty to get 'real' ordered qty $qty = $orderItem->getQtyInvoiced() / $productSubscription->getQty(); // Create subscription item /** @var Adyen_Subscription_Model_Subscription_Item $subscriptionItem */ $subscriptionItem = Mage::getModel('adyen_subscription/subscription_item')->setSubscriptionId($subscription->getId())->setStatus(Adyen_Subscription_Model_Subscription_Item::STATUS_ACTIVE)->setProductId($orderItem->getProductId())->setProductOptions(serialize($orderItem->getProductOptions()))->setSku($orderItem->getSku())->setName($orderItem->getName())->setProductSubscriptionId($productSubscription->getId())->setLabel($productSubscription->getLabel())->setPrice($orderItem->getRowTotal() / $qty)->setPriceInclTax($orderItem->getRowTotalInclTax() / $qty)->setQty($qty)->setOnce(0)->setCreatedAt(now()); Mage::dispatchEvent('adyen_subscription_order_createsubscription_add_item', array('subscription' => $subscription, 'item' => $subscriptionItem)); $transactionItems[] = $subscriptionItem; } // Create subscription addresses $subscriptionBillingAddress = Mage::getModel('adyen_subscription/subscription_address')->initAddress($subscription, $order->getBillingAddress())->save(); $subscriptionShippingAddress = Mage::getModel('adyen_subscription/subscription_address')->initAddress($subscription, $order->getShippingAddress())->save(); /** @var Mage_Sales_Model_Quote $quote */ $quote = Mage::getModel('sales/quote')->setStore($order->getStore())->load($order->getQuoteId()); $subscription->setActiveQuote($quote); $orderAdditional = $subscription->getOrderAdditional($order, true)->save(); $quoteAdditional = $subscription->getActiveQuoteAdditional(true)->setOrder($order); $scheduleDate = $subscription->calculateNextScheduleDate(); $subscription->setScheduledAt($scheduleDate); $transaction = Mage::getModel('core/resource_transaction')->addObject($subscription)->addObject($orderAdditional)->addObject($quoteAdditional); foreach ($transactionItems as $item) { $transaction->addObject($item); } $transaction->save(); $subscriptions[] = $subscription; Mage::dispatchEvent('adyen_subscription_order_createsubscription_after', array('order' => $order, 'subscription' => $subscription)); } if (!empty($subscription) && $subscription->getId()) { $order->setCreatedAdyenSubscription(true); } return $subscriptions; }
/** * Send email id payment is in Fraud status * @param Mage_Customer_Model_Customer $receiver * @param Mage_Sales_Model_Order $order * @param string $message * @return Mage_Checkout_Helper_Data */ public function sendFraudPaymentEmail($receiver, $order, $message, $email_key = 'fraud_payment') { $translate = Mage::getSingleton('core/translate'); /* @var $translate Mage_Core_Model_Translate */ $translate->setTranslateInline(false); $mailTemplate = Mage::getModel('core/email_template'); /* @var $mailTemplate Mage_Core_Model_Email_Template */ $template = Mage::getStoreConfig('hipay/' . $email_key . '/template', $order->getStoreId()); $copyTo = $this->_getEmails('hipay/' . $email_key . '/copy_to', $order->getStoreId()); $copyMethod = Mage::getStoreConfig('hipay/' . $email_key . '/copy_method', $order->getStoreId()); if ($copyTo && $copyMethod == 'bcc') { $mailTemplate->addBcc($copyTo); } $sendTo = array(array('email' => $receiver->getEmail(), 'name' => $receiver->getName())); if ($copyTo && $copyMethod == 'copy') { foreach ($copyTo as $email) { $sendTo[] = array('email' => $email, 'name' => null); } } $shippingMethod = ''; if ($shippingInfo = $order->getShippingAddress()->getShippingMethod()) { $data = explode('_', $shippingInfo); $shippingMethod = $data[0]; } $paymentMethod = ''; if ($paymentInfo = $order->getPayment()) { $paymentMethod = $paymentInfo->getMethod(); } $items = ''; foreach ($order->getAllVisibleItems() as $_item) { /* @var $_item Mage_Sales_Model_Quote_Item */ $items .= $_item->getProduct()->getName() . ' x ' . $_item->getQty() . ' ' . $order->getStoreCurrencyCode() . ' ' . $_item->getProduct()->getFinalPrice($_item->getQty()) . "\n"; } $total = $order->getStoreCurrencyCode() . ' ' . $order->getGrandTotal(); foreach ($sendTo as $recipient) { $mailTemplate->setDesignConfig(array('area' => 'frontend', 'store' => $order->getStoreId()))->sendTransactional($template, Mage::getStoreConfig('hipay/' . $email_key . '/identity', $order->getStoreId()), $recipient['email'], $recipient['name'], array('reason' => $message, 'dateAndTime' => Mage::app()->getLocale()->date(), 'customer' => $order->getCustomerFirstname() . ' ' . $order->getCustomerLastname(), 'customerEmail' => $order->getCustomerEmail(), 'billingAddress' => $order->getBillingAddress(), 'shippingAddress' => $order->getShippingAddress(), 'shippingMethod' => Mage::getStoreConfig('carriers/' . $shippingMethod . '/title'), 'paymentMethod' => Mage::getStoreConfig('payment/' . $paymentMethod . '/title'), 'items' => nl2br($items), 'total' => $total)); } $translate->setTranslateInline(true); return $this; }
/** * @param Mage_Sales_Model_Order $order * * @return string */ public function getAllProductsSkus(Mage_Sales_Model_Order $order) { $skus = array(); foreach ($order->getAllVisibleItems() as $item) { /** @var Mage_Sales_Model_Order_Item $item */ $skus[] = $item->getSku(); } return implode(',', $skus); }
public function recoveryCart() { $recoveryCart = Mage::getStoreConfig('payment/redsys/recover_cart', Mage::app()->getStore()); if ($recoveryCart) { $_order = new Mage_Sales_Model_Order(); $orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId(); $_order->loadByIncrementId($orderId); $items = $_order->getAllVisibleItems(); $cart = Mage::getSingleton('checkout/cart'); foreach ($items as $itemId => $item) { $cart->addOrderItem($item); } $cart->save(); //@todo Volver a poner la direccion y reenviar al checkout } }
public function init(Mage_Sales_Model_Order $order) { $this->setLiczOd("BRT"); $this->setDataWystawienia(date('Y-m-d')); $this->setDataSprzedazy(date('Y-m-d')); $this->setFormatDatySprzedazy("DZN"); $this->setRodzajPodpisuOdbiorcy("BPO"); $this->setWidocznyNumerGios(true); $this->setZaplacono('0'); $this->setTerminPlatnosci(''); $items = $order->getAllVisibleItems(); $positions = array(); foreach ($items as $item) { /* @var $item Mage_Sales_Model_Order_Item */ $invoice_position = new PowerMedia_Ifirma_Model_InvoicePosition(); $tax = sprintf('%.2f', $item->getTaxPercent() / 100); $invoice_position->setStawkaVat((string) $tax); $invoice_position->setIlosc($item->getQtyOrdered()); $invoice_position->setNazwaPelna($item->getName()); $invoice_position->setJednostka("sztuk"); $invoice_position->setTypStawkiVat("PRC"); $invoice_position->setCenaJednostkowa($item->getPriceInclTax()); $invoice_position->setPKWiU(""); $positions[] = $invoice_position->getProperties(); } $shipping = $order->getShippingInclTax(); if ($shipping >= 0) { /* @var $item Mage_Sales_Model_Order_Item */ $invoice_position = new PowerMedia_Ifirma_Model_InvoicePosition(); $tax = sprintf('%.2f', $item->getTaxPercent() / 100); $invoice_position->setStawkaVat((string) $tax); $invoice_position->setIlosc(1); $invoice_position->setNazwaPelna('Koszty dostawy'); $invoice_position->setJednostka("sztuk"); $invoice_position->setTypStawkiVat("PRC"); $invoice_position->setCenaJednostkowa($shipping); $invoice_position->setPKWiU(""); $positions[] = $invoice_position->getProperties(); } $this->setPozycje($positions); $invoice_contractor = new PowerMedia_Ifirma_Model_InvoiceContractor(); $invoice_contractor->setNazwa($order->getBillingAddress()->getName()); $invoice_contractor->setUlica($order->getBillingAddress()->getStreetFull()); $invoice_contractor->setKodPocztowy($order->getBillingAddress()->getPostcode()); $invoice_contractor->setMiejscowosc($order->getBillingAddress()->getCity()); $invoice_contractor->setKraj($order->getBillingAddress()->getCountry()); $this->setKontrahent($invoice_contractor->getProperties()); }
/** * Loads the order info from a Magento order model. * * @param Mage_Sales_Model_Order $order the order model. */ public function loadData(Mage_Sales_Model_Order $order) { $this->_orderNumber = $order->getId(); $this->_externalOrderRef = $order->getRealOrderId(); $this->_createdDate = $order->getCreatedAt(); $this->_paymentProvider = $order->getPayment()->getMethod(); $this->_orderStatus = Mage::getModel('nosto_tagging/meta_order_status', array('code' => $order->getStatus(), 'label' => $order->getStatusLabel())); foreach ($order->getAllStatusHistory() as $item) { /** @var Mage_Sales_Model_Order_Status_History $item */ $this->_orderStatuses[] = Mage::getModel('nosto_tagging/meta_order_status', array('code' => $item->getStatus(), 'label' => $item->getStatusLabel(), 'createdAt' => $item->getCreatedAt())); } $this->_buyer = Mage::getModel('nosto_tagging/meta_order_buyer', array('firstName' => $order->getCustomerFirstname(), 'lastName' => $order->getCustomerLastname(), 'email' => $order->getCustomerEmail())); foreach ($order->getAllVisibleItems() as $item) { /** @var $item Mage_Sales_Model_Order_Item */ $this->_items[] = $this->buildItem($item, $order); } if ($this->includeSpecialItems) { if (($discount = $order->getDiscountAmount()) > 0) { /** @var Nosto_Tagging_Model_Meta_Order_Item $orderItem */ $this->_items[] = Mage::getModel('nosto_tagging/meta_order_item', array('productId' => -1, 'quantity' => 1, 'name' => 'Discount', 'unitPrice' => $discount, 'currencyCode' => $order->getOrderCurrencyCode())); } if (($shippingInclTax = $order->getShippingInclTax()) > 0) { /** @var Nosto_Tagging_Model_Meta_Order_Item $orderItem */ $this->_items[] = Mage::getModel('nosto_tagging/meta_order_item', array('productId' => -1, 'quantity' => 1, 'name' => 'Shipping and handling', 'unitPrice' => $shippingInclTax, 'currencyCode' => $order->getOrderCurrencyCode())); } } }
/** * Add PayEx Single Order Line * @param string $orderRef * @param Mage_Sales_Model_Order $order * @return bool */ public function addOrderLine($orderRef, $order) { // add Order Items $items = $order->getAllVisibleItems(); $i = 1; /** @var $item Mage_Sales_Model_Order_Item */ foreach ($items as $item) { // @todo Calculate prices using Discount Rules // @todo Get children products from bundle //if (!$item->getNoDiscount()) { // Mage::helper('payexautopay/tools')->addToDebug('Warning: The product has a discount. There might be problems.', $order->getIncrementId()); //} $itemQty = (int) $item->getQtyOrdered(); //$taxPrice = $item->getTaxAmount(); $taxPrice = $itemQty * $item->getPriceInclTax() - $itemQty * $item->getPrice(); $taxPercent = $item->getTaxPercent(); $priceWithTax = $itemQty * $item->getPriceInclTax(); // Calculate tax percent for Bundle products if ($item->getProductType() === Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) { $taxPercent = $taxPrice > 0 ? round(100 / (($priceWithTax - $taxPrice) / $taxPrice)) : 0; } $params = array('accountNumber' => '', 'orderRef' => $orderRef, 'itemNumber' => $i, 'itemDescription1' => $item->getName(), 'itemDescription2' => '', 'itemDescription3' => '', 'itemDescription4' => '', 'itemDescription5' => '', 'quantity' => $itemQty, 'amount' => (int) (100 * $priceWithTax), 'vatPrice' => (int) (100 * $taxPrice), 'vatPercent' => (int) (100 * $taxPercent)); $result = Mage::helper('payexautopay/api')->getPx()->AddSingleOrderLine2($params); Mage::helper('payexautopay/tools')->debugApi($result, 'PxOrder.AddSingleOrderLine2'); $i++; } // add Shipping if (!$order->getIsVirtual()) { $shipping = $order->getShippingAmount(); $shippingIncTax = $order->getShippingInclTax(); $shippingTax = $order->getShippingTaxAmount(); $params = array('accountNumber' => '', 'orderRef' => $orderRef, 'itemNumber' => $i, 'itemDescription1' => $order->getShippingDescription(), 'itemDescription2' => '', 'itemDescription3' => '', 'itemDescription4' => '', 'itemDescription5' => '', 'quantity' => 1, 'amount' => (int) (100 * $shippingIncTax), 'vatPrice' => (int) (100 * $shippingTax), 'vatPercent' => $shipping != 0 ? round(100 * 100 * $shippingTax / $shipping) : 0); $result = Mage::helper('payexautopay/api')->getPx()->AddSingleOrderLine2($params); Mage::helper('payexautopay/tools')->debugApi($result, 'PxOrder.AddSingleOrderLine2'); $i++; } // add Discount $discount = $order->getDiscountAmount() + $order->getShippingDiscountAmount(); if (abs($discount) > 0) { $params = array('accountNumber' => '', 'orderRef' => $orderRef, 'itemNumber' => $i, 'itemDescription1' => $order->getDiscountDescription() !== null ? Mage::helper('sales')->__('Discount (%s)', $order->getDiscountDescription()) : Mage::helper('sales')->__('Discount'), 'itemDescription2' => '', 'itemDescription3' => '', 'itemDescription4' => '', 'itemDescription5' => '', 'quantity' => 1, 'amount' => (int) (100 * $discount), 'vatPrice' => 0, 'vatPercent' => 0); $result = Mage::helper('payexautopay/api')->getPx()->AddSingleOrderLine2($params); Mage::helper('payexautopay/tools')->debugApi($result, 'PxOrder.AddSingleOrderLine2'); $i++; } // Add reward points if ((double) $order->getBaseRewardCurrencyAmount() > 0) { $params = array('accountNumber' => '', 'orderRef' => $orderRef, 'itemNumber' => $i, 'itemDescription1' => Mage::helper('payexautopay')->__('Reward points'), 'itemDescription2' => '', 'itemDescription3' => '', 'itemDescription4' => '', 'itemDescription5' => '', 'quantity' => 1, 'amount' => -1 * (int) (100 * $order->getBaseRewardCurrencyAmount()), 'vatPrice' => 0, 'vatPercent' => 0); $result = Mage::helper('payexautopay/api')->getPx()->AddSingleOrderLine2($params); Mage::helper('payexautopay/tools')->debugApi($result, 'PxOrder.AddSingleOrderLine2'); $i++; } return true; }
/** * Initialize shipment items QTY * * @param Mage_Sales_Model_Order $order * * @return array */ protected function _getItemQtys($order) { $itemQtys = array(); /** * @var Mage_Sales_Model_Order_Item $item */ $items = $order->getAllVisibleItems(); foreach ($items as $item) { /** * the qty to ship is the total remaining (not yet shipped) qty of every item */ $itemQty = $item->getQtyOrdered() - $item->getQtyShipped(); $itemQtys[$item->getId()] = $itemQty; } return $itemQtys; }