0

Hello all i want to do some changes in Magento Enterprise's Gift card functionality so that i have override the observer of Enterprise_Giftcard module into my local module Essentiel_Giftcards and its working correctly.

Here is my code

Config.xml

<?xml version="1.0" encoding="utf-8"?>
<config>
    <modules>
        <Essentiel_Giftcards>
            <version>0.1.0</version>
        </Essentiel_Giftcards>
    </modules>
    <global>
        <models>
            <essentiel_giftcards>
                <class>Essentiel_Giftcards_Model</class>
            </essentiel_giftcards>
            <essentiel_giftcard_resource>
                <class>Essentiel_Giftcards_Model_Resource</class>
            </essentiel_giftcard_resource>
            <enterprise_giftcard>
                <rewrite>
                    <observer>Essentiel_Giftcards_Model_Observer</observer>
                </rewrite>
            </enterprise_giftcard>
        </models>
     </global>
</config>

Observer.php

class Essentiel_Giftcards_Model_Observer extends Enterprise_GiftCard_Model_Observer
{
 /**
 * Generate gift card accounts after order save
 *
 * @param Varien_Event_Observer $observer
 * @return Enterprise_GiftCard_Model_Observer
 */
public function generateGiftCardAccounts(Varien_Event_Observer $observer)
{
    // sales_order_save_after

    $order = $observer->getEvent()->getOrder();
    $requiredStatus = Mage::getStoreConfig(
        Enterprise_GiftCard_Model_Giftcard::XML_PATH_ORDER_ITEM_STATUS,
        $order->getStore());
    $loadedInvoices = array();

    foreach ($order->getAllItems() as $item) {
        if ($item->getProductType() == Enterprise_GiftCard_Model_Catalog_Product_Type_Giftcard::TYPE_GIFTCARD) {
            $qty = 0;
            $options = $item->getProductOptions();

            switch ($requiredStatus) {
                case Mage_Sales_Model_Order_Item::STATUS_INVOICED:
                    $paidInvoiceItems = (isset($options['giftcard_paid_invoice_items'])
                        ? $options['giftcard_paid_invoice_items']
                        : array());
                    // find invoice for this order item
                    $invoiceItemCollection = Mage::getResourceModel('sales/order_invoice_item_collection')
                        ->addFieldToFilter('order_item_id', $item->getId());

                    foreach ($invoiceItemCollection as $invoiceItem) {
                        $invoiceId = $invoiceItem->getParentId();
                        if(isset($loadedInvoices[$invoiceId])) {
                            $invoice = $loadedInvoices[$invoiceId];
                        } else {
                            $invoice = Mage::getModel('sales/order_invoice')
                                ->load($invoiceId);
                            $loadedInvoices[$invoiceId] = $invoice;
                        }
                        // check, if this order item has been paid
                        if ($invoice->getState() == Mage_Sales_Model_Order_Invoice::STATE_PAID &&
                            !in_array($invoiceItem->getId(), $paidInvoiceItems)
                        ) {
                                $qty += $invoiceItem->getQty();
                                $paidInvoiceItems[] = $invoiceItem->getId();
                        }
                    }
                    $options['giftcard_paid_invoice_items'] = $paidInvoiceItems;
                    break;
                default:
                    $qty = $item->getQtyOrdered();
                    if (isset($options['giftcard_created_codes'])) {
                        $qty -= count($options['giftcard_created_codes']);
                    }
                    break;
            }

            $hasFailedCodes = false;
            if ($qty > 0) {
                $isRedeemable = 0;
                if ($option = $item->getProductOptionByCode('giftcard_is_redeemable')) {
                    $isRedeemable = $option;
                }

                $lifetime = 0;
                if ($option = $item->getProductOptionByCode('giftcard_lifetime')) {
                    $lifetime = $option;
                }

                $amount = $item->getBasePrice();
                $websiteId = Mage::app()->getStore($order->getStoreId())->getWebsiteId();

                $data = new Varien_Object();
                $data->setWebsiteId($websiteId)
                    ->setAmount($amount)
                    ->setLifetime($lifetime)
                    ->setIsRedeemable($isRedeemable)
                    ->setOrderItem($item);

                $codes = (isset($options['giftcard_created_codes']) ?
                    $options['giftcard_created_codes'] : array());
                $goodCodes = 0;
                for ($i = 0; $i < $qty; $i++) {
                    try {
                        $code = new Varien_Object();
                        Mage::dispatchEvent('enterprise_giftcardaccount_create',
                            array('request'=>$data, 'code'=>$code));
                        $codes[] = $code->getCode();
                        $goodCodes++;
                    } catch (Mage_Core_Exception $e) {
                        $hasFailedCodes = true;
                        $codes[] = null;
                    }
                }
                if ($goodCodes && $item->getProductOptionByCode('giftcard_recipient_email')) {
                    $sender = $item->getProductOptionByCode('giftcard_sender_name');
                    $senderName = $item->getProductOptionByCode('giftcard_sender_name');
                    if ($senderEmail = $item->getProductOptionByCode('giftcard_sender_email')) {
                        $sender = "$sender <$senderEmail>";
                    }

                    $codeList = Mage::helper('enterprise_giftcard')->getEmailGeneratedItemsBlock()
                        ->setCodes($codes)
                        ->setIsRedeemable($isRedeemable)
                        ->setStore(Mage::app()->getStore($order->getStoreId()));
                    $balance = Mage::app()->getLocale()->currency(
                        Mage::app()->getStore($order->getStoreId())
                        ->getBaseCurrencyCode())->toCurrency($amount);

                    $templateData = array(
                        'name'                   => $item->getProductOptionByCode('giftcard_recipient_name'),
                        'email'                  => $item->getProductOptionByCode('giftcard_recipient_email'),
                        'sender_name_with_email' => $sender,
                        'sender_name'            => $senderName,
                        'gift_message'           => $item->getProductOptionByCode('giftcard_message'),
                        'giftcards'              => $codeList->toHtml(),
                        'balance'                => $balance,
                        'is_multiple_codes'      => 1 < $goodCodes,
                        'store'                  => $order->getStore(),
                        'store_name'             => $order->getStore()->getName(),//@deprecated after 1.4.0.0-beta1
                        'is_redeemable'          => $isRedeemable,
                    );

                    $email = Mage::getModel('core/email_template')
                        ->setDesignConfig(array('store' => $item->getOrder()->getStoreId()));
                    $email->sendTransactional(
                        $item->getProductOptionByCode('giftcard_email_template'),
                        Mage::getStoreConfig(
                            Enterprise_GiftCard_Model_Giftcard::XML_PATH_EMAIL_IDENTITY,
                            $item->getOrder()->getStoreId()),
                        $item->getProductOptionByCode('giftcard_recipient_email'),
                        $item->getProductOptionByCode('giftcard_recipient_name'),
                        $templateData
                    );

                    if ($email->getSentSuccess()) {
                        $options['email_sent'] = 1;
                    }
                }
                $options['giftcard_created_codes'] = $codes;
                $item->setProductOptions($options);
                $item->save();
            }
            if ($hasFailedCodes) {
                $url = Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/giftcardaccount');
                $message = Mage::helper('enterprise_giftcard')->__('Some of Gift Card Accounts were not generated properly. You can create Gift Card Accounts manually <a href="%s">here</a>.', $url);

                Mage::getSingleton('adminhtml/session')->addError($message);
            }
        }
    }

    return $this;
}

}

Well i am not doing any changes in above function i have just copied it from Enterprise/GiftCard/Model/Observer.php for further changes. Now when i process a giftcard order, every thing is working correct except the giftcard email which i am receiving just after generating the invoice from admin (completing order processing). Gift card email contain all the information except Giftcard code.

I wounder how the same function (without any change) is not working correctly after overriding it in a local module ?

| improve this question | | | | |
  • Please post all your code either here, or in a github gist, I will download it and debug it =] – Jeffrey L. Roberts May 5 '13 at 15:03
  • "Override" is a little vague here. If you describe the technique you used to do this it may shed light on the problem. – Alan Storm May 6 '13 at 6:17
  • @JeffreyL.Roberts : I have updated the code here. – Abhijeet kumar sharma May 6 '13 at 22:08
  • @AlanStorm : I am great fan of you. I love your blog. I have updated the overall code i hope this may shade some light. – Abhijeet kumar sharma May 6 '13 at 22:11
2

I was able to receive the gift card numbers after I generated the invoice...

Make sure in the settings that

  • Your gift card product has been created
  • That your gift card product is enabled
  • Your inventory quantity for your gift card is > 0
  • That you have generated your giftcard code pool

Also, Make sure you have similar code to the following

app/etc/modules/JLR_Giftcarder.xml

<?xml version="1.0"?>
<config>
    <modules>
        <JLR_Giftcarder>
            <active>true</active>
            <codePool>local</codePool>
        </JLR_Giftcarder>
    </modules>
</config>

app/code/local/JLR/Giftcard/etc/config.xml

<?xml version="1.0" encoding="utf-8"?>
<config>
    <modules>
        <JLR_Giftcarder>
            <version>0.1.0</version>
        </JLR_Giftcarder>
    </modules>
    <global>
        <models>
            <jlr_giftcarder>
                <class>JLR_Giftcarder_Model</class>
            </jlr_giftcarder>
            <enterprise_giftcard>
                <rewrite>
                    <observer>JLR_Giftcarder_Model_Observer</observer>
                </rewrite>
            </enterprise_giftcard>
        </models>
     </global>
</config>

app/code/local/JLR/Giftcarder/Model/Observer.php

<?php

class JLR_Giftcarder_Model_Observer extends Enterprise_GiftCard_Model_Observer
{
 /**
 * Generate gift card accounts after order save
 *
 * @param Varien_Event_Observer $observer
 * @return Enterprise_GiftCard_Model_Observer
 */
public function generateGiftCardAccounts(Varien_Event_Observer $observer)
{
    // sales_order_save_after

    $order = $observer->getEvent()->getOrder();
    $requiredStatus = Mage::getStoreConfig(
        Enterprise_GiftCard_Model_Giftcard::XML_PATH_ORDER_ITEM_STATUS,
        $order->getStore());
    $loadedInvoices = array();

    foreach ($order->getAllItems() as $item) {
        if ($item->getProductType() == Enterprise_GiftCard_Model_Catalog_Product_Type_Giftcard::TYPE_GIFTCARD) {
            $qty = 0;
            $options = $item->getProductOptions();

            switch ($requiredStatus) {
                case Mage_Sales_Model_Order_Item::STATUS_INVOICED:
                    $paidInvoiceItems = (isset($options['giftcard_paid_invoice_items'])
                        ? $options['giftcard_paid_invoice_items']
                        : array());
                    // find invoice for this order item
                    $invoiceItemCollection = Mage::getResourceModel('sales/order_invoice_item_collection')
                        ->addFieldToFilter('order_item_id', $item->getId());

                    foreach ($invoiceItemCollection as $invoiceItem) {
                        $invoiceId = $invoiceItem->getParentId();
                        if (isset($loadedInvoices[$invoiceId])) {
                            $invoice = $loadedInvoices[$invoiceId];
                        } else {
                            $invoice = Mage::getModel('sales/order_invoice')
                                ->load($invoiceId);
                            $loadedInvoices[$invoiceId] = $invoice;
                        }
                        // check, if this order item has been paid
                        if ($invoice->getState() == Mage_Sales_Model_Order_Invoice::STATE_PAID &&
                            !in_array($invoiceItem->getId(), $paidInvoiceItems)
                        ) {
                                $qty += $invoiceItem->getQty();
                                $paidInvoiceItems[] = $invoiceItem->getId();
                        }
                    }
                    $options['giftcard_paid_invoice_items'] = $paidInvoiceItems;
                    break;
                default:
                    $qty = $item->getQtyOrdered();
                    if (isset($options['giftcard_created_codes'])) {
                        $qty -= count($options['giftcard_created_codes']);
                    }
                    break;
            }

            $hasFailedCodes = false;
            if ($qty > 0) {
                $isRedeemable = 0;
                if ($option = $item->getProductOptionByCode('giftcard_is_redeemable')) {
                    $isRedeemable = $option;
                }

                $lifetime = 0;
                if ($option = $item->getProductOptionByCode('giftcard_lifetime')) {
                    $lifetime = $option;
                }

                $amount = $item->getBasePrice();
                $websiteId = Mage::app()->getStore($order->getStoreId())->getWebsiteId();

                $data = new Varien_Object();
                $data->setWebsiteId($websiteId)
                    ->setAmount($amount)
                    ->setLifetime($lifetime)
                    ->setIsRedeemable($isRedeemable)
                    ->setOrderItem($item);

                $codes = (isset($options['giftcard_created_codes']) ?
                    $options['giftcard_created_codes'] : array());
                $goodCodes = 0;
                for ($i = 0; $i < $qty; $i++) {
                    try {
                        $code = new Varien_Object();
                        Mage::dispatchEvent('enterprise_giftcardaccount_create',
                            array('request'=>$data, 'code'=>$code));
                        $codes[] = $code->getCode();
                        $goodCodes++;
                    } catch (Mage_Core_Exception $e) {
                        $hasFailedCodes = true;
                        $codes[] = null;
                    }
                }
                if ($goodCodes && $item->getProductOptionByCode('giftcard_recipient_email')) {
                    $sender = $item->getProductOptionByCode('giftcard_sender_name');
                    $senderName = $item->getProductOptionByCode('giftcard_sender_name');
                    if ($senderEmail = $item->getProductOptionByCode('giftcard_sender_email')) {
                        $sender = "$sender <$senderEmail>";
                    }

                    $codeList = Mage::helper('enterprise_giftcard')->getEmailGeneratedItemsBlock()
                        ->setCodes($codes)
                        ->setIsRedeemable($isRedeemable)
                        ->setStore(Mage::app()->getStore($order->getStoreId()));
                    $balance = Mage::app()->getLocale()->currency(
                        Mage::app()->getStore($order->getStoreId())
                        ->getBaseCurrencyCode())->toCurrency($amount);

                    $templateData = array(
                        'name'                   => $item->getProductOptionByCode('giftcard_recipient_name'),
                        'email'                  => $item->getProductOptionByCode('giftcard_recipient_email'),
                        'sender_name_with_email' => $sender,
                        'sender_name'            => $senderName,
                        'gift_message'           => $item->getProductOptionByCode('giftcard_message'),
                        'giftcards'              => $codeList->toHtml(),
                        'balance'                => $balance,
                        'is_multiple_codes'      => 1 < $goodCodes,
                        'store'                  => $order->getStore(),
                        'store_name'             => $order->getStore()->getName(),//@deprecated after 1.4.0.0-beta1
                        'is_redeemable'          => $isRedeemable,
                    );

                    $email = Mage::getModel('core/email_template')
                        ->setDesignConfig(array('store' => $item->getOrder()->getStoreId()));
                    $email->sendTransactional(
                        $item->getProductOptionByCode('giftcard_email_template'),
                        Mage::getStoreConfig(
                            Enterprise_GiftCard_Model_Giftcard::XML_PATH_EMAIL_IDENTITY,
                            $item->getOrder()->getStoreId()),
                        $item->getProductOptionByCode('giftcard_recipient_email'),
                        $item->getProductOptionByCode('giftcard_recipient_name'),
                        $templateData
                    );

                    if ($email->getSentSuccess()) {
                        $options['email_sent'] = 1;
                    }
                }
                $options['giftcard_created_codes'] = $codes;
                $item->setProductOptions($options);
                $item->save();
            }
            if ($hasFailedCodes) {
                $url = Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/giftcardaccount');
                $message = Mage::helper('enterprise_giftcard')->__('Some of Gift Card Accounts were not generated properly. You can create Gift Card Accounts manually <a href="%s">here</a>.', $url);

                Mage::getSingleton('adminhtml/session')->addError($message);
            }
        }
    }

    return $this;
}

}
| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.