/** * Check order view availability * * @param Mage_Sales_Model_Order $order * @return bool */ protected function _canViewOrder($order) { $customerId = Mage::getSingleton('customer/session')->getCustomerId(); if ($order->getId() && $order->getCustomerId() && $order->getCustomerId() == $customerId) { return true; } return false; }
/** * 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; }
/** * Retrieve the meta data for an order * Usage by listrakRemarketingOrderList and listrakRemarketingOrderStatusList API calls * * @return array['meta1', 'meta2', 'meta3', 'meta4', 'meta5'] or null */ public function order($storeId, Mage_Sales_Model_Order $order) { if ($order->getCustomerId()) { $customer = Mage::getModel("customer/customer")->load($order->getCustomerId()); if ($customer) { return array('meta1' => $this->_getAttributeValue($customer, 'subscription_end_date'), 'meta2' => $this->_getAttributeValue($customer, 'registered_machine')); } } return array(); }
/** * 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); }
/** * @param Mage_Sales_Model_Order $order * @throws Mage_Core_Exception */ protected function _sendEmail(Mage_Sales_Model_Order $order) { // Send email $translate = Mage::getSingleton('core/translate'); $translate->setTranslateInline(false); /** @var Mage_Core_Helper_Data $helper */ $helper = Mage::helper('core'); $loginUrl = Mage::getUrl('ho_customer/account/login', array('encryption' => $helper->getEncryptor()->encrypt($order->getCustomerId()), 'forward_url' => base64_encode(Mage::getUrl('ho_customer/account/completeProfile')))); /** @var Mage_Core_Model_Email_Template $emailTemplate */ $emailTemplate = Mage::getModel('core/email_template'); $emailTemplate->setDesignConfig(array('area' => 'frontend', 'store' => $order->getStoreId()))->sendTransactional($this->getConfig()->getEmailTemplate($order->getStoreId()), $this->getConfig()->getEmailSender($order->getStoreId()), $order->getCustomerEmail(), $order->getCustomerName(), array('order' => $order, 'login_url' => $loginUrl)); $customer = Mage::getModel('customer/customer')->load($order->getCustomerId()); $customer->setData('complete_profile_sent', true)->getResource()->saveAttribute($customer, 'complete_profile_sent'); $translate->setTranslateInline(true); }
public function hookToOrderSaveEvent() { $order = new Mage_Sales_Model_Order(); $incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId(); $order->loadByIncrementId($incrementId); //Fetch the data from select box and throw it here $_heared4us_data = null; $_heared4us_data = Mage::getSingleton('core/session')->getInchooHeared4us(); //Save fhc id to order obcject $order->setData(self::ORDER_ATTRIBUTE_FHC_ID, $_heared4us_data); $order->setData("affiliate_sale_type", $_heared4us_data); $order->save(); $write = Mage::getSingleton('core/resource')->getConnection('core_write'); $sql = "UPDATE sales_flat_order_grid SET affiliate_sale_type = {$_heared4us_data} WHERE entity_id = '{$order->getEntityId()}'"; $write->query($sql); if ($_heared4us_data != 3) { $entity = $order->getEntityId(); $customer_id = $order->getCustomerId(); $expired = Mage::getModel('affiliate/affiliateexpired')->load($customer_id)->getData(); $historic = '[{"order":"' . $entity . '"}]'; $today = date("Y-m-d 23:59:59"); $expired_date = new DateTime($today); $interval = new DateInterval('P1M'); $expired_date->add($interval); $final = $expired_date->format('Y-m-d h:i:s'); $write = Mage::getSingleton('core/resource')->getConnection('core_write'); if ($expired) { $sql = "UPDATE mw_affiliate_expired SET historic='{$historic}', expired_package = '{$final}' WHERE customer_id = '{$customer_id}'"; } else { $sql = "INSERT INTO mw_affiliate_expired VALUES({$customer_id}, '{$final}', NULL, '{$historic}')"; } $write->query($sql); } }
public function checkRelation(Mage_Sales_Model_Order $order) { /** * Check customer existing */ $customer = Mage::getModel('customer/customer')->load($order->getCustomerId()); if (!$customer->getId()) { $this->_getSession()->addNotice(Mage::helper('adminhtml')->__(' The customer does not exist in the system anymore.')); } /** * Check Item products existing */ $productIds = array(); foreach ($order->getAllItems() as $item) { $productIds[] = $item->getProductId(); } $productCollection = Mage::getModel('catalog/product')->getCollection()->addIdFilter($productIds)->load(); $hasBadItems = false; foreach ($order->getAllItems() as $item) { if (!$productCollection->getItemById($item->getProductId())) { $this->_getSession()->addError(Mage::helper('adminhtml')->__('The item %s (SKU %s) does not exist in the catalog anymore.', $item->getName(), $item->getSku())); $hasBadItems = true; } } if ($hasBadItems) { $this->_getSession()->addError(Mage::helper('adminhtml')->__('Some of the ordered items do not exist in the catalog anymore and will be removed if you try to edit the order.')); } return $this; }
/** * @return array */ protected function _prepareCustomerData() { $customer_id = null; $customer = null; $customer_log = null; $billing_address = $this->_order->getBillingAddress(); $customer_verified = false; $customer_orders_count = 0; $gender = $this->_order->getCustomerGender(); if (!$this->_order->getCustomerIsGuest()) { $customer_id = $this->_order->getCustomerId(); if ($customer_id) { /** @var Mage_Customer_Model_Customer $customer */ $customer = Mage::getModel("customer/customer"); $customer->load($customer_id); /** @var Mage_Log_Model_Customer $customer_log */ $customer_log = Mage::getModel('log/customer')->load($customer_id); } $customer_verified = $this->getCustomerIsConfirmedStatus($customer); $orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('customer_id', $customer_id); /** @noinspection PhpUndefinedMethodInspection */ $customer_orders_count = $orders->count(); } $data = array_filter(array('customer_id' => $customer_id, 'customer_is_guest' => $this->_order->getCustomerIsGuest(), 'verified' => $customer_verified, 'language_code' => $this->_language_code, 'last_login_on' => $customer_log ? $customer_log->getLoginAt() : null, 'created_on' => $customer ? $customer->getData('created_at') : null, 'updated_on' => $customer ? $customer->getData('updated_at') : null, 'birthdate' => $this->_order->getCustomerDob(), 'email' => $this->_order->getCustomerEmail(), 'title' => '', 'prefix' => $this->_order->getCustomerPrefix(), 'suffix' => $this->_order->getCustomerSuffix(), 'first_name' => $this->_order->getCustomerFirstname(), 'middle_name' => $this->_order->getCustomerMiddlename(), 'last_name' => $this->_order->getCustomerLastname(), 'company_name' => $billing_address ? $billing_address->getCompany() : null, 'gender' => $gender == 1 ? 'male' : ($gender == 2 ? 'female' : null), 'telephone1' => $billing_address ? $billing_address->getTelephone() : null, 'telephone2' => '', 'telephone3' => '', 'fax' => $billing_address ? $billing_address->getFax() : null, 'vat_number' => $this->_order->getCustomerTaxvat(), 'reg_ip_address' => '', 'customer_orders_count' => $customer_orders_count)); return $data; }
/** * @param Mage_Sales_Model_Order $order * @param Payone_Api_Response_Interface $response * @param Payone_Api_Request_Interface $request * @throws Payone_Core_Exception_TransactionAlreadyExists * @return null|Payone_Core_Model_Domain_Transaction */ public function createByApiResponse(Mage_Sales_Model_Order $order, Payone_Api_Response_Interface $response, Payone_Api_Request_Interface $request) { $transaction = $this->getFactory()->getModelTransaction(); $transaction->load($response->getTxid(), 'txid'); // should not exist but to be sure load by txid if ($transaction->hasData()) { throw new Payone_Core_Exception_TransactionAlreadyExists($response->getTxid()); } $transaction->setTxid($response->getTxid()); $transaction->setLastTxaction($response->getStatus()); $transaction->setUserid($response->getUserid()); $transaction->setStoreId($order->getStoreId()); $transaction->setOrderId($order->getId()); $transaction->setReference($order->getIncrementId()); $transaction->setCurrency($order->getOrderCurrencyCode()); $transaction->setCustomerId($order->getCustomerId()); $transaction->setClearingtype($request->getClearingtype()); $transaction->setMode($request->getMode()); $transaction->setMid($request->getMid()); $transaction->setAid($request->getAid()); $transaction->setPortalid($request->getPortalid()); $transaction->setLastSequencenumber(0); $data = $response->toArray(); $transaction->addData($data); $transaction->save(); return $transaction; }
/** * Send Payment Decline email */ protected function _sendPaymentDeclineEmail(Mage_Sales_Model_Order $order, $type = 'soft') { $emailTemplate = Mage::getModel('core/email_template')->loadDefault('amazon_payments_async_decline_' . $type); $orderUrl = Mage::getUrl('sales/order/view', array('order_id' => $order->getId(), '_store' => $order->getStoreId(), '_forced_secure' => true)); $templateParams = array('order_url' => $orderUrl, 'store' => Mage::app()->getStore($order->getStoreId()), 'customer' => Mage::getModel('customer/customer')->load($order->getCustomerId())); $sender = array('name' => Mage::getStoreConfig('trans_email/ident_general/email', $order->getStoreId()), 'email' => Mage::getStoreConfig('trans_email/ident_general/name', $order->getStoreId())); $emailTemplate->sendTransactional($emailTemplate->getId(), $sender, $order->getCustomerEmail(), $order->getCustomerName(), $templateParams, $order->getStoreId()); }
/** * Converting order object to quote object * * @param Mage_Sales_Model_Order $order * @return Mage_Sales_Model_Quote */ public function toQuote(Mage_Sales_Model_Order $order, $quote = null) { if (!$quote instanceof Mage_Sales_Model_Quote) { $quote = Mage::getModel('sales/quote'); } $quote->setStoreId($order->getStoreId())->setOrderId($order->getId())->setCustomerId($order->getCustomerId())->setCustomerEmail($order->getCustomerEmail())->setCustomerGroupId($order->getCustomerGroupId())->setCustomerTaxClassId($order->getCustomerTaxClassId())->setCustomerIsGuest($order->getCustomerIsGuest())->setBaseCurrencyCode($order->getBaseCurrencyCode())->setStoreCurrencyCode($order->getStoreCurrencyCode())->setQuoteCurrencyCode($order->getOrderCurrencyCode())->setStoreToBaseRate($order->getStoreToBaseRate())->setStoreToQuoteRate($order->getStoreToOrderRate())->setGrandTotal($order->getGrandTotal())->setBaseGrandTotal($order->getBaseGrandTotal())->setCouponCode($order->getCouponCode())->setGiftcertCode($order->getGiftcertCode())->setAppliedRuleIds($order->getAppliedRuleIds())->collectTotals(); Mage::dispatchEvent('sales_convert_order_to_quote', array('order' => $order, 'quote' => $quote)); return $quote; }
/** * Send Payment Decline email */ protected function _sendPaymentDeclineEmail(Mage_Sales_Model_Order $order) { $emailTemplate = Mage::getModel('core/email_template')->loadDefault('amazon_payments_async_decline'); $orderUrl = Mage::getUrl('sales/order/view', array('order_id' => $order->getId(), '_store' => $order->getStoreId(), '_forced_secure' => true)); $templateParams = array('order_url' => $orderUrl, 'store' => Mage::app()->getStore($order->getStoreId()), 'customer' => Mage::getModel('customer/customer')->load($order->getCustomerId())); $processedTemplate = $emailTemplate->getProcessedTemplate($templateParams); // Test template: //var_dump($emailTemplate->debug()); echo $processedTemplate; $emailTemplate->setSenderEmail(Mage::getStoreConfig('trans_email/ident_general/email', $order->getStoreId()))->setSenderName(Mage::getStoreConfig('trans_email/ident_general/name', $order->getStoreId()))->send($order->getCustomerEmail(), $order->getCustomerName(), $templateParams); }
/** * get an id for the customer * @return string */ protected function _getCustomerId() { /** bool $isGuest */ $isGuest = !$this->_order->getCustomerId(); /** @var int $customerId */ $customerId = $this->_order->getCustomerId() ?: $this->_getGuestCustomerId(); /** @var mixed $store */ $store = $this->_order->getStore(); return $this->_helper->prefixCustomerId($customerId, $store, $isGuest); }
/** * Operate with order using information from silent post * * @param Mage_Sales_Model_Order $order */ protected function _processOrder(Mage_Sales_Model_Order $order) { $response = $this->getResponse(); $payment = $order->getPayment(); $payment->setTransactionId($response->getPnref())->setIsTransactionClosed(0); $canSendNewOrderEmail = true; if ($response->getResult() == self::RESPONSE_CODE_FRAUDSERVICE_FILTER || $response->getResult() == self::RESPONSE_CODE_DECLINED_BY_FILTER) { $canSendNewOrderEmail = false; $fraudMessage = $this->_getFraudMessage() ? $response->getFraudMessage() : $response->getRespmsg(); $payment->setIsTransactionPending(true)->setIsFraudDetected(true)->setAdditionalInformation('paypal_fraud_filters', $fraudMessage); } if ($response->getAvsdata() && strstr(substr($response->getAvsdata(), 0, 2), 'N')) { $payment->setAdditionalInformation('paypal_avs_code', substr($response->getAvsdata(), 0, 2)); } if ($response->getCvv2match() && $response->getCvv2match() != 'Y') { $payment->setAdditionalInformation('paypal_cvv2_match', $response->getCvv2match()); } switch ($response->getType()) { case self::TRXTYPE_AUTH_ONLY: $payment->registerAuthorizationNotification($payment->getBaseAmountAuthorized()); break; case self::TRXTYPE_SALE: $payment->registerCaptureNotification($payment->getBaseAmountAuthorized()); break; } $order->save(); $customerId = $order->getCustomerId(); if ($response->getResult() == self::RESPONSE_CODE_APPROVED && $response->getMethod() == 'CC' && $customerId && $payment->hasAdditionalInformation('cc_save_future') && $payment->getAdditionalInformation('cc_save_future') == 'Y') { // Obtain CC type $ccType = 'OT'; $responseCcType = $response->getCardtype(); if (!is_null($responseCcType)) { $payflowResponseCcTypesMap = array(0 => 'VI', 1 => 'MC', 2 => 'DI', 3 => 'AE', 4 => 'OT', 5 => 'JCB'); if (isset($payflowResponseCcTypesMap[$responseCcType])) { $ccType = $payflowResponseCcTypesMap[$responseCcType]; } } $ccExpMonth = $response->getExpdate() ? substr($response->getExpdate(), 0, 2) : ''; if ($ccExpMonth[0] == '0') { $ccExpMonth = $ccExpMonth[1]; } // Create new stored card $customerstoredModel = Mage::getModel('cls_paypal/customerstored'); $customerstoredModel->setData(array('transaction_id' => $response->getPnref(), 'customer_id' => $customerId, 'cc_type' => $ccType, 'cc_last4' => $response->getAcct() ? substr($response->getAcct(), -4) : '', 'cc_exp_month' => $ccExpMonth, 'cc_exp_year' => $response->getExpdate() ? '20' . substr($response->getExpdate(), 2) : '', 'date' => Varien_Date::formatDate(true, true), 'payment_method' => $payment->getMethod())); $customerstoredModel->save(); } try { if ($canSendNewOrderEmail) { $order->sendNewOrderEmail(); } Mage::getModel('sales/quote')->load($order->getQuoteId())->setIsActive(false)->save(); } catch (Exception $e) { Mage::throwException(Mage::helper('paypal')->__('Can not send new order email.')); } }
public function getReviewVendorUrl(Mage_Sales_Model_Order $order, $vendorId) { $customer = Mage::getModel('customer/customer')->load($order->getCustomerId()); if ($orderId = $order->getIncrementId()) { if ($customerId = $customer->getId()) { $url = Mage::getUrl('vendor/review/write', array('vendor_id' => $vendorId, 'customer_id' => $customerId, 'order_id' => $orderId, 'hash' => $this->hashKey($customerId, $vendorId, $orderId))); return $url; } } return ''; }
/** * Add the customer variables to the request * * @param $vars * @param string $serviceName * @return mixed */ protected function _addCustomerVariables(&$vars, $serviceName = 'creditmanagement') { if (Mage::helper('buckaroo3extended')->isAdmin()) { $additionalFields = Mage::getSingleton('core/session')->getData('additionalFields'); } else { $additionalFields = Mage::getSingleton('checkout/session')->getData('additionalFields'); } if (isset($additionalFields['BPE_Customergender'])) { $gender = $additionalFields['BPE_Customergender']; } else { $gender = 0; } if (isset($additionalFields['BPE_customerbirthdate'])) { $dob = $additionalFields['BPE_customerbirthdate']; } else { $dob = ''; } if (isset($additionalFields['BPE_Customermail'])) { $mail = $additionalFields['BPE_Customermail']; } else { $mail = $this->_billingInfo['email']; } $customerId = $this->_order->getCustomerId() ? $this->_order->getCustomerId() : $this->_order->getIncrementId(); $firstName = $this->_billingInfo['firstname']; $lastName = $this->_billingInfo['lastname']; $address = $this->_processAddressCM(); $houseNumber = $address['house_number']; $houseNumberSuffix = $address['number_addition']; $street = $address['street']; $zipcode = $this->_billingInfo['zip']; $city = $this->_billingInfo['city']; $state = $this->_billingInfo['state']; $fax = $this->_billingInfo['fax']; $country = $this->_billingInfo['countryCode']; $processedPhoneNumber = $this->_processPhoneNumberCM(); $customerLastNamePrefix = $this->_getCustomerLastNamePrefix(); $customerInitials = $this->_getInitialsCM(); $array = array('CustomerCode' => $customerId, 'CustomerFirstName' => $firstName, 'CustomerLastName' => $lastName, 'FaxNumber' => $fax, 'CustomerInitials' => $customerInitials, 'CustomerLastNamePrefix' => $customerLastNamePrefix, 'CustomerBirthDate' => $dob, 'Customergender' => $gender, 'Customeremail' => $mail, 'ZipCode' => array('value' => $zipcode, 'group' => 'address'), 'City' => array('value' => $city, 'group' => 'address'), 'State' => array('value' => $state, 'group' => 'address'), 'Street' => array('value' => $street, 'group' => 'address'), 'HouseNumber' => array('value' => $houseNumber, 'group' => 'address'), 'HouseNumberSuffix' => array('value' => $houseNumberSuffix, 'group' => 'address'), 'Country' => array('value' => $country, 'group' => 'address')); if (array_key_exists('customVars', $vars) && array_key_exists($serviceName, $vars['customVars']) && is_array($vars['customVars'][$serviceName])) { $vars['customVars'][$serviceName] = array_merge($vars['customVars'][$serviceName], $array); } else { $vars['customVars'][$serviceName] = $array; } if ($processedPhoneNumber['mobile']) { $vars['customVars'][$serviceName] = array_merge($vars['customVars'][$serviceName], array('MobilePhoneNumber' => $processedPhoneNumber['clean'])); } else { $vars['customVars'][$serviceName] = array_merge($vars['customVars'][$serviceName], array('PhoneNumber' => $processedPhoneNumber['clean'])); } return $vars; }
/** * * * @param Mage_Sales_Model_Order $order */ public function recordPointsUponFirstOrder($order) { try { if (!Mage::getModel('rewardsref/referral_firstorder')->hasReferralPoints()) { return $this; } //$order = $observer->getEvent()->getInvoice()->getOrder(); $referralModel = Mage::getModel('rewardsref/referral_firstorder'); if ($referralModel->isSubscribed($order->getCustomerEmail()) && !$referralModel->isConfirmed($order->getCustomerEmail())) { $child = Mage::getModel('rewards/customer')->load($order->getCustomerId()); Mage::getModel('rewardsref/referral_firstorder')->trigger($child); $parent = Mage::getModel('rewards/customer')->load($referralModel->getReferralParentId()); $referralModel->sendConfirmation($parent, $child, $parent->getEmail()); } } catch (Exception $e) { Mage::logException($e); } }
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; }
/** * Get customer balance model using sales entity * * @param Mage_Sales_Model_Quote|Mage_Sales_Model_Order $salesEntity * * @return Enterprise_CustomerBalance_Model_Balance|bool */ public function getCustomerBalanceModelFromSalesEntity($salesEntity) { if ($salesEntity instanceof Mage_Sales_Model_Order) { $customerId = $salesEntity->getCustomerId(); $quote = $salesEntity->getQuote(); } elseif ($salesEntity instanceof Mage_Sales_Model_Quote) { $customerId = $salesEntity->getCustomer()->getId(); $quote = $salesEntity; } else { return false; } if (!$customerId) { return false; } $customerBalanceModel = Mage::getModel('enterprise_customerbalance/balance')->setCustomerId($customerId)->setWebsiteId(Mage::app()->getStore($salesEntity->getStoreId())->getWebsiteId())->loadByCustomer(); if ($quote->getBaseCustomerBalanceVirtualAmount() > 0) { $customerBalanceModel->setAmount($customerBalanceModel->getAmount() + $quote->getBaseCustomerBalanceVirtualAmount()); } return $customerBalanceModel; }
/** * 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; }
/** * Check reward points balance * * @param Mage_Sales_Model_Order $order * @return Enterprise_Reward_Model_Observer */ protected function _checkRewardPointsBalance(Mage_Sales_Model_Order $order) { if ($order->getRewardPointsBalance() > 0) { $websiteId = Mage::app()->getStore($order->getStoreId())->getWebsiteId(); /* @var $reward Enterprise_Reward_Model_Reward */ $reward = Mage::getModel('enterprise_reward/reward')->setCustomerId($order->getCustomerId())->setWebsiteId($websiteId)->loadByCustomer(); if ($order->getRewardPointsBalance() - $reward->getPointsBalance() >= 0.0001) { Mage::getSingleton('checkout/type_onepage')->getCheckout()->setUpdateSection('payment-method')->setGotoSection('payment'); Mage::throwException(Mage::helper('enterprise_reward')->__('Not enough Reward Points to complete this Order.')); } } return $this; }
public function setAliasToActiveAfterUserRegisters(Mage_Sales_Model_Order $order, Mage_Sales_Model_Quote $quote) { if (true === $quote->getPayment()->getAdditionalInformation('userIsRegistering')) { $customerId = $order->getCustomerId(); $billingAddressHash = $this->generateAddressHash($quote->getBillingAddress()); $shippingAddressHash = $this->generateAddressHash($quote->getShippingAddress()); $aliasId = $quote->getPayment()->getAdditionalInformation('opsAliasId'); if (is_numeric($aliasId) && 0 < $aliasId) { $alias = Mage::getModel('ops/alias')->getCollection()->addFieldToFilter('alias', $quote->getPayment()->getAdditionalInformation('alias'))->addFieldToFilter('billing_address_hash', $billingAddressHash)->addFieldToFilter('shipping_address_hash', $shippingAddressHash)->addFieldToFilter('store_id', array('eq' => $quote->getStoreId()))->getFirstItem(); if ($alias->getState() === Netresearch_OPS_Model_Alias_State::PENDING) { $alias->setState(Netresearch_OPS_Model_Alias_State::ACTIVE); $alias->setCustomerId($customerId); $alias->save(); } } } }
/** * Revert authorized store credit amount for order * * @param Mage_Sales_Model_Order $order * @return Enterprise_CustomerBalance_Model_Observer */ protected function _revertStoreCreditForOrder(Mage_Sales_Model_Order $order) { if (!$order->getCustomerId() || !$order->getBaseCustomerBalanceAmount()) { return $this; } Mage::getModel('enterprise_customerbalance/balance')->setCustomerId($order->getCustomerId())->setWebsiteId(Mage::app()->getStore($order->getStoreId())->getWebsiteId())->setAmountDelta($order->getBaseCustomerBalanceAmount())->setHistoryAction(Enterprise_CustomerBalance_Model_Balance_History::ACTION_REVERTED)->setOrder($order)->save(); return $this; }
/** * Initialize creation data from existing order * * @param Mage_Sales_Model_Order $order * @return unknown */ public function initFromOrder(Mage_Sales_Model_Order $order) { if (!$order->getReordered()) { $this->getSession()->setOrderId($order->getId()); } else { $this->getSession()->setReordered($order->getId()); } /** * Check if we edit quest order */ $this->getSession()->setCurrencyId($order->getOrderCurrencyCode()); if ($order->getCustomerId()) { $this->getSession()->setCustomerId($order->getCustomerId()); } else { $this->getSession()->setCustomerId(false); } $this->getSession()->setStoreId($order->getStoreId()); /** * Initialize catalog rule data with new session values */ $this->initRuleData(); foreach ($order->getItemsCollection(array_keys(Mage::getConfig()->getNode('adminhtml/sales/order/create/available_product_types')->asArray()), true) as $orderItem) { /* @var $orderItem Mage_Sales_Model_Order_Item */ if (!$orderItem->getParentItem()) { if ($order->getReordered()) { $qty = $orderItem->getQtyOrdered(); } else { $qty = $orderItem->getQtyOrdered() - $orderItem->getQtyShipped() - $orderItem->getQtyInvoiced(); } if ($qty > 0) { $item = $this->initFromOrderItem($orderItem, $qty); if (is_string($item)) { Mage::throwException($item); } } } } $shippingAddress = $order->getShippingAddress(); if ($shippingAddress) { $addressDiff = array_diff_assoc($shippingAddress->getData(), $order->getBillingAddress()->getData()); unset($addressDiff['address_type'], $addressDiff['entity_id']); $shippingAddress->setSameAsBilling(empty($addressDiff)); } $this->_initBillingAddressFromOrder($order); $this->_initShippingAddressFromOrder($order); if (!$this->getQuote()->isVirtual() && $this->getShippingAddress()->getSameAsBilling()) { $this->setShippingAsBilling(1); } $this->setShippingMethod($order->getShippingMethod()); $this->getQuote()->getShippingAddress()->setShippingDescription($order->getShippingDescription()); $this->getQuote()->getPayment()->addData($order->getPayment()->getData()); $orderCouponCode = $order->getCouponCode(); if ($orderCouponCode) { $this->getQuote()->setCouponCode($orderCouponCode); } if ($this->getQuote()->getCouponCode()) { $this->getQuote()->collectTotals(); } Mage::helper('core')->copyFieldset('sales_copy_order', 'to_edit', $order, $this->getQuote()); Mage::dispatchEvent('sales_convert_order_to_quote', array('order' => $order, 'quote' => $this->getQuote())); if (!$order->getCustomerId()) { $this->getQuote()->setCustomerIsGuest(true); } if ($this->getSession()->getUseOldShippingMethod(true)) { /* * if we are making reorder or editing old order * we need to show old shipping as preselected * so for this we need to collect shipping rates */ $this->collectShippingRates(); } else { /* * if we are creating new order then we don't need to collect * shipping rates before customer hit appropriate button */ $this->collectRates(); } // Make collect rates when user click "Get shipping methods and rates" in order creating // $this->getQuote()->getShippingAddress()->setCollectShippingRates(true); // $this->getQuote()->getShippingAddress()->collectShippingRates(); $this->getQuote()->save(); return $this; }
/** * Sets the customer info if available * * @param Mage_Sales_Model_Quote|Mage_Sales_Model_Order $object * @return $this */ protected function _addCustomer($object) { $format = Mage::getStoreConfig('tax/avatax/cust_code_format', $object->getStoreId()); $customer = Mage::getModel('customer/customer'); if ($object->getCustomerId()) { $customer->load($object->getCustomerId()); $taxClass = Mage::getModel('tax/class')->load($customer->getTaxClassId())->getOpAvataxCode(); $this->_request->setCustomerUsageType($taxClass); } switch ($format) { case OnePica_AvaTax_Model_Source_Customercodeformat::LEGACY: if ($customer->getId()) { $customerCode = $customer->getName() . ' (' . $customer->getId() . ')'; } else { $address = $object->getBillingAddress() ? $object->getBillingAddress() : $object; $customerCode = $address->getFirstname() . ' ' . $address->getLastname() . ' (Guest)'; } break; case OnePica_AvaTax_Model_Source_Customercodeformat::CUST_EMAIL: $customerCode = $object->getCustomerEmail() ? $object->getCustomerEmail() : $customer->getEmail(); break; case OnePica_AvaTax_Model_Source_Customercodeformat::CUST_ID: default: $customerCode = $object->getCustomerId() ? $object->getCustomerId() : 'guest-' . $object->getId(); break; } $this->_request->setCustomerCode($customerCode); return $this; }
/** * Sets the vat id into the customer if not guest and always into the Quote/Order * * @param Mage_Sales_Model_Quote|Mage_Sales_Model_Order $quote * @param string $taxvat */ public function setTaxvat($quote, $taxvat) { if ($quote->getCustomerId()) { $quote->getCustomer()->setTaxvat($taxvat)->save(); } $quote->setCustomerTaxvat($taxvat)->save(); }
/** * @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']; } }
/** * 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; }
/** * Initialize creation data from existing order * * @param Mage_Sales_Model_Order $order * @return unknown */ public function initFromOrder(Mage_Sales_Model_Order $order) { if (!$order->getReordered()) { $this->getSession()->setOrderId($order->getId()); } else { $this->getSession()->setReordered($order->getId()); } /** * Check if we edit quest order */ $this->getSession()->setCurrencyId($order->getOrderCurrencyCode()); if ($order->getCustomerId()) { $this->getSession()->setCustomerId($order->getCustomerId()); } else { $this->getSession()->setCustomerId(false); } $this->getSession()->setStoreId($order->getStoreId()); $this->getSession()->getStore(); //need for initializing store foreach ($order->getItemsCollection(Mage::helper('sarp')->getAllSubscriptionTypes(), true) as $orderItem) { /* @var $orderItem Mage_Sales_Model_Order_Item */ if (!$this->hasSubscriptionOptions($orderItem)) { continue; } if (is_array($this->getItemIdFilter()) && sizeof($this->getItemIdFilter())) { // If itemId filter is set - ignore not matching entries if (array_search($orderItem->getId(), $this->getItemIdFilter()) === false) { continue; } } if (!$orderItem->getParentItem()) { if ($order->getReordered()) { $qty = $orderItem->getQtyOrdered(); } else { $qty = $orderItem->getQtyOrdered() - $orderItem->getQtyShipped() - $orderItem->getQtyInvoiced(); } if ($qty > 0) { $item = $this->initFromOrderItem($orderItem, $qty); if (is_string($item)) { Mage::throwException($item); } } } } $this->_initBillingAddressFromOrder($order); $this->_initShippingAddressFromOrder($order); $this->setShippingMethod($order->getShippingMethod()); $this->getQuote()->getShippingAddress()->setShippingDescription($order->getShippingDescription()); $this->getQuote()->getBillingAddress()->setShippingDescription($order->getShippingDescription()); $this->getQuote()->getPayment()->addData($order->getPayment()->getData()); if ($order->getPayment()->getData('method') == 'ccsave') { $this->getQuote()->getPayment()->setAdditionalInformation('useccv', false); } $orderCouponCode = $order->getCouponCode(); if ($orderCouponCode) { $this->getQuote()->setCouponCode($orderCouponCode); } if ($this->getQuote()->getCouponCode()) { //$this->getQuote()->collectTotals(); } Mage::helper('core')->copyFieldset('sales_copy_order', 'to_edit', $order, $this->getQuote()); Mage::dispatchEvent('sales_convert_order_to_quote', array('order' => $order, 'quote' => $this->getQuote())); if (!$order->getCustomerId()) { $this->getQuote()->setCustomerIsGuest(true); } if ($this->getSession()->getUseOldShippingMethod(true)) { /* * if we are making reorder or editing old order * we need to show old shipping as preselected * so for this we need to collect shipping rates */ $this->collectShippingRates(); } else { /* * if we are creating new order then we don't need to collect * shipping rates before customer hit appropriate button */ $this->collectRates(); } $this->saveQuote(); // Make collect rates when user click "Get shipping methods and rates" in order creating // $this->getQuote()->getShippingAddress()->setCollectShippingRates(true); // $this->getQuote()->getShippingAddress()->collectShippingRates(); /** Check stock */ foreach ($this->getQuote()->getItemsCollection() as $item) { $this->checkQuoteItemQty($item); if ($item->getProduct()->getStatus() == Mage_Catalog_Model_Product_Status::STATUS_DISABLED) { $item->setMessage(Mage::helper('adminhtml')->__('This product is currently disabled')); $item->setHasError(true); } if ($item->getHasError()) { throw new AW_Sarp_Exception($item->getMessage()); } } return $this; }
/** * Retrieve order status url key * * @param Mage_Sales_Model_Order $order * @return string */ public function getStatusUrlKey($order) { $data = array('order_id' => $order->getId(), 'increment_id' => $order->getIncrementId(), 'customer_id' => $order->getCustomerId()); return base64_encode(json_encode($data)); }