Magento – Change customer group id for guest inside onepage

checkoutcustomer-grouponepage-checkoutquote

I need to dynamically change customer group id inside onestepcheckout page. I tried to insert

Mage::getSingleton('checkout/session')->getQuote()->setCustomerGroupId(3)->save()

just before $this->getOnepage()->saveBilling, but it doesn't work.

I guess the problem is inside _validateCustomerData() inside Mage_Checkout_Model_Type_Onepage where there are lines:

    if ($quote->getCheckoutMethod() == self::METHOD_REGISTER) {
        // set customer password
        $customer->setPassword($customerRequest->getParam('customer_password'));
        $customer->setConfirmation($customerRequest->getParam('confirm_password'));
    } else {
        // spoof customer password for guest
        $password = $customer->generatePassword();
        $customer->setPassword($password);
        $customer->setConfirmation($password);
        // set NOT LOGGED IN group id explicitly,
        // otherwise copyFieldset('customer_account', 'to_quote') will fill it with default group id value
        $customer->setGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
    }

One option would be to change function _validateCustomerData and change line

$customer->setGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID); 

where I would pass and write desired groupId. I am not sure if there is any better way. Thanks for any suggestion!

Best Answer

I just found there is observer sales_quote_collect_totals_before which help to achieve what I want.

xml:

    <events>
        <sales_quote_collect_totals_before>
            <observers>
                <companyname_modulename_customergroup_observer>
                    <type>singleton</type>
                    <class>Companyname_Modulename_Model_Customer_Observer</class>
                    <method>updateCustomerGroup</method>
                </companyname_modulename_customergroup_observer>
            </observers>
        </sales_quote_collect_totals_before>
    </events>

Observer class:

class Companyname_Modulename_Model_Customer_Observer extends Mage_Core_Model_Abstract
{
    public function updateCustomerGroup($observer)
    {
        Mage::getSingleton('checkout/session')->getQuote()->setCustomerGroupId(3);
    }
}

There is still a small problem. Inside admin customer will be still under NOT LOGGED IN group, even if I changed it. But tax class will be correct for customer group I selected inside observer which is the reason why I actually needed to change customer group id. So I am fine with that.