Wednesday, April 29, 2015

Magento Maximum Allowed Order QTY

ake a look @ Magento Maximum Allowed Order Amount, you would have to create a custom module to add this feature.
Create an observer for sales_quote_save_before

<config>
    <frontend>
        <events>
            <sales_quote_save_before>
                <observers>
                    <mymodule_custom>
                        <class>Mymodule_Custom_Model_Observer</class>
                        <method>LimitOrderqty</method>
                    </mymodule_custom>
                </observers>
            </sales_quote_save_before>
        </events>
    </frontend>
</config>
 
In your observer
 
<?php  
class Mymodule_Custom_Model_Observer {
 
public function LimitOrderqty(Varien_Event_Observer $observer){ 
   $cart = Mage::getModel('checkout/cart')->getQuote();
   $customer = Mage::getSingleton('customer/session')->getCustomer();
   $allowQTY = $customer->getLastsaleqty() + (int)($customer->getLastsaleqty()*$customer->getGreaseqty()/100);
  if ($cart->getItemsQty() > $allowQTY) {
            Mage::getSingleton('checkout/session')->addError('You are not allow to add that QTY in your cart. Your Approved QTY limit '.$allowQTY);
   
   Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('checkout/cart'));
            Mage::app()->getResponse()->sendResponse();
            exit;
        }
 }
   
} 

Tuesday, April 28, 2015

How to create user concurrency in Magento

I had a requirement where my client was looking on user login concurrency. By default Magento don't have this feature. So i have created a module which will handle user concurrency. Please follow the code to do it.


Go to the following site and create your module in a quick way.
http://www.silksoftware.com/magento-module-creator/#.UvHRXfuMA3h

Now Create the following table
CREATE TABLE IF NOT EXISTS 'customer_login_tracking' (
  'email' varchar(100) NOT NULL,
  'session_id' varchar(200) NOT NULL,
  'login_time' int(11) NOT NULL,
  UNIQUE KEY 'customer_id' ('email')
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now add the following code in your etc/config.xml (where my module name space is Mymodule and module is Custom)
  <frontend>     
         <routers>
          <custom>
            <use>standard</use>
              <args>
                <module>Mymodule_Custom</module>
                <frontName>newpassword</frontName>
              </args>             
          </custom>
          <customer>
            <args>
                <modules>
                    <Mymodule_Custom before="Mage_Customer_AccountController">Mymodule_Custom</Mymodule_Custom>
                </modules>
            </args>
          </customer>
        </routers>
 </frontend>

 Now i have created 2 controllers
Custom\controllers\AccountController.php

<?php

require_once(Mage::getModuleDir('controllers','Mage_Customer').DS.'AccountController.php');

class Mymodule_Custom_AccountController extends Mage_Customer_AccountController
{
   

    /**
     * Login post action
     */
    public function loginPostAction()
    {
       
        if (!$this->_validateFormKey()) {
            $this->_redirect('*/*/');
            return;
        }

        if ($this->_getSession()->isLoggedIn()) {
            $this->_redirect('*/*/');
            return;
        }
        $session = $this->_getSession();

        if ($this->getRequest()->isPost()) {
            $login = $this->getRequest()->getPost('login');
            if (!empty($login['username']) && !empty($login['password'])) {
                try {
                       $resource = Mage::getSingleton('core/resource');
                       $readConnection = $resource->getConnection('core_read');
                       $writeConnection = $resource->getConnection('core_write');
                                             
                       $tableName2 = $resource->getTableName('customer_login_tracking');
                      
                       $login_check = $readConnection->fetchRow('SELECT * FROM ' . $tableName2.' WHERE email="'.$login['username'].'"');
                      
                       if(isset($login_check['session_id'])){
                           $value = Mage::getUrl('custom/index/Clearcustomersession/us/'.base64_encode($login['username']));
                           $message = $this->_getHelper('customer')->__('You are already login from other place. <a href="%s">Click here</a> to clear the session.', $value);
                           Mage::getSingleton('core/session')->addError($message);
                       }else{
                          if($session->login($login['username'], $login['password'])){
                              $query = 'INSERT INTO '.$tableName2.' SET email="'.$login['username'].'", session_id="'.$session->getEncryptedSessionId().'", login_time="'.time().'"';
                              $writeConnection->query($query); 
                          }
                          if ($session->getCustomer()->getIsJustConfirmed()) {                               
                                $this->_welcomeCustomer($session->getCustomer(), true);                                                                       
                          }
                       }
                   
                } catch (Mage_Core_Exception $e) {
                    switch ($e->getCode()) {
                        case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
                            $value = $this->_getHelper('customer')->getEmailConfirmationUrl($login['username']);
                            $message = $this->_getHelper('customer')->__('This account is not confirmed. <a href="%s">Click here</a> to resend confirmation email.', $value);
                            break;
                        case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
                            $message = $e->getMessage();
                            break;
                        default:
                            $message = $e->getMessage();
                    }
                    $session->addError($message);
                    $session->setUsername($login['username']);
                } catch (Exception $e) {
                    // Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
                }
            } else {
                $session->addError($this->__('Login and password are required.'));
            }
        }

        $this->_loginPostRedirect();
    }
   
     /**
     * Customer logout action
     */
    public function logoutAction()
    {
        $resource = Mage::getSingleton('core/resource');
        $tableName2 = $resource->getTableName('customer_login_tracking');
        $readConnection = $resource->getConnection('core_read');   
        $readConnection->query('DELETE FROM '.$tableName2.' WHERE email="'.$this->_getSession()->getCustomer()->getEmail().'"');
       
        $this->_getSession()->logout()
            ->renewSession();

        $this->_redirect('*/*/logoutSuccess');
    }

  
}


Custom\controllers\IndexController.php

<?php
class Mymodule_Custom_IndexController extends Mage_Core_Controller_Front_Action{
public function ClearcustomersessionAction(){       
         $email = base64_decode($this->getRequest()->getParam('us'));
         $resource = Mage::getSingleton('core/resource');
         $readConnection = $resource->getConnection('core_read');
         $tableName = $resource->getTableName('customer_login_tracking');       
         $result = $readConnection->fetchRow('SELECT * FROM ' . $tableName.' WHERE email="'.$email.'"');
         unlink(Mage::getBaseDir('session').'\sess_'.$result['session_id']);
         $readConnection->query('DELETE FROM '.$tableName.' WHERE email="'.$email.'"');
         Mage::getSingleton('core/session')->addSuccess('Your previous session has been remove. Please login again.');
         Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('customer/account'));
     }
}

  

Sunday, April 12, 2015

Magento redirect to login page while user not login on landing

$redirect_url = Mage::getUrl('customer/account/login/');
$current_url = Mage::helper('core/url')->getCurrentUrl();
if((!$this->helper('customer')->isLoggedIn()) && ($current_url != $redirect_url)){
    Mage::app()->getFrontController()->getResponse()->setRedirect($redirect_url);
}

Friday, April 10, 2015

How to create new attributes for customer

Hello Friend,
I have found some small and Quick solution for creating attribute for customer.
Login your Admin and follow the stapes.
Catalog -> Attribute -> Manage Attributes
Now create an attribute. It might be text box or drop down
Now open your phpmyadmin & find out eav_attribute table Now find out your attribute with your attribute_code and change entity_type_id with 1. Because 1 stand for customer attribute.
Now from any controller just run the following code


$oAttribute = Mage::getSingleton('eav/config')->getAttribute('customer', 'your attribute code');
$oAttribute->setData('used_in_forms', array('customer_account_edit','customer_account_create','adminhtml_customer','checkout_register'));
$oAttribute->save();