/** * @param Mage_Sales_Model_Order $order * * @return $this */ protected function _redirectByOrder(Mage_Sales_Model_Order $order) { if (!$order->getId()) { $this->_redirectCart(); return $this; } if ($order->isCanceled()) { $this->_redirectPaymentError(); return $this; } switch ($order->getState()) { case Mage_Sales_Model_Order::STATE_NEW: $this->_redirectOrderPending(); break; case Mage_Sales_Model_Order::STATE_CANCELED: $this->_redirectPaymentError(); break; case Mage_Sales_Model_Order::STATE_PROCESSING: case Mage_Sales_Model_Order::STATE_COMPLETE: case Mage_Sales_Model_Order::STATE_CLOSED: case Mage_Sales_Model_Order::STATE_HOLDED: case Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW: default: $this->_redirectOrderState(); break; } return $this; }
public function cancelaPedido(Mage_Sales_Model_Order $order) { $paymentMethod = $order->getPayment()->getMethodInstance()->getCode(); $listPaymentMethodsIdeasa = Mage::helper('base')->listPaymentMethods(); $this->logger->info('Processando cancelamento do pedido ' . $order->getRealOrderId() . ', do modulo: ' . $paymentMethod); try { if ($order->getState() != Mage_Sales_Model_Order::STATE_CANCELED) { $order->cancel(); //força o cancelamento if ($order->getStatus() != Mage_Sales_Model_Order::STATE_CANCELED) { $order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true, Mage::helper('base')->__('Pedido cancelado'), $notified = false); } else { $order->addStatusToHistory($order->getStatus(), Mage::helper('base')->__('Pedido cancelado.')); } if ($order->hasInvoices() != '') { $order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true, Mage::helper('base')->__('O pagamento e o pedido foram cancelados, mas não foi possível retornar os produtos ao estoque pois já havia uma fatura gerada para este pedido.'), $notified = false); } $order->save(); } if (Mage::helper('base')->isIdeasaPaymentMethod($paymentMethod) && Mage::helper('base/module')->isPagSeguroDiretoExists() && $paymentMethod == $listPaymentMethodsIdeasa[0]) { Mage::getModel('pagsegurodireto/notification')->sendEmail($order); } } catch (Exception $e) { $this->logger->error("Erro ao cancelar pedido {$orderId} \n {$e->__toString}()"); } $this->logger->info('Cancelamento do pedido foi concluido ' . $order->getRealOrderId() . ', do modulo: ' . $paymentMethod); return; }
/** * Check order view availability * * @param Mage_Sales_Model_Order $order * @return bool */ protected function _canViewOrder($order) { $customerId = Mage::getSingleton('customer/session')->getCustomerId(); $availableStates = Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates(); if ($order->getId() && $order->getCustomerId() && $order->getCustomerId() == $customerId && in_array($order->getState(), $availableStates, $strict = true)) { return true; } return false; }
/** * @return array */ protected function _prepareOrderData() { // magento 1.5 compat $shipping_method_c = $this->_order->getShippingMethod(true); $shipping_method = $this->_order->getData('shipping_method'); $shipping_method_code = $shipping_method_c ? $shipping_method_c->getData('carrier_code') : $shipping_method; $data = array_filter(array('currency_code' => $this->_order->getOrderCurrencyCode(), 'shipping_method_code' => $shipping_method_code, 'shipping_method_title' => $this->_order->getShippingDescription(), 'created_on' => $this->_order->getCreatedAt(), 'updated_on' => $this->_order->getUpdatedAt(), 'state' => $this->_order->getState(), 'status' => $this->_order->getStatus(), 'is_gift' => $this->_order->getGiftMessageId() != null, 'ref_quote_id' => $this->_order->getQuoteId(), 'order_subtotal_with_tax' => $this->_order->getSubtotalInclTax(), 'order_subtotal' => $this->_order->getSubtotal(), 'order_tax' => $this->_order->getTaxAmount(), 'order_hidden_tax' => $this->_order->getHiddenTaxAmount(), 'order_shipping_with_tax' => $this->_order->getShippingInclTax(), 'order_shipping' => $this->_order->getShippingAmount(), 'order_discount' => $this->_order->getDiscountAmount(), 'order_shipping_discount' => $this->_order->getShippingDiscountAmount(), 'order_total' => $this->_order->getGrandTotal(), 'order_total_items' => $this->_order->getTotalItemCount())); return $data; }
public function canSendEmail(Mage_Sales_Model_Order $order) { if ($order->getState() == Mage_Sales_Model_Order::STATE_CANCELED) { if (Mage::getStoreConfig(Ideasa_Base_ConfiguracoesSystem::CONTROLE_ENVIO_EMAIL_CANCELADO)) { return true; } } if ($order->getState() == Mage_Sales_Model_Order::STATE_NEW) { if (Mage::getStoreConfig(Ideasa_Base_ConfiguracoesSystem::CONTROLE_ENVIO_EMAIL_NOVO)) { return true; } } if ($order->getState() == Mage_Sales_Model_Order::STATE_PROCESSING || $order->getState() == Mage_Sales_Model_Order::STATE_COMPLETE) { if (Mage::getStoreConfig(Ideasa_Base_ConfiguracoesSystem::CONTROLE_ENVIO_EMAIL_FATURA_GERADA)) { return true; } } return false; }
public function canCancel(Mage_Sales_Model_Order $order) { if ($order->getCustomerId() != Mage::getSingleton('customer/session')->getCustomerId()) { return false; } if (!in_array($order->getState(), Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates(), $strict = true)) { return false; } if (!$order->canCancel() || $order->hasInvoices() || $order->hasShipments()) { return false; } if ($order->getState() == Mage_Sales_Model_Order::STATE_NEW && $this->canCancelNew($order->getStore())) { return true; } if ($order->getState() == Mage_Sales_Model_Order::STATE_PENDING_PAYMENT && $this->canCancelPending($order->getStore())) { return true; } return false; }
/** * Returns true if order may be edited by currently logged in customer * * @param Mage_Sales_Model_Order $order * @return boolean */ public function isOrderEditable(Mage_Sales_Model_Order $order) { if (!$order->getCustomerId()) { return false; } if (Mage::getSingleton('customer/session')->getCustomerId() != $order->getCustomerId()) { return false; } $allowedStates = explode(',', Mage::getStoreConfig('sales/editcustomoptions/allowed_order_state')); return in_array($order->getState(), $allowedStates); }
/** * processes an order awaiting payment. Sets its new state and status. * * @param $newStates * @param bool $description * @return bool */ protected function _processPendingPayment($newStates, $description = false) { $description = Mage::helper('buckaroo3extended')->__($description); $description .= " (#{$this->_postArray['brq_statuscode']})"; //sets the transaction key if its defined ($trx) //will retrieve it from the response array, if response actually is an array if (!$this->_order->getTransactionKey() && array_key_exists('brq_transactions', $this->_postArray)) { $this->_order->setTransactionKey($this->_postArray['brq_transactions']); } if ($this->_order->getState() == Mage_Sales_Model_Order::STATE_NEW) { $this->_order->addStatusHistoryComment($description, $newStates[1])->save(); $this->_order->setStatus($newStates[1])->save(); } else { $this->_order->addStatusHistoryComment($description)->save(); } return true; }
/** * Process payment pending notification * * @throws Exception */ public function _registerPaymentPending() { $reason = $this->getRequestData('pending_reason'); if ('authorization' === $reason) { $this->_registerPaymentAuthorization(); return; } if ('order' === $reason) { throw new Exception('The "order" authorizations are not implemented.'); } // case when was placed using PayPal standard if (Mage_Sales_Model_Order::STATE_PENDING_PAYMENT == $this->_order->getState() && !$this->getRequestData('transaction_entity')) { $this->_registerPaymentCapture(); return; } $this->_importPaymentInformation(); $this->_order->getPayment()->setPreparedMessage($this->_createIpnComment($this->_info->explainPendingReason($reason)))->setTransactionId($this->getRequestData('txn_id'))->setIsTransactionClosed(0)->registerPaymentReviewAction(Mage_Sales_Model_Order_Payment::REVIEW_ACTION_UPDATE, false); $this->_order->save(); }
/** * @param Mage_Sales_Model_Order $order * @param string $uri * @param string $method * @param string $body */ public function logRequest(Mage_Sales_Model_Order $order = null, $uri, $method, $body) { if (!$this->isApiLogEnabled()) { return; } $message = $this->getDashHash(); $message .= PHP_EOL; $message .= PHP_EOL . 'Starting Request'; $message .= PHP_EOL . 'Request Data:'; $message .= PHP_EOL; if ($order && $order->getId()) { $message .= PHP_EOL . sprintf('Order ID: %s', $order->getId()); $message .= PHP_EOL . sprintf('Order Real ID: %s', $order->getRealOrderId()); $message .= PHP_EOL . sprintf('Order State: %s', $order->getState()); $message .= PHP_EOL . sprintf('Order Status: %s', $order->getStatus()); } $message .= PHP_EOL . sprintf('URI: %s', $uri); $message .= PHP_EOL . sprintf('Method: %s', $method); $message .= PHP_EOL . sprintf('Request Body: %s', $body); $message .= PHP_EOL; $message .= $this->getShortDashHash(); $this->log($message); }
/** * Update payment status to complete * * @param $payment */ public function updatePaymentStatusCompleted($payment) { if ($this->_order->getState() != Mage_Sales_Model_Order::STATE_PROCESSING) { $payment->setTransactionId($this->_transactionId); $payment->setIsTransactionApproved(true); $payment->setIsTransactionClosed(true); $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_ORDER); if (isset($this->_payuPayMethod)) { if ($this->_payuPayMethod == "PBL") { $method = Mage::helper('payu_account')->__('Pay by link'); } if ($this->_payuPayMethod == "CARD_TOKEN") { $method = Mage::helper('payu_account')->__('Pay with card'); } } if (isset($method)) { $payment->setPreparedMessage("PayU - " . $method . " " . Mage::helper('payu_account')->__('The transaction completed successfully.')); $this->_order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true, "PayU - " . $method . " " . Mage::helper('payu_account')->__('The transaction completed successfully.'), false)->sendOrderUpdateEmail(true, "PayU - " . Mage::helper('payu_account')->__('The transaction completed successfully in PayU.'))->save(); } else { $payment->setPreparedMessage("PayU - " . Mage::helper('payu_account')->__('The transaction completed successfully.')); $this->_order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true, "PayU - " . Mage::helper('payu_account')->__('The transaction completed successfully.'), false)->sendOrderUpdateEmail(true, "PayU - " . Mage::helper('payu_account')->__('The transaction completed successfully in PayU.'))->save(); } } }
/** * Add comment to order * * @param Mage_Sales_Model_Order $order * @param string $comment * @param boolean $isShipmentSuccessfullyCreated * * @return void */ public function addCommentToOrder(Mage_Sales_Model_Order $order, $comment, $isShipmentSuccessfullyCreated = false) { /* * for Magento 1.4.x.x */ if (true === $this->getConfig()->isVersionRecommendedOrLarger()) { $order->addStatusHistoryComment($comment)->setIsVisibleOnFront(false)->setIsCustomerNotified(false)->save(); /* * for Magento 1.3.x.x */ } else { //Get existing order status $status = $order->getStatus(); //If shipment was created successfully if (true === $isShipmentSuccessfullyCreated) { $status = Mage_Sales_Model_Order::STATE_PROCESSING; } //Is status is empty, take state if ($status == "") { $status = $order->getState(); } if (false === $isShipmentSuccessfullyCreated) { /* * reload the order to avoid that unwanted order data is saved | SEE DHLIS-181 * Order Items are set as shipped in CE 1.3 even if there was an exception */ $order = Mage::getModel('sales/order')->load($order->getId()); } $order->addStatusToHistory($status, $comment)->save(); } }
/** * Create invoice for order */ protected function createInvoice(Mage_Sales_Model_Order $order) { if ($order->getState() == Mage_Sales_Model_Order::STATE_NEW) { try { if (!$order->canInvoice()) { $order->addStatusHistoryComment('MultiSafepay: Order cannot be invoiced.', false); $order->save(); return false; } //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(false); $invoice->getOrder()->setIsInProcess(true); $order->addStatusHistoryComment('Automatically invoiced by MultiSafepay invoicer.', false); $transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder()); $transactionSave->save(); //END Handle Invoice //Send Invoice emails $mail_invoice = $this->getConfigData("mail_invoice"); $send_bno_invoice = $this->getConfigData("bno_no_invoice"); $gateway = $order->getPayment()->getMethodInstance()->_gateway; if ($mail_invoice && $gateway != 'PAYAFTER') { $invoice->setEmailSent(true); $invoice->sendEmail(); $invoice->save(); } elseif ($gateway == 'PAYAFTER' && !$send_bno_invoice && $mail_invoice) { $invoice->setEmailSent(true); $invoice->sendEmail(); $invoice->save(); } $order->setTotalPaid($order->getGrandTotal()); } catch (Exception $e) { $order->addStatusHistoryComment('MultiSafepay invoicer: Exception occurred during the creation of the invoice. Exception message: ' . $e->getMessage(), false); $order->save(); } } return false; }
/** * Perform order state and status assertions depending on currency code * * @param Mage_Sales_Model_Order $order * @param string $currencyCode */ protected function _assertOrder($order, $currencyCode) { if ($currencyCode == 'USD') { $this->assertEquals('complete', $order->getState()); $this->assertEquals('complete', $order->getStatus()); } else { $this->assertEquals('payment_review', $order->getState()); $this->assertEquals('fraud', $order->getStatus()); } }
/** * Process Configured Payment Action: Direct Sale, create invoce if state is Pending * * @param Mage_Sales_Model_Order $order Order * @param array $params Request params */ protected function _processDirectSale($order, $params, $instantCapture = 0) { Mage::register('postfinance_auto_capture', true); $status = $params['STATUS']; if ($status == PostFinance_Payment_Model_Payment_Abstract::POSTFINANCE_AWAIT_CUSTOMER_PAYMENT) { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, Mage::helper('postfinance')->__('Waiting for the payment of the customer')); $order->save(); } elseif ($status == PostFinance_Payment_Model_Payment_Abstract::POSTFINANCE_AUTHORIZED_WAITING) { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, Mage::helper('postfinance')->__('Authorization waiting from PostFinance')); $order->save(); } elseif ($order->getState() == Mage_Sales_Model_Order::STATE_PENDING_PAYMENT || $instantCapture) { if ($status == PostFinance_Payment_Model_Payment_Abstract::POSTFINANCE_AUTHORIZED) { if ($order->getStatus() != Mage_Sales_Model_Order::STATE_PENDING_PAYMENT) { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, Mage_Sales_Model_Order::STATE_PROCESSING, Mage::helper('postfinance')->__('Processed by PostFinance')); } } else { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, Mage_Sales_Model_Order::STATE_PROCESSING, Mage::helper('postfinance')->__('Processed by PostFinance')); } if (!$order->getInvoiceCollection()->getSize()) { $invoice = $order->prepareInvoice(); $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE); $invoice->register(); $invoice->setState(Mage_Sales_Model_Order_Invoice::STATE_PAID); $invoice->getOrder()->setIsInProcess(true); $invoice->save(); $transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder())->save(); /* * If the payment method is a redirect-payment-method send the email * In any other case Magento sends an email automatically in Mage_Checkout_Model_Type_Onepage::saveOrder */ if ($this->isRedirectPaymentMethod($order) === true && $order->getEmailSent() !== '1') { $order->sendNewOrderEmail(); } } } else { $order->save(); } }
/** * Check if order can be cancelled manually * * @param Mage_Sales_Model_Order $order * @return bool */ public function canCancelManually($order) { $payment = $order->getPayment(); //If order has state 'pending_payment' and the payment has Barclaycard-status 0 or null (unknown) then cancel the order if ($order->getState() == Mage_Sales_Model_Order::STATE_PENDING_PAYMENT && (true === is_null($payment->getAdditionalInformation('status')) || $payment->getAdditionalInformation('status') == '0')) { return true; } else { return false; } }
/** * 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(); }
/** * Process Configured Payment Action: Direct Sale, create invoice if state is Pending * * @param Mage_Sales_Model_Order $order Order * @param array $params Request params */ protected function _processDirectSale($order, $params, $instantCapture = 0) { Mage::register('ops_auto_capture', true); $status = $params['STATUS']; if ($status == Netresearch_OPS_Model_Payment_Abstract::OPS_AWAIT_CUSTOMER_PAYMENT) { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, Mage::helper('ops')->__('Waiting for the payment of the customer')); // send new order mail for bank transfer, since it is 'successfully' authorized at this point if ($order->getPayment()->getMethodInstance() instanceof Netresearch_OPS_Model_Payment_BankTransfer && $order->getEmailSent() != 1) { $order->sendNewOrderEmail(); } $order->save(); } elseif ($status == Netresearch_OPS_Model_Payment_Abstract::OPS_AUTHORIZED_WAITING) { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, Mage::helper('ops')->__('Authorization waiting from Barclaycard')); $order->save(); } elseif ($order->getState() == Mage_Sales_Model_Order::STATE_PENDING_PAYMENT || $instantCapture) { if ($status == Netresearch_OPS_Model_Payment_Abstract::OPS_AUTHORIZED) { if ($order->getStatus() != Mage_Sales_Model_Order::STATE_PENDING_PAYMENT) { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, Mage_Sales_Model_Order::STATE_PROCESSING, Mage::helper('ops')->__('Processed by Barclaycard')); } } else { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true, Mage::helper('ops')->__('Processed by Barclaycard')); $order->save(); } if (!$order->getInvoiceCollection()->getSize() && $order->getState() == Mage_Sales_Model_Order::STATE_PROCESSING && $order->canInvoice()) { $invoice = $order->prepareInvoice(); $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE); $invoice->register(); $invoice->setState(Mage_Sales_Model_Order_Invoice::STATE_PAID); $invoice->getOrder()->setIsInProcess(true); $invoice->save(); $this->sendInvoiceToCustomer($invoice); $transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder())->save(); /* * If the payment method is a redirect-payment-method send the email * In any other case Magento sends an email automatically in Mage_Checkout_Model_Type_Onepage::saveOrder */ if ($this->isRedirectPaymentMethod($order) === true && $order->getEmailSent() != 1) { $order->sendNewOrderEmail(); } $eventData = array('data_object' => $order, 'order' => $order); Mage::dispatchEvent('ops_sales_order_save_commit_after', $eventData); } if ($this->isInlinePayment($order->getPayment()) && 0 < strlen(trim($order->getPayment()->getAdditionalInformation('HTML_ANSWER'))) && $order->getPayment()->getAdditionalInformation('status') == Netresearch_OPS_Model_Payment_Abstract::OPS_PAYMENT_REQUESTED) { $order->getPayment()->setIsTransactionApproved(true)->registerPaymentReviewAction(Mage_Sales_Model_Order_Payment::REVIEW_ACTION_UPDATE, true)->save(); $this->setInvoicesToPaid($order); $order->getPayment()->getAuthorizationTransaction()->setIsClosed(true)->save(); $order->getPayment()->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE, $order->getPayment())->setIsClosed(true)->save(); $order->sendNewOrderEmail(); $order->save(); } if ($this->isInlinePayment($order->getPayment()) && Mage::getModel('ops/config')->getSendInvoice() && Mage::getModel('ops/config')->getPaymentAction($order->getStoreId()) === Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE_CAPTURE) { foreach ($order->getInvoiceCollection() as $invoice) { $this->sendInvoiceToCustomer($invoice); } } } else { $order->save(); } }
/** * Check order state * * If the order state (not status) is already one of: * canceled, closed, holded or completed, * then we do not update the order status anymore. * * @param $order object Mage_Sales_Model_Order */ public function check(Mage_Sales_Model_Order $order) { if ($order->getId()) { $state = $order->getState(); switch ($state) { case Mage_Sales_Model_Order::STATE_HOLDED: case Mage_Sales_Model_Order::STATE_CANCELED: case Mage_Sales_Model_Order::STATE_CLOSED: case Mage_Sales_Model_Order::STATE_COMPLETE: exit; break; default: } } }
/** * Check if the current user made the given order * * @param Mage_Sales_Model_Order $order * @return boolean */ protected function _canViewOrder($order) { $customerId = Mage::getSingleton('customer/session')->getCustomerId(); $availableStates = Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates(); $method = $order->getPayment()->getMethod(); if ($order->getCustomerId() == $customerId && in_array($order->getState(), $availableStates, true) && strpos($method, 'boleto_') !== false) { $this->_method = substr($method, 7); return true; } return false; }
/** * Check if order is valid for frontend display * @see Mage_Sales_Controller_Abstract::_canViewOrder * @return boolean */ public function isOrderFrontendEnabled(Mage_Sales_Model_Order $order) { $availableStates = Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates(); return in_array($order->getState(), $availableStates, $strict = true); }
/** * Poll Amazon API to receive order status and update Magento order. */ public function syncOrderStatus(Mage_Sales_Model_Order $order, $isManualSync = false) { $_api = $this->_getApi($order->getStoreId()); $message = ''; try { $amazonOrderReference = $order->getPayment()->getAdditionalInformation('order_reference'); $orderReferenceDetails = $_api->getOrderReferenceDetails($amazonOrderReference); if ($orderReferenceDetails) { // Retrieve Amazon Authorization Details // Last transaction ID is Amazon Authorize Reference ID $lastAmazonReference = $order->getPayment()->getLastTransId(); $resultAuthorize = $this->_getApi($order->getStoreId())->getAuthorizationDetails($lastAmazonReference); $amazonAuthorizationState = $resultAuthorize->getAuthorizationStatus()->getState(); $reasonCode = $resultAuthorize->getAuthorizationStatus()->getReasonCode(); // Re-authorize if holded, an Open order reference, and manual sync if ($order->getState() == Mage_Sales_Model_Order::STATE_HOLDED && $orderReferenceDetails->getOrderReferenceStatus()->getState() == 'Open' && $isManualSync) { $payment = $order->getPayment(); $amount = $payment->getAmountOrdered(); $method = $payment->getMethodInstance(); // Re-authorize $payment->setTransactionId($amazonOrderReference); $payment->setAdditionalInformation('sandbox', null); // Remove decline and other test simulations $method->setForceSync(true); switch ($method->getConfigData('payment_action')) { case $method::ACTION_AUTHORIZE: $resultAuthorize = $method->authorize($payment, $amount, false); break; case $method::ACTION_AUTHORIZE_CAPTURE: $resultAuthorize = $method->authorize($payment, $amount, true); break; default: break; } // Resync $order->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, true); $order->save(); $this->syncOrderStatus($order); return; } $message = Mage::helper('payment')->__('Sync with Amazon: Authorization state is %s.', $amazonAuthorizationState); switch ($amazonAuthorizationState) { // Pending (All Authorization objects are in the Pending state for 30 seconds after Authorize request) case Amazon_Payments_Model_Api::AUTH_STATUS_PENDING: $message .= ' (Payment is currently authorizing. Please try again momentarily.)'; break; // Declined // Declined case Amazon_Payments_Model_Api::AUTH_STATUS_DECLINED: if ($order->getState() != Mage_Sales_Model_Order::STATE_HOLDED) { $order->setState(Mage_Sales_Model_Order::STATE_HOLDED, true); } if ($reasonCode == 'InvalidPaymentMethod') { $this->_sendPaymentDeclineEmail($order, 'soft'); $message .= " Order placed on hold due to {$reasonCode}. Email sent to customer with link to order details page and instructions to update their payment method."; } else { $this->_sendPaymentDeclineEmail($order, 'hard'); $message .= " Order placed on hold due to {$reasonCode}. Email sent to customer with instructions to contact seller."; } break; // Open (Authorize Only) // Open (Authorize Only) case Amazon_Payments_Model_Api::AUTH_STATUS_OPEN: $order->setState(Mage_Sales_Model_Order::STATE_NEW); $order->setStatus($_api->getConfig()->getNewOrderStatus($order->getStoreId())); break; // Closed (Authorize and Capture) // Closed (Authorize and Capture) case Amazon_Payments_Model_Api::AUTH_STATUS_CLOSED: // Payment captured; create invoice if ($reasonCode == 'MaxCapturesProcessed') { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING); $order->setStatus($_api->getConfig()->getNewOrderStatus($order->getStoreId())); if ($this->_createInvoice($order, $resultAuthorize->getIdList()->getmember())) { $message .= ' ' . Mage::helper('payment')->__('Invoice created.'); } } else { $order->setState(Mage_Sales_Model_Order::STATE_HOLDED, true); $message .= ' Unable to create invoice due to Authorization Reason Code: ' . $reasonCode; } break; } // Update order if ($amazonAuthorizationState != Amazon_Payments_Model_Api::AUTH_STATUS_PENDING) { $order->addStatusToHistory($order->getStatus(), $message, false); $order->save(); } Mage::getSingleton('adminhtml/session')->addSuccess($message); } } catch (Exception $e) { // Change order to "On Hold" if ($order->getState() != Mage_Sales_Model_Order::STATE_HOLDED) { $message = 'Error exception during sync. Please check exception.log'; $order->setState(Mage_Sales_Model_Order::STATE_HOLDED, true); $order->addStatusToHistory($order->getStatus(), $message, false); $order->save(); } Mage::logException($e); Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } }
/** * Check order view availability * * @param Mage_Sales_Model_Order $order * @return bool */ protected function _canViewOrder($order) { $customerId = Mage::getSingleton('Mage_Customer_Model_Session')->getCustomerId(); $availableStates = Mage::getSingleton('Mage_Sales_Model_Order_Config')->getVisibleOnFrontStates(); if ($order->getId() && $order->getCustomerId() && $order->getCustomerId() == $customerId && in_array($order->getState(), $availableStates, true)) { return true; } return false; }
/** * Create invoice for order */ protected function createInvoice(Mage_Sales_Model_Order $order) { if ($order->getState() == Mage_Sales_Model_Order::STATE_NEW) { try { if (!$order->canInvoice()) { $order->addStatusHistoryComment('MultiSafepay: Order cannot be invoiced.', false); $order->save(); return false; } //START Handle Invoice $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice(); $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE); $invoice->register(); $invoice->getOrder()->setCustomerNoteNotify(false); $invoice->getOrder()->setIsInProcess(true); $order->addStatusHistoryComment('Automatically invoiced by MultiSafepay invoicer.', false); $transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder()); $transactionSave->save(); $payment = $order->getPayment(); $transaction = $payment->getTransaction($this->mspDetails['ewallet']['id']); if (is_object($transaction)) { $transaction->setAdditionalInformation(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS, $this->transdetails); $transaction->save(); } if ($this->_config["updatetransaction"]) { $invoiceId = $invoice->getIncrementId(); $msp = new MultiSafepay(); $msp->test = $this->_config["test_api"] == 'test'; $msp->merchant['account_id'] = $this->_config["account_id"]; $msp->merchant['site_id'] = $this->_config["site_id"]; $msp->merchant['site_code'] = $this->_config["secure_code"]; $msp->transaction['id'] = $_GET['transactionid']; $msp->transaction['invoice_id'] = $invoiceId; $msp->updateInvoice(); if ($msp->error) { echo 'update trans error'; } } //END Handle Invoice //Send Invoice emails $mail_invoice = $this->getConfigData("mail_invoice"); $send_bno_invoice = $this->getConfigData("bno_no_invoice"); $gateway = $order->getPayment()->getMethodInstance()->_gateway; if ($mail_invoice && $gateway != 'PAYAFTER' && $gateway != 'KLARNA') { $invoice->setEmailSent(true); $invoice->sendEmail(); $invoice->save(); } elseif (($gateway == 'PAYAFTER' || $gateway == 'KLARNA') && $send_bno_invoice && $mail_invoice) { $invoice->setEmailSent(true); $invoice->sendEmail(); $invoice->save(); } $order->setTotalPaid($order->getGrandTotal()); } catch (Exception $e) { $order->addStatusHistoryComment('MultiSafepay invoicer: Exception occurred during the creation of the invoice. Exception message: ' . $e->getMessage(), false); $order->save(); } } return false; }
/** * execute if transaction was confirmed * * @param SofortLib_TransactionData $transData * @param Mage_Sales_Model_Order $order * @param boolean $forceInvoice = false to create invoice for rechnung, ignoring transaction status * @return void */ private function _transactionConfirmed($transData, $order, $forceInvoice = false) { // unconfirmed notification not process // only rechnung needed if ($order->getState() != 'sofort' && $transData->isSofortrechnung()) { $this->_transactionUnconfirmed($transData, $order, true); } $payment = $order->getPayment(); $paymentObj = $order->getPayment()->getMethodInstance(); $amount = $forceInvoice ? $transData->getAmount() + $transData->getAmountRefunded() : $transData->getAmount(); $currency = $transData->getCurrency(); $statusReason = $transData->getStatusReason(); $transaction = $transData->getTransaction(); // should send a email $notifyCustomer = false; // status the order will be changed $newOrderStatus = $paymentObj->getConfigData('order_status'); // rechnung bestätigt if ($transData->isSofortrechnung() && ($statusReason == 'not_credited_yet' && $transData->getInvoiceStatus() == 'pending' || $forceInvoice)) { $notifyCustomer = false; $newOrderStatus = Mage::getStoreConfig('payment/sofort/sofortrechnung_order_status'); if ($transData->getInvoiceType() == 'OR') { // is process as invoice $invoice = array('number' => $transData->getInvoiceNumber(), 'bank_holder' => $transData->getInvoiceBankHolder(), 'bank_account_number' => $transData->getInvoiceBankAccountNumber(), 'bank_code' => $transData->getInvoiceBankCode(), 'bank_name' => $transData->getInvoiceBankName(), 'reason' => $transData->getInvoiceReason(1) . ' ' . $transData->getInvoiceReason(2), 'date' => $transData->getInvoiceDate(), 'due_date' => $transData->getInvoiceDueDate(), 'debitor_text' => $transData->getInvoiceDebitorText()); } else { // is process as lastschrift, fill with empty data $invoice = array('number' => $transData->getInvoiceNumber(), 'bank_holder' => '', 'bank_account_number' => '', 'bank_code' => '', 'bank_name' => '', 'reason' => '', 'date' => '', 'due_date' => '', 'debitor_text' => Mage::helper('pnsofortueberweisung')->__('your invoice amount will automatically be deducted from your your bank account.')); } $order->getPayment()->setAdditionalInformation("sofortrechnung_invoice_url", $transData->getInvoiceUrl()); $order->getPayment()->setAdditionalInformation('sofort_invoice', serialize($invoice)); // rechnung } elseif ($transData->isSofortrechnung()) { return; // lastschrift } elseif ($transData->isLastschrift()) { $newOrderStatus = Mage::getStoreConfig('payment/sofort/lastschriftsofort_order_status'); $notifyCustomer = true; // sofortueberweisung } else { $newOrderStatus = Mage::getStoreConfig('payment/sofort/pnsofort_order_status'); $notifyCustomer = true; } $payment->setStatus(Paymentnetwork_Pnsofortueberweisung_Model_Pnsofortueberweisung::STATUS_SUCCESS); $payment->setStatusDescription(Mage::helper('pnsofortueberweisung')->__('Payment was successful.', $transaction)); $order->setPayment($payment); if ($order->getPayment()->canCapture() && $order->canInvoice()) { $payment->setTransactionId($transaction)->setIsTransactionClosed(0)->registerCaptureNotification($amount); } elseif (method_exists($payment, 'addTransaction')) { //transaction overview in magento > 1.5 $payment->setTransactionId($transaction)->setIsTransactionClosed(0)->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE); } $order->setPayment($payment); // if status is already closed or completed dont change it if ($order->getStatus() == 'closed' || $order->getStatus() == 'complete') { $order->addStatusHistoryComment(Mage::helper('pnsofortueberweisung')->__('Payment was successful.', $transaction))->setIsCustomerNotified($notifyCustomer); $order->setIsVisibleOnFront(true); } else { if ($newOrderStatus == 'unchanged') { $order->addStatusHistoryComment(Mage::helper('pnsofortueberweisung')->__('Payment was successful.', $transaction))->setIsCustomerNotified($notifyCustomer); $order->setIsVisibleOnFront(true); } else { $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING); $order->addStatusHistoryComment(Mage::helper('pnsofortueberweisung')->__('Payment was successful.', $transaction), $newOrderStatus)->setIsCustomerNotified($notifyCustomer); $order->setIsVisibleOnFront(true); } } // FIX BUG to send multible mails to customer if ($notifyCustomer && !$order->getEmailSent()) { $order->setEmailSent(true); $order->save(); $order->sendNewOrderEmail(); } $order->save(); }
/** * Redirect and notify the customer of a successful or a fail * cancel order action. * * @param Mage_Sales_Model_Order * @param Mage_Core_Model_Session * @param string * @return self */ protected function _handleRomCancelResponse(Mage_Sales_Model_Order $order, Mage_Core_Model_Session $session, $redirectUrl) { $incrementId = $order->getIncrementId(); if ($order->getState() === Mage_Sales_Model_Order::STATE_CANCELED) { $session->addSuccess(sprintf($this->_orderHelper->__(static::CANCEL_SUCCESS_MESSAGE), $incrementId)); } else { $session->addError(sprintf($this->_orderHelper->__(static::CANCEL_FAIL_MESSAGE), $incrementId)); } $this->_redirectUrl($redirectUrl); return $this; }
/** * @param Mage_Sales_Model_Order $order * * @return string */ public function getOrderStatus($order) { $state = $order->getState(); $map = array('new' => 'Processing', 'pending_payment' => 'ProblemWithOrder', 'processing' => 'Processing', 'complete' => 'Delivered', 'closed' => 'Cancelled', 'cancelled' => 'Cancelled', 'holded' => 'ProblemWithOrder'); return 'http://schema.org/OrderStatus/' . $map[$state]; }
/** * Capture order's payment using AIM. * * @param Mage_Sales_Model_Order $order */ protected function _captureOrder(Mage_Sales_Model_Order $order) { $payment = $order->getPayment(); if ($payment->getAdditionalInformation('payment_type') == self::ACTION_AUTHORIZE_CAPTURE) { try { $payment->setTransactionId(null)->setParentTransactionId($this->getResponse()->getXTransId())->capture(null); // set status from config for AUTH_AND_CAPTURE orders. if ($order->getState() == Mage_Sales_Model_Order::STATE_PROCESSING) { $orderStatus = $this->getConfigData('order_status'); if (!$orderStatus || $order->getIsVirtual()) { $orderStatus = $order->getConfig()->getStateDefaultStatus(Mage_Sales_Model_Order::STATE_PROCESSING); } if ($orderStatus) { $order->setStatus($orderStatus); } } $order->save(); } catch (Exception $e) { Mage::logException($e); //if we couldn't capture order, just leave it as NEW order. } } }
/** * @param Mage_Sales_Model_Order $order * * @return bool */ public function isOrderComplete(Mage_Sales_Model_Order $order) { return $order->getState() === Mage_Sales_Model_Order::STATE_COMPLETE; }