Habilitar las notificaciones vía email de los comentarios sobre los productos en Prestashop 1.6

08 diciembre, 2014 |

Si te gusta, compártelo ;)

Introducción

Es fustrante y laborioso tener que consultar cada día el módulo de comentarios para comprobar si tenemos un nuevo comentario de algún cliente.

Para ahorraros esta labor, he creado este tutorial para habilitar notificaciones (vía email) cada vez que se haga un comentario sobre un producto en nuestra tienda.

La idea es, que cuando un cliente haga un comentario desde la "Página de Producto" sobre un determinado artículo, recibamos un email avisándonos del mismo, ahorrándonos la tediosa tarea de tener que comprobar si tenemos mensajes desde la configuración del módulo de comentarios.


Compatibilidad: Prestashop 1.5, y 1.6

Descargar los archivos del proyecto

A pesar de que este tutorial trata sobre Prestashop 1.6, también es posible hacerlo con Prestashop 1.5. Para hacerlo con la versión 1.5 tendremos que utilizar una plantilla de email correspondiente a esta versión. Más adelante veremos esto.

Vamos a trabajar con el archivo default.php perteneciente al módulo de comentarios, y necesitaremos crear dos plantillas de email en prestashop/mails/*el-idioma. Comencemos!

El controlador del módulo de comentarios

Debemos editar el archivo default.php que se encuentra en la ruta prestashop/modules/productcomments/controllers/front

Abramos el archivo con nuestro editor de código y busquemos el método ajaxProcessAddComment()

Este método es el encargado de enviar el comentario, y es en este método donde tenemos que insertar el código para habilitar los emails.

Así que, busquemos esta línea (la segunda que hay en el método) $result = true;, y peguemos a continuación de ella el siguiente código:

// Enviar e-mail

    $product_name = Product::getProductName($comment->id_product);
    $shop_email = Configuration::get('PS_SHOP_EMAIL');
    $shop_name = Configuration::get('PS_SHOP_NAME');

    Mail::Send(Configuration::get('PS_LANG_DEFAULT'), 'nuevo_comentario', Mail::l('Nuevo comentario en su tienda'),
    array(
     '{comment_content}' => $comment->content,
     '{product_name}' => $product_name
    ), $shop_email,
     $shop_name, $shop_email);
    

    Tools::clearCache(Context::getContext()->smarty, $this->getTemplatePath('productcomments-reviews.tpl'));

Quedando así:

protected function ajaxProcessAddComment()
 {
  $module_instance = new ProductComments();

  $result = true;
  $id_guest = 0;
  $id_customer = $this->context->customer->id;
  if (!$id_customer)
   $id_guest = $this->context->cookie->id_guest;

  $errors = array();
  // Validation
  if (!Validate::isInt(Tools::getValue('id_product')))
   $errors[] = $module_instance->l('ID product is incorrect');
  if (!Tools::getValue('title') || !Validate::isGenericName(Tools::getValue('title')))
   $errors[] = $module_instance->l('Title is incorrect');
  if (!Tools::getValue('content') || !Validate::isMessage(Tools::getValue('content')))
   $errors[] = $module_instance->l('Comment is incorrect');
  if (!$id_customer && (!Tools::isSubmit('customer_name') || !Tools::getValue('customer_name') || !Validate::isGenericName(Tools::getValue('customer_name'))))
   $errors[] = $module_instance->l('Customer name is incorrect');
  if (!$this->context->customer->id && !Configuration::get('PRODUCT_COMMENTS_ALLOW_GUESTS'))
   $errors[] = $module_instance->l('You must be logged in order to send a comment');
  if (!count(Tools::getValue('criterion')))
   $errors[] = $module_instance->l('You must give a rating');

  $product = new Product(Tools::getValue('id_product'));
  if (!$product->id)
   $errors[] = $module_instance->l('Product not found');

  if (!count($errors))
  {
   $customer_comment = ProductComment::getByCustomer(Tools::getValue('id_product'), $id_customer, true, $id_guest);
   if (!$customer_comment || ($customer_comment && (strtotime($customer_comment['date_add']) + Configuration::get('PRODUCT_COMMENTS_MINIMAL_TIME')) < time()))
   {

    $comment = new ProductComment();
    $comment->content = strip_tags(Tools::getValue('content'));
    $comment->id_product = (int)Tools::getValue('id_product');
    $comment->id_customer = (int)$id_customer;
    $comment->id_guest = $id_guest;
    $comment->customer_name = Tools::getValue('customer_name');
    if (!$comment->customer_name)
     $comment->customer_name = pSQL($this->context->customer->firstname.' '.$this->context->customer->lastname);
    $comment->title = Tools::getValue('title');
    $comment->grade = 0;
    $comment->validate = 0;
    $comment->save();

    $grade_sum = 0;
    foreach(Tools::getValue('criterion') as $id_product_comment_criterion => $grade)
    {
     $grade_sum += $grade;
     $product_comment_criterion = new ProductCommentCriterion($id_product_comment_criterion);
     if ($product_comment_criterion->id)
      $product_comment_criterion->addGrade($comment->id, $grade);
    }

    if (count(Tools::getValue('criterion')) >= 1)
    {
     $comment->grade = $grade_sum / count(Tools::getValue('criterion'));
     // Update Grade average of comment
     $comment->save();
    }
    $result = true;
    
    // Enviar e-mail

    $product_name = Product::getProductName($comment->id_product);
    $shop_email = Configuration::get('PS_SHOP_EMAIL');
    $shop_name = Configuration::get('PS_SHOP_NAME');

    Mail::Send(Configuration::get('PS_LANG_DEFAULT'), 'nuevo_comentario', Mail::l('Nuevo comentario en su tienda'),
    array(
     '{comment_content}' => $comment->content,
     '{product_name}' => $product_name
    ), $shop_email,
     $shop_name, $shop_email);
    

    Tools::clearCache(Context::getContext()->smarty, $this->getTemplatePath('productcomments-reviews.tpl'));
   }
   else
   {
    $result = false;
    $errors[] = $module_instance->l('You should wait').' '.Configuration::get('PRODUCT_COMMENTS_MINIMAL_TIME').' '.$module_instance->l('seconds before posting a new comment');
   }
  }
  else
   $result = false;

  die(Tools::jsonEncode(array(
   'result' => $result,
   'errors' => $errors
  )));
 }

Explicación del código insertado:

Necesitamos algunas variables para pasarlas como parámetros al método Send(). Por medio de estas variables obtendremos el nombre del producto, el email de la tienda y el nombre de la tienda.

Los parámetros del método Send() que aquí vemos son:
El idioma predeterminado de la tienda, el nombre de la plantilla, el asunto del mensaje, las variables de la plantilla (contenido del comentario y nombre del producto), el destinatario, el nombre de la tienda y el emisor del email

Mail::Send(Configuration::get('PS_LANG_DEFAULT'), 'nuevo_comentario', Mail::l('Nuevo comentario en su tienda'),
    array(
     '{comment_content}' => $comment->content,
     '{product_name}' => $product_name
    ), $shop_email,
     $shop_name, $shop_email);

Ya hemos terminado con este archivo!, ahora vamos a crear las plantillas.

Creando las plantillas de email

Necesitamos crear dos archivos en prestashop/mails/lenguaje-tienda. Un archivo será de tipo .html y el otro un .txt
Vamos a crear primero el archivo nuevo_comentario.html en la ruta mencionada. Pegar este código en el archivo:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
  <title>Message from {shop_name}</title>

 <style> @media only screen and (max-width: 300px){ 
  body {
  width:218px !important;
  margin:auto !important;
  }
  .table {width:195px !important;margin:auto !important;}
  .logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto !important;display: block !important;} 
  span.title{font-size:20px !important;line-height: 23px !important}
  span.subtitle{font-size: 14px !important;line-height: 18px !important;padding-top:10px !important;display:block !important;} 
  td.box p{font-size: 12px !important;font-weight: bold !important;}
  .table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr { 
  display: block !important; 
  }
  .table-recap{width: 200px!important;}
  .table-recap tr td, .conf_body td{text-align:center !important;} 
  .address{display: block !important;margin-bottom: 10px !important;}
  .space_address{display: none !important;} 
  }
  @media only screen and (min-width: 301px) and (max-width: 500px) { 
  body {width:308px!important;margin:auto!important;}
  .table {width:285px!important;margin:auto!important;} 
  .logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;} 
  .table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr { 
  display: block !important; 
  }
  .table-recap{width: 293px !important;}
  .table-recap tr td, .conf_body td{text-align:center !important;}
  
  }
  @media only screen and (min-width: 501px) and (max-width: 768px) {
  body {width:478px!important;margin:auto!important;}
  .table {width:450px!important;margin:auto!important;} 
  .logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;} 
  }
  @media only screen and (max-device-width: 480px) { 
  body {width:308px!important;margin:auto!important;}
  .table {width:285px;margin:auto!important;} 
  .logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
  
  .table-recap{width: 285px!important;}
  .table-recap tr td, .conf_body td{text-align:center!important;} 
  .address{display: block !important;margin-bottom: 10px !important;}
  .space_address{display: none !important;} 
  }
  </style>
 </head>
  <body style="-webkit-text-size-adjust:none;background-color:#fff;width:650px;font-family:Open-sans, sans-serif;color:#555454;font-size:13px;line-height:18px;margin:auto">
  <table class="table table-mail" style="width:100%;margin-top:10px;-moz-box-shadow:0 0 5px #afafaf;-webkit-box-shadow:0 0 5px #afafaf;-o-box-shadow:0 0 5px #afafaf;box-shadow:0 0 5px #afafaf;filter:progid:DXImageTransform.Microsoft.Shadow(color=#afafaf,Direction=134,Strength=5)">
  <tr>
  <td class="space" style="width:20px;padding:7px 0">&nbsp;</td>
  <td align="center" style="padding:7px 0">
  <table class="table" bgcolor="#ffffff" style="width:100%">
  <tr>
  <td align="center" class="logo" style="border-bottom:4px solid #333333;padding:7px 0">
  <a title="{shop_name}" href="{shop_url}" style="color:#337ff1">
  <img src="{shop_logo}" alt="{shop_name}" />
  </a>
  </td>
  </tr>
<tr>
  <td align="center" class="titleblock" style="padding:7px 0">
  <font size="2" face="Open-sans, sans-serif" color="#555454">
  <span class="title" style="font-weight:500;font-size:28px;text-transform:uppercase;line-height:33px">Hola!</span>
  </font>
  </td>
  </tr>
  <tr>
  <td class="space_footer" style="padding:0!important">&nbsp;</td>
  </tr>
  <tr>
  <td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0">
  <table class="table" style="width:100%">
  <tr>
  <td width="10" style="padding:7px 0">&nbsp;</td>
  <td style="padding:7px 0">
  <font size="2" face="Open-sans, sans-serif" color="#555454">
  <p data-html-only="1" style="border-bottom:1px solid #D6D4D4;margin:3px 0 7px;text-transform:uppercase;font-weight:500;font-size:18px;padding-bottom:10px">
  Ha recibido un comentario relativo al producto "{product_name}"      </p>
  <span style="color:#777">
  {comment_content}
  </span>
  </font>
  </td>
  <td width="10" style="padding:7px 0">&nbsp;</td>
  </tr>
  </table>
  </td>
  </tr>
 <tr>
  <td class="space_footer" style="padding:0!important">&nbsp;</td>
  </tr>
  <tr>
  <td class="footer" style="border-top:4px solid #333333;padding:7px 0">
  <span><a href="{shop_url}" style="color:#337ff1">{shop_name}</a> powered by <a href="http://www.prestashop.com/" style="color:#337ff1">PrestaShop&trade;</a></span>
  </td>
  </tr>
  </table>
  </td>
  <td class="space" style="width:20px;padding:7px 0">&nbsp;</td>
  </tr>
  </table>
  </body>
  </html>

A continuación, crearemos otro archivo llamado nuevo_comentario.txt y pegaremos el siguiente código en su interior:

[{shop_url}] 

Hola!,

Ha recibido un comentario relativo al producto "{product_name}"

{comment_content}
{shop_name} [{shop_url}] powered by
PrestaShop(tm) [http://www.prestashop.com/] 
Si estamos usando Prestashop 1.5, podemos tomar una plantilla de email predeterminada, como log_alert.html, copiar este archivo, modificarlo con la adición de las nuevas variables, y renombrarlo a "nuevo_comentario.html".

Y con esto hemos terminado, ya podemos probar si funciona! Suerte!

No hay comentarios: