/** * Retourne vrai si un produit est dispo * */ public function isInStock($product) { try { //echo '<br>-->'.$product->getId().' stock='.$Stock.' ordered='.$OrderedQty; $Stock = $product->getStockItem()->getQty(); $OrderedQty = $product->getordered_qty(); if ($Stock - $OrderedQty > 0) { return true; } else { return false; } } catch (Exception $ex) { mage::log('Error inside isInStock method : ' . $ex->getMessage()); return false; } }
public function estorno($observer) { if (!is_object($observer->getEvent()->getCreditmemo()->getInvoice())) { //apresenta um erro caso a pessoa não escolha a fatura no admin Mage::throwException(Mage::helper('payment')->__('Não foi possivel identificar a fatura. É preciso escolher uma fatura para o estorno. ')); } $orderId = $observer->getEvent()->getCreditmemo()->getInvoice()->getOrderId(); $order = mage::getModel('sales/order')->load($orderId); $tid = $order->getPayment()->getCcTransId(); $payment = $order->getPayment(); if ($payment->getMethod() != 'apelidocielo') { return true; } $creditmemo = $observer->getEvent()->getCreditmemo(); $valor = number_format($creditmemo->getGrandTotal(), 2, '', ''); $debug = Mage::getStoreConfig('payment/apelidocielo/debug'); if ($debug) { //Esse log só funciona se a opção Ativar log em Developer > Log no admin estiver marcada mage::log("\r\n=========== Dados do credito sendo enviados para estorno ==========\r\n\r\n ", null, 'oitoo_cielo.log'); } $cielo = mage::getModel('apelidocielo/cielo'); $retornoestorno = $cielo->setCancelamento($tid, $valor); if ($retornoestorno->autorizacao->codigo == 9 || $retornoestorno->autorizacao->codigo == 6) { //quando o pagamento é capturado não é mais possivel editar as infromações //faz o log de sucesso Mage::dispatchEvent('oitoo_cielo_log', array('quote_id' => (string) $payment->getOrder()->getQuoteId(), 'codigo' => $retornoestorno->autorizacao->codigo, 'texto' => 'Pedido estornado com sucesso! ', 'tid' => $retornoestorno->tid)); return $this; //o crédito foi estornado. } else { if (isset($retornoestorno->codigo)) { Mage::throwException(Mage::helper('payment')->__('Erro num: ' . $retornoestorno->codigo . ' - ' . $retornoestorno->mensagem)); } else { Mage::throwException(Mage::helper('payment')->__('Não foi possivel efetuar o estorno')); } } return $this; }
public function addAction() { $response = array(); if (!Mage::getStoreConfigFlag('wishlist/general/active')) { $response['status'] = 'ERROR'; $response['message'] = $this->__('Wishlist Has Been Disabled By Admin'); } if (!Mage::getSingleton('customer/session')->isLoggedIn()) { $response['status'] = 'ERROR'; $response['message'] = $this->__('Please Login First'); } if (empty($response)) { $session = Mage::getSingleton('customer/session'); $wishlist = $this->_getWishlist(); if (!$wishlist) { $response['status'] = 'ERROR'; $response['message'] = $this->__('Unable to Create Wishlist'); } else { $productId = (int) $this->getRequest()->getParam('product'); if (!$productId) { $response['status'] = 'ERROR'; $response['message'] = $this->__('Product Not Found'); } else { $product = Mage::getModel('catalog/product')->load($productId); if (!$product->getId() || !$product->isVisibleInCatalog()) { $response['status'] = 'ERROR'; $response['message'] = $this->__('Cannot specify product.'); } else { try { $requestParams = $this->getRequest()->getParams(); $buyRequest = new Varien_Object($requestParams); $result = $wishlist->addNewItem($product, $buyRequest); if (is_string($result)) { Mage::throwException($result); } $wishlist->save(); Mage::dispatchEvent('wishlist_add_product', array('wishlist' => $wishlist, 'product' => $product, 'item' => $result)); Mage::helper('wishlist')->calculate(); $message = $this->__('%1$s has been added to your wishlist.', $product->getName()); $response['status'] = 'SUCCESS'; $response['message'] = $message; Mage::unregister('wishlist'); $this->loadLayout(); $response['toplink'] = $this->getLayout()->getBlock('top.links')->toHtml(); $response['sidebar'] = $this->getLayout()->getBlock('wishlist_sidebar')->toHtml(); } catch (Mage_Core_Exception $e) { $response['status'] = 'ERROR'; $response['message'] = $this->__('An error occurred while adding item to wishlist: %s', $e->getMessage()); } catch (Exception $e) { mage::log($e->getMessage()); $response['status'] = 'ERROR'; $response['message'] = $this->__('An error occurred while adding item to wishlist.'); } } } } } $this->_sendJson($response); return; }
/** * Function to update waybill if order tracking is of Delhivery Lastmile */ public function sales_shipment_add_tracking($observer) { $track = $observer->getEvent()->getTrack(); $order = $track->getShipment()->getOrder(); $shippingMethod = $order->getShippingMethod(); // String in format of 'carrier_method' if (!$shippingMethod) { return; } // Process only Delhivery Lastmile methods if ($track->getCarrierCode() != 'dlastmile') { return; } //mage::log($track->getNumber()); //mage::log($track->getCarrierCode()); $model = Mage::getModel('lastmile/lastmile'); $awbobj = $model->loadByAwb($track->getNumber()); $data = array(); $status = 'Assigned'; $data['state'] = 1; $data['status'] = "Assigned"; $data['orderid'] = $order->getId(); $data['shipment_to'] = $order->getShippingAddress()->getName(); $data['shipment_id'] = $track->getShipment()->getIncrementId(); mage::log($data); $model->setData($data); $model->setId($awbobj); $model->save(); return; }
/** * Check if we log changes for entity type * * @param unknown_type $objectType * @return unknown */ public function considerObjectType($objectType) { //register object types for optimization if (!Mage::registry('adminlogger_ignored_object_types')) { if (mage::getStoreConfig('adminlogger/general/enable_log') == 1) { mage::log('Load ignored object types in registry'); } $ignoredObjectTypes = mage::getStoreConfig('adminlogger/advanced/object_to_ignore'); $t_ignoredObjectTypes = explode("\n", $ignoredObjectTypes); for ($i = 0; $i < count($t_ignoredObjectTypes); $i++) { $t_ignoredObjectTypes[$i] = trim($t_ignoredObjectTypes[$i]); } Mage::register('adminlogger_ignored_object_types', $t_ignoredObjectTypes); } //check if object type is managed if (in_array($objectType, Mage::registry('adminlogger_ignored_object_types'))) { if (mage::getStoreConfig('adminlogger/general/enable_log') == 1) { mage::log('Object type ' . $objectType . ' ignored '); } return false; } else { if (mage::getStoreConfig('adminlogger/general/enable_log') == 1) { mage::log('Object type ' . $objectType . ' considered '); } return true; } }
/** * Surcharge la méthode after save pour mettre a jour les stocks * * @return Mage_Core_Model_Abstract */ protected function _afterSave() { try { //appel le parent parent::_afterSave(); //Define if shipment just created $creation = $this->getentity_id() != $this->getOrigData('entity_id'); if ($creation) { //Create stock movements $order = $this->getOrder(); foreach ($this->getAllItems() as $item) { //retrieve informaiton $qty = $this->getRealShippedQtyForItem($item); try { $StockMovement = mage::getmodel('Purchase/StockMovement')->setsm_product_id($item->getproduct_id())->setsm_type('order')->setsm_coef(-1)->setsm_qty($qty)->setsm_date(date('Y-m-d'))->setsm_ui($item->getId())->setsm_description(mage::helper('purchase')->__('Order #') . $this->getOrder()->getincrement_id())->save(); } catch (Exception $ex) { //nothing, db constraint exception because stock movement already exists } //reset reserved qty $orderItem = $item->getOrderItem(); $orderItem->setreserved_qty(0)->save(); } //update order planning $orderId = $this->getOrder()->getId(); mage::helper('BackgroundTask')->AddTask('Update planning for order ' . $orderId, 'purchase/Planning', 'updatePlanning', $orderId); //Met a jour les qte commandées pour le produit $order->UpdateProductsOrdererQty; } } catch (Exception $ex) { mage::log($ex->getMessage()); } return $this; }
public function render(Varien_Object $row) { mage::log($row->getUserId(), null, 'row.log'); /*$value = $row->getData($this->getColumn()->getIndex()); return '<span style="color:red;">'.$value.'</span>';*/ $customer = Mage::getModel('customer/customer')->load($row->getUserId()); return $customer->getName(); }
protected function _prepareCollection() { $collection = Mage::getResourceModel($this->_getCollectionClass()); //$collection->addAttributeToSelect(array('barcode')); $collection->addAttributeToSelect('*'); $this->setCollection($collection); mage::log(); return parent::_prepareCollection(); }
/** * Function to get waybills to be canceled if order is cancelled */ public function findAwbToCancel($OrderId) { $resource = Mage::getSingleton('core/resource'); $readConnection = $resource->getConnection('core_read'); $query = "SELECT lastmile_id FROM " . $resource->getTableName('lastmile/lastmile') . " WHERE orderid = {$OrderId} AND status = 'Assigned'"; mage::log("{$query}"); $data = $readConnection->fetchAll($query); return $data; }
/** * Function to get last updated date of pincode * * @return date in yyyy-mm-dd format */ public function getUpdatedate() { $resource = Mage::getSingleton('core/resource'); $readConnection = $resource->getConnection('core_read'); $query = "SELECT DATE_FORMAT(update_time,'%Y-%m-%d') FROM " . $resource->getTableName('lastmile/pincode') . " ORDER BY update_time DESC LIMIT 1"; mage::log("{$query}"); $data = $readConnection->fetchOne($query); return $data; }
protected function _prepareForm() { $form = new Varien_Data_Form(array("id" => "edit_form", "action" => $this->getUrl("*/*/save", array("id" => $this->getRequest()->getParam("id"))), "method" => "post", "enctype" => "multipart/form-data")); $registry = Mage::registry("otpconfiguration_data"); mage::log($registry, null, 'reg.log'); $registry->setData('user_id', 'hitesh'); $form->setValues($registry->getData()); $form->setUseContainer(true); $this->setForm($form); return parent::_prepareForm(); }
/** * Function to download Delhivery serviceable pincodes */ public function fetchAction() { $apiurl = Mage::getStoreConfig('carriers/dlastmile/pincode_url'); $token = Mage::getStoreConfig('carriers/dlastmile/licensekey'); if ($apiurl && $token) { //$path = $apiurl.'json/?pre-paid=Y&token='.$token; $path = $apiurl . 'json/?token=' . $token . '&pre-paid=Y'; $date = Mage::getModel('lastmile/pincode')->getUpdatedate(); //if($date) //$path .= "&dt=$date"; //mage::log($path); $retValue = Mage::helper('lastmile')->Executecurl($path, '', ''); $codes = json_decode($retValue); mage::log(sizeof($codes->delivery_codes)); //mage::log($codes); // Delete all zipcodes $delete = Mage::getModel('lastmile/pincode')->deleteAll(); if (sizeof($codes)) { foreach ($codes->delivery_codes as $item) { try { //$lastmilezip = Mage::getModel('lastmile/pincode')->loadByPin($item->postal_code->pin); $model = Mage::getModel('lastmile/pincode'); $data = array(); $data['district'] = $item->postal_code->district; $data['pin'] = $item->postal_code->pin; $data['pre_paid'] = $item->postal_code->pre_paid; $data['cash'] = $item->postal_code->cash; $data['pickup'] = $item->postal_code->pickup; $data['cod'] = $item->postal_code->cod; $data['is_oda'] = $item->postal_code->is_oda; $data['state_code'] = $item->postal_code->state_code; $model->setData($data); mage::log($data); if ($lastmilezip) { $model->setId($lastmilezip->getId()); } if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) { $model->setCreatedTime(now())->setUpdateTime(now()); } else { $model->setUpdateTime(now()); } $model->save(); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } } } Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('lastmile')->__('Pincode Updated Successfully')); } else { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('lastmile')->__('Please add valid License Key and Gateway URL in plugin configuration')); } $this->_redirect('*/*/'); }
/** * reserve product for orders * * @param unknown_type $productId */ public function reserveProductForOrders($productId) { //define if we must reserve product for orders (positive stock movement) or release(negative stock movement) $product = mage::getModel('catalog/product')->load($productId); $reservedQty = $product->getreserved_qty(); $stock = $product->getStockItem()->getQty(); //if stock allow to reserve products in other orders if ($stock > $reservedQty) { //collect orders with no reservation $orders = $product->GetPendingOrders(false); foreach ($orders as $order) { $this->reserveProductForOrder($order->getId(), $product->getId()); } } else { //collect all pending orders (sort by date) and unreserve products mage::log('Product #' . $productId . ' stock is <= reserved qty : no reservation possible'); } }
/** * Update planning (method to use when information for the order changes (product reservation, payment, expedition ...) * * @param unknown_type $orderId */ public function updatePlanning($orderId) { mage::log('##Start update planning for order #' . $orderId); $order = mage::getModel('sales/order')->load($orderId); if ($order->getId()) { $planning = $order->getPlanning(); if ($planning->getConsiderationDate() == null) { mage::log('Set condideration date'); $planning->setConsiderationInformation($order); } $planning->setFullStockInformation($order); $planning->setShippingInformation($order); $planning->setDeliveryInformation($order); $planning->save(); } else { mage::log('Unable to load order #' . $orderId); } mage::log('##End update planning for order #' . $orderId); }
protected function _prepareForm() { $form = new Varien_Data_Form(); $this->setForm($form); $fieldset = $form->addFieldset("otpconfiguration2_form", array("legend" => Mage::helper("otpconfiguration2")->__("Item information"))); $fieldset->addField("otp_id", "text", array("label" => Mage::helper("otpconfiguration2")->__("Id"), "name" => "otp_id")); $event = $fieldset->addField("country_code", "text", array("label" => Mage::helper("otpconfiguration2")->__("Country Code"), "name" => "country_code", 'onchange' => 'checkSelectedItem(this)')); $fieldset->addField("otp_code", "text", array("label" => Mage::helper("otpconfiguration2")->__("Otp Code"), "name" => "otp_code")); $fieldset->addField("created_time", "text", array("label" => Mage::helper("otpconfiguration2")->__("Created Time"), "name" => "created_time")); $fieldset->addField("updated_time", "text", array("label" => Mage::helper("otpconfiguration2")->__("Updated Time"), "name" => "updated_time")); $fieldset->addField("user_id", "text", array("label" => Mage::helper("otpconfiguration2")->__("User Name"), "name" => "user_id", "values" => 'testing')); $event->setAfterElementHtml("<script type=\"text/javascript\">\n\t\t\t\t function checkSelectedItem(selectElement){\n\t\t\t\t var reloadurl = '" . Mage::helper("adminhtml")->getUrl("admin_otpconfiguration2/adminhtml_otpconfiguration/grid") . "?parent_id=' + selectElement.value;\n\t\t\t\t new Ajax.Request(reloadurl, {\n\t\t\t\t method: 'post',\n\t\t\t\t onLoading: function (transport) {\n\t\t\t\t \$('parent_id').update('Searching...');\n\t\t\t\t },\n\t\t\t\t onComplete: function(transport) {\n\t\t\t\t \$('parent_id').update('Searching...');\n\t\t\t\t }\n\t\t\t\t });\n\t\t\t\t }\n\t\t\t\t</script>"); if (Mage::getSingleton("adminhtml/session")->getOtpconfigurationData()) { $form->setValues(Mage::getSingleton("adminhtml/session")->getOtpconfigurationData()); Mage::getSingleton("adminhtml/session")->setOtpconfigurationData(null); } elseif (Mage::registry("otpconfiguration_data")) { $form->setValues(Mage::registry("otpconfiguration_data")->getData()); } mage::log(Mage::helper("adminhtml")->getUrl("hitmystyle_otpconfiguration2/otpconfiguration/grid"), null, 'log.log'); return parent::_prepareForm(); }
public function getCustomerTokenCard() { if (!is_null($this->_customer)) { if ($this->getCustomerToken()) { $call = 'customers/' . $this->getCustomerToken(); $proto = Zend_Http_Client::GET; $result = $this->talkToGateway(array(), $call, $proto); if (property_exists($result, 'error')) { $message = $this->buildError($result); Mage::throwException($message); } else { if (property_exists($result, 'response') && property_exists($result->response, 'token')) { return $result->response->card; } else { mage::log($result); mage::throwException('Invalid response from payment gateway. Please check logs for details.'); } } } } return false; }
public function saveRow(array $importData) { mage::log($_REQUEST); $cidade = $importData['cidade']; $estado = $importData['estado']; $pais = $importData['pais']; $valor = $importData['valor']; $custo = $importData['custo']; $cep_de = $importData['cep_de']; $cep_ate = $importData['cep_ate']; $peso_de = $importData['peso_de']; $peso_ate = $importData['peso_ate']; $titulo = $importData['titulo']; $website = $importData['website']; $regra = mage::getModel('regrasdefrete/regras'); $regra->setData(array('cidade' => $cidade, 'estado' => $estado, 'pais' => $pais, 'valor' => $valor, 'custo' => $custo, 'cep_de' => $cep_de, 'cep_ate' => $cep_ate, 'peso_de' => $peso_de, 'peso_ate' => $peso_ate, 'titulo' => $titulo, 'website' => $website)); if ($regra->save()) { return true; } else { Mage::throwException('Ocorreu um erro ao importar a regra ' . $titulo); return false; } return true; }
/** * * Add Wishlist Action * Return block */ public function wishlistAction() { $response = array(); if (!Mage::getStoreConfigFlag('wishlist/general/active')) { $response['status'] = 'ERROR'; $response['message'] = $this->__('Wishlist Has Been Disabled By Admin'); } if (!Mage::getSingleton('customer/session')->isLoggedIn()) { $response['status'] = 'ERROR'; $response['message'] = $this->__('Please Login First'); } if (empty($response)) { $session = Mage::getSingleton('customer/session'); $wishlist = $this->_getWishlist(); if (!$wishlist) { $response['status'] = 'ERROR'; $response['message'] = $this->__('Unable to Create Wishlist'); } else { $productId = (int) $this->getRequest()->getParam('product'); if (!$productId) { $response['status'] = 'ERROR'; $response['message'] = $this->__('Product Not Found'); } else { $product = Mage::getModel('catalog/product')->load($productId); if (!$product->getId() || !$product->isVisibleInCatalog()) { $response['status'] = 'ERROR'; $response['message'] = $this->__('Cannot specify product.'); } else { try { $requestParams = $this->getRequest()->getParams(); $buyRequest = new Varien_Object($requestParams); $result = $wishlist->addNewItem($product, $buyRequest); if (is_string($result)) { Mage::throwException($result); } $wishlist->save(); Mage::dispatchEvent('wishlist_add_product', array('wishlist' => $wishlist, 'product' => $product, 'item' => $result)); Mage::helper('wishlist')->calculate(); $message = array(); $message[] = '<p>' . $this->__('%1$s has been added to your wishlist.', $product->getName()) . '</p>'; $message[] = '<img src="' . $product->getImageUrl() . '" >'; $message[] = '<div class="ajax-action"><a class="view-wishlist" href="' . Mage::helper('wishlist')->getListUrl() . '"><span>' . $this->__('Go To Wishlist') . '</span></a></div>'; $response['status'] = 'SUCCESS'; $response['message'] = implode($message); Mage::unregister('wishlist'); $this->loadLayout(); $toplink = $this->getLayout()->getBlock('top.links')->toHtml(); $sidebar_block = $this->getLayout()->getBlock('wishlist_sidebar'); if ($sidebar_block) { $sidebar_block->setTemplate('wishlist/sidebar.phtml'); $sidebar = $sidebar_block->toHtml(); $response['sidebar'] = $sidebar; } $response['toplink'] = $toplink; } catch (Mage_Core_Exception $e) { $response['status'] = 'ERROR'; $response['message'] = $this->__('An error occurred while adding item to wishlist: %s', $e->getMessage()); } catch (Exception $e) { mage::log($e->getMessage()); $response['status'] = 'ERROR'; $response['message'] = $this->__('An error occurred while adding item to wishlist.'); } } } } } $this->getResponse()->setHeader('Content-type', 'application/json'); $this->getResponse()->setBody((string) $this->getRequest()->getParam('callback') . '(' . Mage::helper('core')->jsonEncode($response) . ')'); return; }
/** * Define consideration information depending of order and parameters * */ public function setConsiderationInformation($order, $quoteMode = false) { $considerationDateTimeStamp = null; $considerationComments = ''; if (!$quoteMode) { $orderRealDatetime = $order->getCreatedAt(); } else { $orderRealDatetime = date('Y-m-d H:i:s'); } mage::log('Order real datatime = ' . $orderRealDatetime); if (!$quoteMode) { //init consider date when order placed if (Mage::getStoreConfig('planning/consider/consider_order_when_placed') == 1) { $considerationDateTimeStamp = strtotime($orderRealDatetime); $considerationComments = mage::helper('purchase')->__('Order placed on ' . $orderRealDatetime) . '<br>'; //if order placed after specifi hour, add one day $maxHour = Mage::getStoreConfig('planning/consider/consider_order_tomorow_if_placed_after'); if (date('G', $considerationDateTimeStamp) > $maxHour) { $considerationDateTimeStamp += 3600 * 24; $considerationComments .= 'add 1 day as order placed after ' . $maxHour . 'h<br>'; } } //init order information when order invoiced if (Mage::getStoreConfig('planning/consider/consider_order_when_invoiced') == 1) { $invoiceDate = $this->getOrderInvoicedDate($order); if ($invoiceDate != null) { $considerationDateTimeStamp = strtotime($invoiceDate); $considerationComments = 'Order invoiced on ' . $invoiceDate . '<br>'; } else { $considerationComments = 'Order not invoiced<br>'; } } //init order information when payment_validated if (Mage::getStoreConfig('planning/consider/consider_order_on_paypment_validated') == 1) { if ($order->getpayment_validated() == 1) { $considerationDateTimeStamp = time(); $considerationComments = mage::helper('purchase')->__('Payment validated on ' . date('Y-m-d')) . '<br>'; //if order placed after specifi hour, add one day $maxHour = Mage::getStoreConfig('planning/consider/consider_order_tomorow_if_placed_after'); if (date('G', $considerationDateTimeStamp) > $maxHour) { $considerationDateTimeStamp += 3600 * 24; $considerationComments .= 'add 1 day as order placed after ' . $maxHour . 'h<br>'; } } } } else { $considerationDateTimeStamp = strtotime($orderRealDatetime); $considerationComments .= 'Quote for today<br>'; //add days depending of payment method $method = $order->getPayment()->getMethod(); if ($method != null) { $delay = $this->getPaymentDelay($method); if ($delay > 0) { $considerationDateTimeStamp += 3600 * 24 * $delay; $considerationComments .= 'Add ' . $delay . ' days for payment method (' . $method . ') -> ' . date('Y-m-d', $considerationDateTimeStamp) . '<br>'; } } else { $considerationComments .= 'No payment method<br>'; } } //add days to avoid holy day if (Mage::getStoreConfig('planning/consider/include_holy_days') == 0) { $daysToAdd = $this->DaysUntilNotHolyDay($considerationDateTimeStamp); if ($daysToAdd > 0) { $considerationDateTimeStamp += 3600 * 24 * $daysToAdd; $considerationComments .= 'add ' . $daysToAdd . ' days to avoid holy day<br>'; } } //set consideration informaiton if ($considerationDateTimeStamp != null) { $this->setpsop_consideration_date(date('Y-m-d', $considerationDateTimeStamp)); $this->setpsop_consideration_comments($considerationComments); } else { mage::log('Consideration date is null'); $this->setpsop_consideration_date(null); $this->setpsop_consideration_comments($considerationComments); } return $this; }
/** * Adding new item */ public function addAction() { $session = Mage::getSingleton('customer/session'); $wishlist = $this->_getWishlist(); if (!$wishlist) { $this->_redirect('*/'); return; } $productId = (int) $this->getRequest()->getParam('product'); if (!$productId) { $this->_redirect('*/'); return; } $product = Mage::getModel('catalog/product')->load($productId); if (!$product->getId() || !$product->isVisibleInCatalog()) { $session->addError($this->__('Cannot specify product.')); $this->_redirect('*/'); return; } try { $buyRequest = new Varien_Object($this->getRequest()->getParams()); $result = $wishlist->addNewItem($product, $buyRequest); if (is_string($result)) { Mage::throwException($result); } $wishlist->save(); Mage::dispatchEvent('wishlist_add_product', array('wishlist' => $wishlist, 'product' => $product, 'item' => $result)); $referer = $session->getBeforeWishlistUrl(); if ($referer) { $session->setBeforeWishlistUrl(null); } else { $referer = $this->_getRefererUrl(); } /** * Set referer to avoid referring to the compare popup window */ $session->setAddActionReferer($referer); Mage::helper('wishlist')->calculate(); $message = $this->__('%1$s has been added to your wishlist. Click <a href="%2$s">here</a> to continue shopping', $product->getName(), $referer); $session->addSuccess($message); } catch (Mage_Core_Exception $e) { $session->addError($this->__('An error occurred while adding item to wishlist: %s', $e->getMessage())); } catch (Exception $e) { mage::log($e->getMessage()); $session->addError($this->__('An error occurred while adding item to wishlist.')); } $this->_redirect('*'); }
/** * Import tracking file * */ public function importTrackingFile($t_lines) { $importedTrackingCount = 0; $skippedTrackingCount = 0; $debug = ''; for ($i = 0; $i < count($t_lines); $i++) { //skip first line (if required) $line = $t_lines[$i]; if ($i == 0 && $this->getct_import_skip_first_record()) { continue; } $tracking = null; $shipmentReference = null; //parse fixed format line if ($this->getct_import_format() == 'fixed') { $currentPosition = 0; foreach ($this->getFields('import') as $field) { $size = $field->getctf_size(); $fieldValue = substr($line, $currentPosition, $size); switch ($field->getctf_content()) { case 'tracking': $tracking = trim($fieldValue); break; case 'shipment': $shipmentReference = trim($fieldValue); break; } $currentPosition += $size; } } //parse delimiter format line if ($this->getct_import_format() == 'delimiter') { //split fields $t_columns = explode($this->getFieldSeparator('import'), $line); foreach ($this->getFields('import') as $field) { if (isset($t_columns[$field->getctf_position()])) { $fieldValue = $t_columns[$field->getctf_position()]; if ($this->getFieldDelimiter('import') != '') { $fieldValue = str_replace($this->getFieldDelimiter('import'), '', $fieldValue); } switch ($field->getctf_content()) { case 'tracking': $tracking = $fieldValue; break; case 'shipment': $shipmentReference = $fieldValue; break; } } } } //add tracking if ($tracking != null && $shipmentReference != null) { $debug .= 'process tracking ' . $tracking . ' for shipment #' . $shipmentReference . "\n"; $shipment = mage::getModel('sales/order_shipment')->loadByIncrementId($shipmentReference); if ($shipment->getId()) { if (!$this->shipmentContainsTracking($shipment, $tracking)) { try { $debug .= 'import tracking=' . $tracking . ' for shipment=' . $shipment->getincrement_id() . "\n"; $track = new Mage_Sales_Model_Order_Shipment_Track(); $track->setNumber($tracking)->setCarrierCode($this->getct_shipping_method())->setTitle('Tracking'); $shipment->addTrack($track)->save(); $importedTrackingCount++; } catch (Exception $ex) { $debug .= 'Error for line #' . $i . ' : ' . $ex->getMessage() . "\n"; $skippedTrackingCount++; } } else { $skippedTrackingCount++; $debug .= 'Tracking already exist for line #' . $i . "\n"; } } else { $skippedTrackingCount++; $debug .= 'Unable to retrieve shipment for line #' . $i . "\n"; } } else { $debug .= 'Unable to retrieve shipment or/and tracking for line #' . $i . "\n"; } } mage::log($debug); $msg = mage::helper('Orderpreparation')->__('Tracking import complete : %s tracking imported, %s tracking skipped', $importedTrackingCount, $skippedTrackingCount); return $msg; }
/** * Function to print shipping label for selected waybills */ public function shippinglabelAction() { $waybills = $this->getRequest()->getParam('lastmile'); mage::log("Shipping Label Printed for these waybills {$waybills}"); $flag = false; if (!empty($waybills)) { $labelperpage = 5; $totalpages = sizeof($waybills) / $labelperpage; $pdf = new Zend_Pdf(); $style = new Zend_Pdf_Style(); for ($page_index = 0; $page_index <= $totalpages; $page_index++) { $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4); $pdf->pages[] = $page; } $pagecounter = 0; $i = 0; $y = 830; foreach ($waybills as $waybill) { $awb = Mage::getModel('lastmile/lastmile')->load($waybill); if ($awb->state == 2) { continue; } $i++; // check if next page; if ($i % $labelperpage == 0) { $pagecounter++; // Set to use new page $y = 830; // Set position for first label on new page } //$pdf->pages[$pagecounter]; $shipments = Mage::getResourceModel('sales/order_shipment_collection')->setOrderFilter($awb->orderid)->load(); if ($shipments->getSize()) { $flag = true; //$pdf = $this->getPdf($awb->awb,$shipment); foreach ($shipments as $shipment) { Mage::getModel('lastmile/shippinglabel')->getContent($pdf->pages[$pagecounter], $shipment->getStore(), $awb->awb, $shipment->getOrder(), $y); } } // Set position for the next label on same page $y = $y - 190; } if ($flag) { return $this->_prepareDownloadResponse('shippinglabel' . Mage::getSingleton('core/date')->date('Y-m-d_H-i-s') . '.pdf', $pdf->render(), 'application/pdf'); } else { $this->_getSession()->addError($this->__('There are no printable shipping labels related to selected waybills.')); $this->_redirect('*/*/'); } } $this->_redirect('*/*/'); }
/** * Update delivery date for product * * @param unknown_type $productId */ public function updateProductDeliveryDate($productId) { $deliveryDate = null; mage::log('Updating product delivery date for product #' . $productId); //collect PO for product (po status = waiting for delivery and order contains product $collection = mage::getModel('Purchase/Order')->getCollection()->join('Purchase/OrderProduct', 'po_num=pop_order_num')->addFieldToFilter('po_status', MDN_Purchase_Model_Order::STATUS_WAITING_FOR_DELIVERY)->addFieldToFilter('pop_product_id', $productId); //browse colleciton to set date foreach ($collection as $item) { mage::log('--> check order #' . $item->getId() . ' with supply date = ' . $item->getpo_supply_date()); if ($item->getpop_qty() > $item->getpop_supplied_qty()) { if ($deliveryDate == null || $deliveryDate > $item->getpo_supply_date()) { $deliveryDate = $item->getpo_supply_date(); } } } //update product mage::log('--> save date : ' . $deliveryDate); Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); $product = mage::getModel('catalog/product')->load($productId); $product->setsupply_date($deliveryDate)->save(); }
protected function _processResult($payment, $result, $tag = NULL) { $this->_returnParam = ''; $_SESSION["cyberscoure_cardtype"] = ''; $_SESSION["cybersource_total"] = ''; $_SESSION["cybersource_currency"] = ''; $additionalData = array(); $additionalData[$tag] = $result; $additionalData['purchase_total'] = $this->_request->purchaseTotals->grandTotalAmount; //$payment->setAdditionalData(serialize($additionalData))->save(); //all is good the response code is 100 if ($result->reasonCode == self::RESPONSE_CODE_SUCCESS && $result->decision == 'ACCEPT') { // Remove any latent redirect URL from the session data $this->getCheckout()->setRedirectUrl(''); $payment->setLastTransId($result->requestID)->setLastCybersourceToken($result->requestToken)->setCcTransId($result->requestID)->setCybersourceToken($result->requestToken)->setCcAvsStatus($result->ccAuthReply->avsCode); /* * checking if we have cvCode in response bc * if we don't send cvn we don't get cvCode in response */ if (isset($result->ccAuthReply->cvCode)) { $payment->setCcCidStatus($result->ccAuthReply->cvCode); } $payment->setStatus(self::STATUS_APPROVED); $payment->setAdditionalData(serialize($additionalData)); Mage::getSingleton('checkout/session')->setAdditionalData(serialize($additionalData)); Mage::getSingleton('checkout/session')->unsetData('cyber_source_last_request_id'); Mage::getSingleton('checkout/session')->unsetData('cyber_source_last_request_token'); Mage::getSingleton('checkout/session')->unsetData('merchant_reference_code'); Mage::getSingleton('checkout/type_onepage')->saveOrderSuccess($payment->getOrder()); } elseif ($result->reasonCode == self::RESPONSE_CODE_ENROLLED && $result->decision == 'REJECT') { //THIS IS WHEN A CARD HAS BEEN CHECKED FOR ENROLLMENT // 3D Secure Data $sPAReq = $result->payerAuthEnrollReply->paReq; //$sMd = $result->payerAuthEnrollReply->xid; $encryptionHandler = $this->getInfoInstance(); $sMd = Mage::helper('core')->encrypt($payment->getData('cc_number') . '|' . $payment->getData('cc_cid')); $sACSURL = $result->payerAuthEnrollReply->acsURL; $session = Mage::getSingleton('checkout/session'); //$session->getQuote()->setIsActive(true)->save(); Mage::getSingleton('checkout/session')->setAcsurl($result->payerAuthEnrollReply->acsURL)->setPareq($result->payerAuthEnrollReply->paReq)->setCybersourceQuoteId($session->getQuoteId())->setCybersourceSuccessQuoteId($session->getLastSuccessQuoteId())->setCybersourceRealOrderId($session->getLastRealOrderId())->setAdditionalData($additionalData); Mage::getSingleton('checkout/session')->setCyberSourceLastRequestId($result->requestID); Mage::getSingleton('checkout/session')->setCyberSourceLastRequestToken($result->requestToken); $this->_returnParam = '3DSECURE|?ACSURL=' . $sACSURL . "|MD=" . urlencode($sMd) . "|PaReq=" . $sPAReq . "|TermURL=" . $this->getTermURL() . "?tokenid=" . $result->requestToken . "|" . $this->get3DSecureURL(); $payment->setLastTransId($result->requestID)->setCcTransId($result->requestID)->setCybersourceToken($result->requestToken); if (isset($result->ccAuthReply->avsCode)) { $payment->setCcAvsStatus($result->ccAuthReply->avsCode); } /* * checking if we have cvCode in response bc * if we don't send cvn we don't get cvCode in response */ if (isset($result->ccAuthReply->cvCode)) { $payment->setCcCidStatus($result->ccAuthReply->cvCode); } $_SESSION["cyberscoure_cardtype"] = $this->_request->card->cardType; $_SESSION["cybersource_total"] = $this->_request->purchaseTotals->grandTotalAmount; $_SESSION["cybersource_currency"] = $this->_request->purchaseTotals->currency; } elseif ($result->reasonCode == self::RESPONSE_CODE_AVSFAIL && $result->decision == 'REJECT') { //AVS FAILED BUT CARD OK SO DO WHAT THE CONFIG SAYS CARD NOT ENROLLED $fail3d_status = Mage::getStoreConfig('payment/cybersource_soap/fail_avs_order_status'); if ($fail3d_status != 'nosave') { if ($result->requestID) { mage::log('AVS FAIL CALLED NO 3d Secure ' . $result->requestID); } // Save order as normal $this->getCheckout()->setRedirectUrl(''); $payment->setLastTransId($result->requestID)->setLastCybersourceToken($result->requestToken)->setCcTransId($result->requestID)->setCybersourceToken($result->requestToken)->setCcAvsStatus($result->ccAuthReply->avsCode); /* * checking if we have cvCode in response bc * if we don't send cvn we don't get cvCode in response */ if (isset($result->ccAuthReply->cvCode)) { $payment->setCcCidStatus($result->ccAuthReply->cvCode); } $payment->setStatus(self::STATUS_APPROVED); $payment->setAdditionalData(serialize($additionalData)); Mage::getSingleton('checkout/session')->setAdditionalData(serialize($additionalData)); Mage::getSingleton('checkout/session')->unsetData('cyber_source_last_request_id'); Mage::getSingleton('checkout/session')->unsetData('cyber_source_last_request_token'); Mage::getSingleton('checkout/session')->unsetData('merchant_reference_code'); Mage::getSingleton('checkout/type_onepage')->saveOrderSuccess($payment->getOrder()); } else { Mage::throwException('Sorry your billing address does not match that on your card, please check the first line of the address and the postcode and try again.'); $this->_unsetSessionVars(); } } else { //improve this error reporting with actual error codes. $errorResponses = $this->getErrorCodes(); $errorResponse = 'Sorry an unknown error has occurred with your payment, please call us. ' . $result->reasonCode; if (key_exists($result->reasonCode, $errorResponses)) { $errorResponse = $errorResponses[$result->reasonCode]; } Mage::throwException($errorResponse); $this->_unsetSessionVars(); } $this->getCheckout()->setParams($this->_returnParam); }
/** * Appelé lorsqu'une facture est payée * */ public function sales_order_invoice_pay(Varien_Event_Observer $observer) { //si on doit passer payment_validated à true if (Mage::getStoreConfig('purchase/configuration/auto_validate_payment') == 1) { try { //recupere les infos $order = $observer->getEvent()->getInvoice()->getOrder(); $order->setpayment_validated(1)->save(); mage::log('payment_validated set to true for order #' . $order->getId()); } catch (Exception $ex) { mage::log('Error when validating payment_validated: ' . $ex->getMessage()); } } }
protected function _initAction() { mage::log('initi', null, 'grid.log'); $this->loadLayout()->_setActiveMenu("otpconfiguration2/otpconfiguration")->_addBreadcrumb(Mage::helper("adminhtml")->__("Otpconfiguration Manager"), Mage::helper("adminhtml")->__("Otpconfiguration Manager")); return $this; }
public function runCron() { mage::log("runCron"); $this->_intTime(); $this->_checkAbandonedCarts(); $this->_checkBirthdays(); $currenttime = date('Y-m-d H:i:s', time()); $coupons = Mage::getModel('followupemail/coupons')->getCollection()->addFieldToFilter('coupon_status', MW_FollowUpEmail_Model_System_Config_Statuscoupon::COUPON_STATUS_SENT)->addFieldToFilter('expiration_date', array('to' => $currenttime)); foreach ($coupons->load()->getData() as $c) { $coupon = Mage::getModel('followupemail/coupons'); $coupon->load($c['coupon_id'])->setCouponStatus(MW_FollowUpEmail_Model_System_Config_Statuscoupon::COUPON_STATUS_EXPIRED)->save(); } $queueEmails = Mage::getModel('followupemail/emailqueue')->getCollection()->addFieldToFilter('status', MW_FollowUpEmail_Model_System_Config_Status::QUEUE_STATUS_READY)->addFieldToFilter('scheduled_at', array('to' => $currenttime)); foreach ($queueEmails->load()->getData() as $d) { //Mage::log("FUE:runCron:".$d['queue_id']); $emailBefore = Mage::getModel('followupemail/emailqueue')->load($d['queue_id']); $params = $emailBefore->getParams(); if (@unserialize($params) === FALSE) { //Mage::log("FUE:runCron:".$d['queue_id'].':updateparams'); Mage::getModel('followupemail/observer')->updateParamsEmail($emailBefore); } $result = Mage::getModel('followupemail/emailqueue')->load($d['queue_id'])->send(); if ($result === true) { } else { if ($result == 3) { Mage::log("FUE log:"); Mage::log("Email " . $d['recipient_email'] . " sent error because:"); Mage::log("This email is not sent to customer neither BBCed to anyone."); } else { Mage::log("FUE log:"); Mage::log("Email " . $d['recipient_email'] . " ccould not be sent."); } } } }
/** * Process a refund * * @param Varien_Object $payment * @param double $amount * @return \ProxiBlue_PinPayments_Model_Gateway */ public function refund(Varien_Object $payment, $amount) { $this->setAmount($amount)->setPayment($payment); try { $result = $this->talkToGateway(array(), 'charges/' . $payment->getRefundTransactionId() . '/refunds'); if (property_exists($result, 'error')) { $message = $this->buildError($result); Mage::throwException($message); } else { if (property_exists($result, 'response') && property_exists($result->response, 'success')) { $payment->setStatus(self::STATUS_APPROVED)->setLastTransId($result->response->token)->setRefundTransactionId($result->response->token); } else { mage::log($result); mage::throwException('Invalid response from payment gateway. Please check logs for details.'); } } } catch (Exception $e) { Mage::throwException($e->getMessage()); } return $this; }