Magento 1.9: Alertas de reposición de stock y alertas de precio

Una de las funcionalidades que ofrece Magento es que el usuario pueda suscribirse a alertas en productos. Bien sean alertas de modificación de precio (“productalert/price”) o de reposición de stocks (“productalert/stock”).

Para activar dicha funcionalidad, hay que ir a Sistema > Configuración > Catálogo > Catálogo:

alertas magento precio y stock

Y los productos (de los productos configurables hablaremos más adelante) pasan a mostrar dicha alerta:
alertas_magento_stock_price-23

Para ello, el theme debe llamar a:

<?php echo $this->getChildHtml('alert_urls') ?>

Y la plantilla por defecto que se ejecuta es productalert/product/view.phtml:

<?php /* @var $this Mage_ProductAlert_Block_Product_View */?>
<h1>Hello</h1>
<p class="<?php echo $this->getHtmlClass() ?>">
    <a href="<?php echo $this->escapeHtml($this->getSignupUrl()) ?>" title="<?php echo $this->escapeHtml($this->__($this->getSignupLabel())); ?>"><?php echo $this->escapeHtml($this->__($this->getSignupLabel())); ?></a>
</p>

En layout/productalert.xml encontramos la función a la que se llama (preparePriceAlertData o prepareStockAlertData):

<layout version="0.1.0">
    <catalog_product_view>
        <reference name="content">
            <reference name="product.info">
                <reference name="alert.urls">
                    <block type="productalert/product_view" name="productalert.price" as="productalert_price" template="productalert/product/view.phtml">
                        <action method="preparePriceAlertData"/>
                        <action method="setHtmlClass"><value>alert-price link-price-alert</value></action>
                        <action method="setSignupLabel" translate="value"><value>Sign up for price alert</value></action>
                    </block>
                    <block type="productalert/product_view" name="productalert.stock" as="productalert_stock" template="productalert/product/view.phtml">
                        <action method="prepareStockAlertData"/>
                        <action method="setHtmlClass"><value>alert-stock link-stock-alert</value></action>
                        <action method="setSignupLabel" translate="value"><value>Sign up to get notified when this product is back in stock</value></action>
                    </block>
                </reference>
            </reference>
        </reference>
    </catalog_product_view>
</layout>

Además, desde cada producto (Catálogo > Administrar producto), se puede ver quién se ha suscrito a cada alerta, en la pestaña “Alertas de producto”:

magento alerts

Estas alertas se almacenan internamente en la tabla product_alert_* (una para precio, otra para stock).

Si queremos obtener un informe con sumario, podemos hacer una query a las tablas anteriores o, si queremos verlo de forma gráfica, podemos instalar la extensión Amasty – Product Alert Reports (gratuita) https://amasty.com/product-alerts-reports.html y en Informes > Alerts dispondremos de la información de alertas a modo de sumario.

Para que los correos de alerta salgan, es necesario tener configurado CRON (+info aqui y aqui).

Hasta aqui, todo bien. Ahora, algunas dudas habituales:

¿Qué sucede si el cliente no está registrado y por tanto no se dispone de su email?
Si el cliente no está registrado, por defecto Magento le pide que se identifique para poder usar las alertas. No muestra un input donde el cliente no registrado pueda introducir su email para suscribirse a la alerta…

¿Qué sucede con los productos configurables?
Imaginemos que vendemos camisetas en tallas S,M,L. El producto “camiseta roja” será un prod configurable y los productos simples tendrán la variante de la talla. Sin embargo, Magento por defecto NO muestra el aviso de “Sign up to get notified when product is back in stock” en los productos configurables, aunque alguno de los productos simples asociados no esté en stock.

¿Puede el cliente registrado acceder desde su panel a la lista de suscripciones de stock y precio?
No, por defecto no puede. El código para mostrar las alertas de cada cliente sería algo asi:

/* LIST STOCK ALERTS */
$customer_id = Mage::getSingleton('customer/session')->getCustomer()->getId();
$customer_stock_alerts = Mage::getModel('productalert/stock')
         ->getCollection()
         ->addFieldToFilter('customer_id', $customer_id);
<p>foreach ( $customer_stock_alerts as $alert )
{
 echo $alert->getProductId();
}
 
/* LIST PRICE ALERTS */
$customer_id = Mage::getSingleton('customer/session')->getCustomer()->getId();
$customer_stock_alerts = Mage::getModel('productalert/price')
         ->getCollection()
         ->addFieldToFilter('customer_id', $customer_id);
<p>foreach ( $customer_stock_alerts as $alert )
{
 echo $alert->getProductId();
}

¿Cómo solucionar estas cuestiones, si no queremos ponernos a programar? Podemos comprar e instalar el módulo Amasty – Out of stock notification, que da solución a estas cuestiones: https://amasty.com/out-of-stock-notification.html

+info:
https://stackoverflow.com/questions/11648920/magento-show-sign-up-to-get-notified-when-this-product-is-back-in-stock-link-f
http://magento.stackexchange.com/questions/10989/cant-see-alert-urls-block-template
http://stackoverflow.com/questions/10810960/show-out-of-stock-for-configurable-products-in-magento
http://magento.stackexchange.com/questions/470/configurable-product-inventory-stock-availability-status-doesnt-change-when
http://stackoverflow.com/questions/5290868/how-would-test-cron-with-magento
http://merch.docs.magento.com/ee/user_guide/content/catalog/inventory-product-alert-run-settings.html
http://www.megamagento.com/2013/11/magento-product-stock-back-alerts-out.html

CDS Invenio: Internet Explorer 8, https, css and images not loading [SOLVED]

I have to admit I hate IE8. I do not use it except for testing that pages are displayed right. Some days ago a user wrote complaining about the visualization of Your options – Your submissions page: the CSS and images were not being loaded.

Internet Explorer 8 assumes that, in an SSL (https) connection, every element has to be loaded via HTTPS. If this does not happen, IE8 displays a security alert so that user can decide to load / not load the “insecure” elements.

The problem

I used httpwatch free basic version when loading the page and noticed the CSS url was starting with “http” and not “https”.

Altought mozilla does not complain about https pages loading http contents, IE8 does.

This is what happened when loading yoursubmissions.py page (the warning text is in spanish, sorry):

yoursubmissions.py issues with IE8

If you click “yes” none of the CSS nor the images are loaded and everything looks awful:

CDS Invenio, css and https

On the other side, if you hit “no” the page looks fine.

The fix

Samuele, from CDS Support Team, gave me a great advice: edit /var/www/yoursubmissions.py, look for the return page(..." line and add secure_page_p=1. This forces yoursubmissions function (defined in webstyle_templates.py) to load CSS via https.

Then run:

sudo -u apache /soft/cds-invenio/bin/inveniocfg --update-all; /etc/init.d/httpd restart

Cool! Now the CSS is working… but the gif’s won’t load. Shit!

Digging in webstyle_templates.py code (more precisely, I noticed that images were being loaded using CFG_SITE_URL instead of CFG_SITE_SECURE_URL in yoursubmissions function. So I added the CFG_SITE_SECURE_URL variable to the imports:

from invenio.config import \
     CFG_SITE_URL, \
     CFG_VERSION, \
     CFG_SITE_URL, \
     CFG_SITE_LANG, \
     CFG_SITE_SECURE_URL

and changed some CFG_SITE_URL to CFG_SITE_SECURE_URL in the image variable assignations. Then you must run:

sudo -u apache /soft/cds-invenio/bin/inveniocfg --update-all; /etc/init.d/httpd restart

I checked everything was working fine after this changes. It was, so I made something similar with:
yourapprobals.py
publiline.py
websession_weinterface.py
webbasket_templates.py
webalert_webinterface.py
webbasket_webinterface.py
webmessage_webinterface.py

I see the page correctly, but the IE8 warning is still showing up

Culprits? Some element(s) is (are) still referenced via HTTP and not HTTPS. You should use a sniffer (for instance, httpwatch) to check which are these elements.

One of the most common is Google analytics urchin file, which is usually loaded like:

<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>
<script type="text/javascript">
try {
  _uacct = "UA-6988718-1";
  urchinTracker();
} catch(err) {}</script>

And should be changed to:

<script src="https://ssl.google-analytics.com/urchin.js" type="text/javascript"></script>
<script type="text/javascript">
try {
  _uacct = "UA-6988718-1";
  urchinTracker();
} catch(err) {}</script>

(This lines are usually in your webstyle_templates_yoursitename.py).

*** 2010-03-12 UPDATE ***
The new google analytics code version (which calls ga.js) does this http/https thing on its own. In fact, here is an example of the call to ga.js (just like the one google provides). Thanks Samuele for pointing this out.

<script type="text/javascript">
 var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." 
: "http://www.");
 document.write(unescape("%3Cscript src='" + gaJsHost + 
"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
 </script>
 <script type="text/javascript">
 try{
 var pageTracker = _gat._getTracker("UA-xxxxxx-x");
 pageTracker._trackPageview();
 } catch(err) {}
</script>

After every change you must remember to run:

sudo -u apache /soft/cds-invenio/bin/inveniocfg --update-all; /etc/init.d/httpd restart

Hope it helps someone 😉