Looking for a JavaEE Architect or Potential Tech Co-Founder?
Please don't hesitate to contact me.

Create a Magento extension that will only allow a customer to login until a given expiry time

Long time ago I was assigned to modify magento, add an expiry date and check if the costumer is expired during login. Those times resource were scarce and what I did was hacked magento, add custom codes and fields in the database. Which is not a good idea since all the work you did will be washed away if you decided to update your magento installation.

So here I am again face with the same problem, but this time we have the concept of community extension in magento /app/code/community, so I'll share a process on how to create such extension.

After all the code is installed on your magento it will add Customer Expiration section under, System->Configuration->Customer Configuration. And "Valid Until" field in Customers->Manage Customers->Select a Customer->Account Information.

Requirements: 1.) Follow the procedure here: http://czetsuya-tech.blogspot.com/2011/11/how-to-install-and-setup-magento-on.html
Note that I'm working on a windows 7 machine.

2.) Create the ff folder structure, and the enumerated files (I'll include the source below):
+app
 +code
  +community
   +KalidadBusinessSolutions
    +CustomerExpiration
     +Block
      +Customer
       +Grid.php
      +Widget
       +Grid
        +Column
         +Renderer
          +Datetime.php
     +controllers
      +AdminController.php
     +etc
      +config.xml
      +system.xml
     +Helper
      +Data.php
     +Model
      +Observer.php
     +sql
      +customerexpiration_setup
       +mysql4-install-0.0.1.php
+etc
 +modules
  +KalidadBusinessSolutions_All.xml
+locale
 +en_US
  +KalidadBusinessSolutions_CustomerActivation.csv
The files: Grid.php
class KalidadBusinessSolutions_CustomerExpiration_Block_Adminhtml_Customer_Grid extends Mage_Adminhtml_Block_Customer_Grid
{
 public function setCollection($collection)
 {
  if ($this->_isActive())
  {
   $collection->addAttributeToSelect('customer_expirydate');
  }

  return parent::setCollection($collection);
 }

 public function addColumn($name, $params)
 {
  if ($this->_isActive())
  {
   if ($name == 'action')
   {
    self::addColumn('customer_expirydate', array(
     'header'    => Mage::helper('customer')->__('Customer Activated'),
     'align'     => 'center',
     'type'      => 'datetime',
     'default'   => '0',
     'index'     => 'customer_expirydate',
     'renderer'  => 'customerexpiration/adminhtml_widget_grid_column_renderer_datetime'
     ));
   }
  }

  return parent::addColumn($name, $params);
 }

 protected function _isActive()
 {
  if(Mage::getStoreConfig('customer/customerexpiration/disable_ext') &&
  !Mage::getStoreConfig('customer/customerexpiration/always_active_in_admin'))
  {
   return false;
  }
  return true;
 }
}
Datetime.php
class KalidadBusinessSolutions_CustomerExpiration_Block_Adminhtml_Widget_Grid_Column_Renderer_Datetime
extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Datetime
{
 public function render(Varien_Object $row)
 {
  if ($data = $this->_getValue($row)) {
   $format = $this->_getFormat();
   try {
    $data = Mage::app()->getLocale()->date($data, Varien_Date::DATETIME_INTERNAL_FORMAT)->toString($format);
   }
   catch (Exception $e)
   {
    $data = Mage::app()->getLocale()->date($data, Varien_Date::DATETIME_INTERNAL_FORMAT)->toString($format);
   }
   return $data;
  }
  return $this->getColumn()->getDefault();
 }
}
AdminController.php
class KalidadBusinessSolutions_CustomerExpiration_AdminController extends Mage_Adminhtml_Controller_Action
{
 
}
Data.php
class KalidadBusinessSolutions_CustomerExpiration_Helper_Data extends Mage_Core_Helper_Abstract
{
 
}
Observer.php
class KalidadBusinessSolutions_CustomerExpiration_Model_Observer extends Mage_Core_Model_Abstract
{
 const XML_PATH_MODULE_DISABLED = 'customer/customerexpiration/disable_ext';

 /**
  * Fired on customer_login event
  * Check if the customer has been activated (via adminhtml)
  * If not, through login error
  *
  * @param Varien_Event_Observer $observer
  */
 public function customerLogin($observer)
 {
  if (Mage::getStoreConfig(self::XML_PATH_MODULE_DISABLED) == 1)
  {
   return;
  }
  
  if ($this->_isApiRequest())
  {
   return;
  }
  
  $customer = $observer->getEvent()->getCustomer();
  $session = Mage::getSingleton('customer/session');
  
  $todays_date = date("Y-m-d"); 
  $today = strtotime($todays_date);  
  
  if ($today >= strtotime($customer->getData('customer_expirydate')))
  {
   $session->setCustomer(Mage::getModel('customer/customer'))->setId(null);
   Mage::throwException(Mage::helper('customerexpiration')->__('This account is not activated or is expired.'));   
  }
 }

 /**
  * Return true if the request is made via the api.
  *
  * @return boolean
  */
 protected function _isApiRequest()
 {
  return Mage::app()->getRequest()->getModuleName() === 'api';
 }

}
mysql4-install-0.0.1.php
$this->startSetup();

$this->addAttribute('customer', 'customer_expirydate', array(
 'type' => 'datetime',
 'input' => 'date',
 'label' => 'Active Until',
 'global' => 1,
 'visible' => 1,
 'required' => 0,
 'user_defined' => 1,
 'default' => null,
 'visible_on_front' => 0,
));

$customer = Mage::getModel('customer/customer');
$attrSetId = $customer->getResource()->getEntityType()->getDefaultAttributeSetId();

$this->addAttributeToSet('customer', $attrSetId, 'General', 'customer_expirydate');

if (version_compare(Mage::getVersion(), '1.4.2', '>='))
{
 Mage::getSingleton('eav/config')
  ->getAttribute('customer', 'customer_expirydate')
  ->setData('used_in_forms', array('adminhtml_customer'))
  ->save();
}

$this->endSetup();
config.xml
<config>
 <modules>
  <KalidadBusinessSolutions_CustomerExpiration>
   <version>0.0.1</version>
  </KalidadBusinessSolutions_CustomerExpiration>
 </modules>
 <global>
  <models>
   <customerexpiration>
    <class>KalidadBusinessSolutions_CustomerExpiration_Model</class>
   </customerexpiration>
  </models>  
  <helpers>
   <customerexpiration>
    <class>KalidadBusinessSolutions_CustomerExpiration_Helper</class>
   </customerexpiration>
  </helpers>
  <blocks>
   <customerexpiration>
    <class>KalidadBusinessSolutions_CustomerExpiration_Block</class>
   </customerexpiration>
   <adminhtml>
    <rewrite>
     <!-- overwrite Mage_Adminhtml_Block_Customer_Grid to add activation to grid -->
     <customer_grid>KalidadBusinessSolutions_CustomerExpiration_Block_Adminhtml_Customer_Grid</customer_grid>
    </rewrite>
   </adminhtml>
  </blocks>
  <resources>
   <customerexpiration_setup>
    <setup>
     <module>KalidadBusinessSolutions_CustomerExpiration</module>
     <class>Mage_Customer_Model_Entity_Setup</class>
    </setup>
   </customerexpiration_setup>
  </resources>
 </global>

 <admin>
  <routers>
   <customerexpiration>
    <use>admin</use>
    <args>
     <module>KalidadBusinessSolutions_CustomerExpiration</module>
     <frontName>customerexpiration</frontName>
    </args>
   </customerexpiration>
  </routers>
 </admin>

 <frontend>
  <events>
   <customer_login>
    <observers>
     <customerexpiration>
      <type>singleton</type>
      <class>customerexpiration/observer</class>
      <method>customerLogin</method>
     </customerexpiration>
    </observers>
   </customer_login>
  </events>
        <translate>
            <modules>
                <KalidadBusinessSolutions_CustomerExpiration>
                     <files>
                          <default>KalidadBusinessSolutions_CustomerExpiration.csv</default>
                     </files>
                </KalidadBusinessSolutions_CustomerExpiration>
            </modules>
        </translate>
 </frontend>

 <default>
  <customer>
   <CustomerExpiration>
    <disable_ext>0</disable_ext>
    <always_active_in_admin>1</always_active_in_admin>
   </CustomerExpiration>
  </customer>
 </default>

 <adminhtml>
        <translate>
            <modules>
                <KalidadBusinessSolutions_CustomerExpiration>
                     <files>
                          <default>KalidadBusinessSolutions_CustomerExpiration.csv</default>
                     </files>
                </KalidadBusinessSolutions_CustomerExpiration>
            </modules>
        </translate>
 </adminhtml>

</config>
system.xml
<?xml version="1.0"?>
<config>
    <sections>
        <customer translate="label" module="customer">
            <groups>
                <customerexpiration translate="label" module="customerexpiration">
                    <label>Customer Expiration</label>
                    <sort_order>768</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                    <fields>
                        <disable_ext translate="label" module="customerexpiration">
                            <label>Disable Customer Expiration</label>
                            <frontend_type>select</frontend_type>
       <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>10</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </disable_ext>
                        <always_active_in_admin translate="label" module="customerexpiration">
                            <label>Always enable in admin interface</label>
                            <frontend_type>select</frontend_type>
       <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>11</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
       <comment>If you want to set account expiry via the admin interface</comment>
                        </always_active_in_admin>                             
                    </fields>
                </customerexpiration>
            </groups>
        </customer>
    </sections>
</config>
KalidadBusinessSolutions_All.xml

 
  
   true
   community
   
    
    
   
  
 

KalidadBusinessSolutions_CustomerActivation.csv
"This account is not activated or is expired.","This account is not activated or is expired."
"Active until","Active until"
After installing all the mentioned files you showed have he ff view: System View
Customer Information
Create a Magento extension that will only allow a customer to login until a given expiry time Create a Magento extension that will only allow a customer to login until a given expiry time Reviewed by Edward Legaspi on Friday, December 02, 2011 Rating: 5

5 comments:

Oğuz Çelikdemir said...

I knew you will do :) congratulations. Oğuz

Vincent said...

Tried using the code but not working. Can I have the complete code?

monserrate483 said...

Hi there,
Looking for a way to add and expiration date to the accounts, I just found your solution which is exactly what I need, the only thing is that 3 years has passed since this article and Magento has changed a lot since then. I'm just a merchant and I don't know if this is going to work now with version 1.9.0.1. Have you updated this information in different article by chance???
Thank you,
Alma

monserrate483 said...

I'm not sure that my previews comment went thru. My question is, have you this information updated for Magento 1.9.0.1?

Edward Legaspi said...

Hi,

I haven't work with magento for quite some time now, so I'm not sure if this tutorial is still applicable to newer releases. But I think the concept here still applies, and maybe magento has simplified creating something like this. 2 things you can do: 1.) find a plugin that has this functionality, since this is common, chances are it's already available for free; 2.) hire a freelancer to create the plugin.

Powered by Blogger.