Jump to content

Mail alert pour un seul type de livraison


Recommended Posts

Bonjour

Sur un PS 1.6.1.7 une modif avait été faite pour que la notification de mailalerts ne soit envoyée à l'adresse donnée pour une nouvelle commande uniquement pour un type de livraison.
Je n'arrive pas à retrouver où. J'ai cherché dans tous les fichiers php du module mailalerts et je ne vois aucune condition.

Il n'y a pas d'override.

Quelqu'un pourrait-il me donner une piste ? Et-ce que cela pourrait avoir été ajouté à un controller ?

 

Merci d'avance

Link to comment
Share on other sites

Merci pour votre réponse mais de quelle classe associée parlez-vous ? Je suis tout autant dans le flou ! on m'a dit qu'un dev avait fait une modif pour que la notification de nouvelle commande ne soit envoyée que si le transporteur choisi était le retrait en magasin. J'ai fait la maj de 1.6.1.7 à 1.6.1.24 avant qu'on me le dise ... du coup cette modif a sauté.
J'essaie donc de la retrouver dans les fichiers du clone de l'ancienne installation. J'ai cherché dans tous les fichiers du module mailalerts en supposant qu'une condition avait été ajoutée, mais sans rien trouver.

J'ai cherché sur le Net pour voir si d'autres avaient fait une modif un peu similaire pour trouver une piste vers où me diriger, mais sans succès.

Link to comment
Share on other sites

il y a 23 minutes, doekia a dit :

Moi j'avais tiré un fil pour brancher mon autoradio, je veux l'enlever mais je sais plus où, vous pouvez m'aider?

:-) le hic, c'est que c'est pas moi qui ai tiré le fil du coup je cherche où on me l'a foutu ! :-)

Link to comment
Share on other sites

il y a 21 minutes, Eolia a dit :

image.png.dae4c49346fd1aa9f6522077ec3c1722.png

Eolia, j'ai cherché dans ces fichiers je ne trouve rien qui spécifierait un transporteur en particulier mais voilà le code de MailAlert.php

<?php
/**
 * 2007-2016 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 * @author    PrestaShop SA <[email protected]>
 * @copyright 2007-2016 PrestaShop SA
 * @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of PrestaShop SA
 */

class MailAlert extends ObjectModel
{
	public $id_customer;

	public $customer_email;

	public $id_product;

	public $id_product_attribute;

	public $id_shop;

	public $id_lang;

	/**
	 * @see ObjectModel::$definition
	 */
	public static $definition = array(
		'table' => 'mailalert_customer_oos',
		'primary' => 'id_customer',
		'fields' => array(
			'id_customer' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true),
			'customer_email' => array('type' => self::TYPE_STRING, 'validate' => 'isEmail', 'required' => true),
			'id_product' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true),
			'id_product_attribute' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true),
			'id_shop' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true),
			'id_lang' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true)
		),
	);

	public static function customerHasNotification($id_customer, $id_product, $id_product_attribute, $id_shop = null, $id_lang = null, $guest_email = '')
	{
		if ($id_shop == null)
			$id_shop = Context::getContext()->shop->id;

		if ($id_lang == null)
			$id_lang = Context::getContext()->language->id;

		$customer = new Customer($id_customer);
		$customer_email = $customer->email;
		$guest_email = pSQL($guest_email);

		$id_customer = (int)$id_customer;
		$customer_email = pSQL($customer_email);
		$where = $id_customer == 0 ? "customer_email = '$guest_email'" : "(id_customer=$id_customer OR customer_email='$customer_email')";
		$sql = '
			SELECT *
			FROM `'._DB_PREFIX_.self::$definition['table'].'`
			WHERE '.$where.'
			AND `id_product` = '.(int)$id_product.'
			AND `id_product_attribute` = '.(int)$id_product_attribute.'
			AND `id_shop` = '.(int)$id_shop;

		return count(Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql));
	}

	public static function deleteAlert($id_customer, $customer_email, $id_product, $id_product_attribute, $id_shop = null)
	{
		$sql = '
			DELETE FROM `'._DB_PREFIX_.self::$definition['table'].'`
			WHERE '.(($id_customer > 0) ? '(`customer_email` = \''.pSQL($customer_email).'\' OR `id_customer` = '.(int)$id_customer.')' :
				'`customer_email` = \''.pSQL($customer_email).'\'').
			' AND `id_product` = '.(int)$id_product.'
			AND `id_product_attribute` = '.(int)$id_product_attribute.'
			AND `id_shop` = '.($id_shop != null ? (int)$id_shop :(int)Context::getContext()->shop->id);

		return Db::getInstance()->execute($sql);
	}

	/*
	 * Get objects that will be viewed on "My alerts" page
	 */
	public static function getMailAlerts($id_customer, $id_lang, Shop $shop = null)
	{
		if (!Validate::isUnsignedId($id_customer) || !Validate::isUnsignedId($id_lang))
			die (Tools::displayError());

		if (!$shop)
			$shop = Context::getContext()->shop;

		$customer = new Customer($id_customer);
		$products = MailAlert::getProducts($customer, $id_lang);
		$products_number = count($products);

		if (empty($products) === true || !$products_number)
			return array();

		for ($i = 0; $i < $products_number; ++$i)
		{
			$obj = new Product((int)$products[$i]['id_product'], false, (int)$id_lang);
			if (!Validate::isLoadedObject($obj))
				continue;

			if (isset($products[$i]['id_product_attribute']) &&
				Validate::isUnsignedInt($products[$i]['id_product_attribute']))
			{
				$attributes = self::getProductAttributeCombination($products[$i]['id_product_attribute'], $id_lang);
				$products[$i]['attributes_small'] = '';

				if ($attributes)
				{
					foreach ($attributes as $row)
						$products[$i]['attributes_small'] .= $row['attribute_name'].', ';
				}

				$products[$i]['attributes_small'] = rtrim($products[$i]['attributes_small'], ', ');
				$products[$i]['id_shop'] = $shop->id;

				/* Get cover */
				$attrgrps = $obj->getAttributesGroups((int)$id_lang);
				foreach ($attrgrps as $attrgrp)
					if ($attrgrp['id_product_attribute'] == (int)$products[$i]['id_product_attribute']
						&& $images = Product::_getAttributeImageAssociations((int)$attrgrp['id_product_attribute']))
					{
						$products[$i]['cover'] = $obj->id.'-'.array_pop($images);
						break;
					}
			}

			if (!isset($products[$i]['cover']) || !$products[$i]['cover'])
			{
				$images = $obj->getImages((int)$id_lang);
				foreach ($images as $image)
					if ($image['cover'])
					{
						$products[$i]['cover'] = $obj->id.'-'.$image['id_image'];
						break;
					}
			}

			if (!isset($products[$i]['cover']))
				$products[$i]['cover'] = Language::getIsoById($id_lang).'-default';

			$products[$i]['link'] = $obj->getLink();
			$products[$i]['link_rewrite'] = $obj->link_rewrite;
		}

		return ($products);
	}

	public static function sendCustomerAlert($id_product, $id_product_attribute)
	{
		$link = new Link();
		$context = Context::getContext()->cloneContext();
		$customers = self::getCustomers($id_product, $id_product_attribute);

		foreach ($customers as $customer)
		{
			$id_shop = (int)$customer['id_shop'];
			$id_lang = (int)$customer['id_lang'];
			$context->shop->id = $id_shop;
			$context->language->id = $id_lang;

			$product = new Product((int)$id_product, false, $id_lang, $id_shop);
			$product_link = $link->getProductLink($product, $product->link_rewrite, null, null, $id_lang, $id_shop);
			$template_vars = array(
				'{product}' => (is_array($product->name) ? $product->name[$id_lang] : $product->name),
				'{product_link}' => $product_link
			);

			if ($customer['id_customer'])
			{
				$customer = new Customer((int)$customer['id_customer']);
				$customer_email = $customer->email;
				$customer_id = (int)$customer->id;
			}
			else
			{
				$customer_id = 0;
				$customer_email = $customer['customer_email'];
			}

			$iso = Language::getIsoById($id_lang);

			if (file_exists(dirname(__FILE__).'/mails/'.$iso.'/customer_qty.txt') &&
				file_exists(dirname(__FILE__).'/mails/'.$iso.'/customer_qty.html'))
				Mail::Send(
					$id_lang,
					'customer_qty',
					Mail::l('Product available', $id_lang),
					$template_vars,
					(string)$customer_email,
					null,
					(string)Configuration::get('PS_SHOP_EMAIL', null, null, $id_shop),
					(string)Configuration::get('PS_SHOP_NAME', null, null, $id_shop),
					null,
					null,
					dirname(__FILE__).'/mails/',
					false,
					$id_shop
				);

			Hook::exec(
				'actionModuleMailAlertSendCustomer',
				array('product' => (is_array($product->name) ? $product->name[$id_lang] : $product->name),
				'link' => $product_link,
				'customer' => $customer,
				'product_obj' => $product)
			);

			self::deleteAlert((int)$customer_id, (string)$customer_email, (int)$id_product, (int)$id_product_attribute, $id_shop);
		}
	}

	/*
	 * Generate correctly the address for an email
	 */
	public static function getFormatedAddress(Address $address, $line_sep, $fields_style = array())
	{
		return AddressFormat::generateAddress($address, array('avoid' => array()), $line_sep, ' ', $fields_style);
	}

	/*
	 * Get products according to alerts
	 */
	public static function getProducts($customer, $id_lang)
	{
		$list_shop_ids = Shop::getContextListShopID(false);

		$sql = '
			SELECT ma.`id_product`, p.`quantity` AS product_quantity, pl.`name`, ma.`id_product_attribute`
			FROM `'._DB_PREFIX_.self::$definition['table'].'` ma
			JOIN `'._DB_PREFIX_.'product` p ON (p.`id_product` = ma.`id_product`)
			'.Shop::addSqlAssociation('product', 'p').'
			LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (pl.`id_product` = p.`id_product` AND pl.id_shop IN ('.implode(', ', $list_shop_ids).'))
			WHERE product_shop.`active` = 1
			AND (ma.`id_customer` = '.(int)$customer->id.' OR ma.`customer_email` = \''.pSQL($customer->email).'\')
			AND pl.`id_lang` = '.(int)$id_lang.Shop::addSqlRestriction(false, 'ma');

		return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
	}

	/*
	 * Get product combinations
	 */
	public static function getProductAttributeCombination($id_product_attribute, $id_lang)
	{
		$sql = '
			SELECT al.`name` AS attribute_name
			FROM `'._DB_PREFIX_.'product_attribute_combination` pac
			LEFT JOIN `'._DB_PREFIX_.'attribute` a ON (a.`id_attribute` = pac.`id_attribute`)
			LEFT JOIN `'._DB_PREFIX_.'attribute_group` ag ON (ag.`id_attribute_group` = a.`id_attribute_group`)
			LEFT JOIN `'._DB_PREFIX_.'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute` AND al.`id_lang` = '.(int)$id_lang.')
			LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group` AND agl.`id_lang` = '.(int)$id_lang.')
			LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON (pac.`id_product_attribute` = pa.`id_product_attribute`)
			'.Shop::addSqlAssociation('product_attribute', 'pa').'
			WHERE pac.`id_product_attribute` = '.(int)$id_product_attribute;

		return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
	}

	/*
	 * Get customers waiting for alert on the specified product/product attribute
	 */
	public static function getCustomers($id_product, $id_product_attribute)
	{
		$sql = '
			SELECT id_customer, customer_email, id_shop, id_lang
			FROM `'._DB_PREFIX_.self::$definition['table'].'`
			WHERE `id_product` = '.(int)$id_product.' AND `id_product_attribute` = '.(int)$id_product_attribute;

		return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
	}
}

 

et celui de mailalert.php

 

<?php
/**
 * 2007-2016 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 * @author    PrestaShop SA <[email protected]>
 * @copyright 2007-2016 PrestaShop SA
 * @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of PrestaShop SA
 */

if (!defined('_CAN_LOAD_FILES_'))
	exit;

include_once(dirname(__FILE__).'/MailAlert.php');

class MailAlerts extends Module
{
	protected $html = '';

	protected $merchant_mails;
	protected $merchant_order;
	protected $merchant_oos;
	protected $customer_qty;
	protected $merchant_coverage;
	protected $product_coverage;
	protected $order_edited;
	protected $return_slip;

	const __MA_MAIL_DELIMITOR__ = "\n";

	public function __construct()
	{
		$this->name = 'mailalerts';
		$this->tab = 'administration';
		$this->version = '3.7.0';
		$this->author = 'PrestaShop';
		$this->need_instance = 0;

		$this->controllers = array('account');

		$this->bootstrap = true;
		parent::__construct();

		if ($this->id)
			$this->init();

		$this->displayName = $this->l('Mail alerts');
		$this->description = $this->l('Sends e-mail notifications to customers and merchants.');
		$this->confirmUninstall = $this->l('Are you sure you want to delete all customer notifications?');
	}

	protected function init()
	{
		$this->merchant_mails = str_replace(',', self::__MA_MAIL_DELIMITOR__, (string)Configuration::get('MA_MERCHANT_MAILS'));
		$this->merchant_order = (int)Configuration::get('MA_MERCHANT_ORDER');
		$this->merchant_oos = (int)Configuration::get('MA_MERCHANT_OOS');
		$this->customer_qty = (int)Configuration::get('MA_CUSTOMER_QTY');
		$this->merchant_coverage = (int)Configuration::getGlobalValue('MA_MERCHANT_COVERAGE');
		$this->product_coverage = (int)Configuration::getGlobalValue('MA_PRODUCT_COVERAGE');
		$this->order_edited = (int)Configuration::getGlobalValue('MA_ORDER_EDIT');
		$this->return_slip = (int)Configuration::getGlobalValue('MA_RETURN_SLIP');
	}

	public function install($delete_params = true)
	{
		if (!parent::install() ||
			!$this->registerHook('actionValidateOrder') ||
			!$this->registerHook('actionUpdateQuantity') ||
			!$this->registerHook('actionProductOutOfStock') ||
			!$this->registerHook('displayCustomerAccount') ||
			!$this->registerHook('displayMyAccountBlock') ||
			!$this->registerHook('actionProductDelete') ||
			!$this->registerHook('actionProductAttributeDelete') ||
			!$this->registerHook('actionProductAttributeUpdate') ||
			!$this->registerHook('actionProductCoverage') ||
			!$this->registerHook('actionOrderReturn') ||
			!$this->registerHook('actionOrderEdited') ||
			!$this->registerHook('registerGDPRConsent') ||
			!$this->registerHook('actionDeleteGDPRCustomer') ||
			!$this->registerHook('actionExportGDPRData') ||
			!$this->registerHook('displayHeader'))
			return false;

		if ($delete_params)
		{
			Configuration::updateValue('MA_MERCHANT_ORDER', 1);
			Configuration::updateValue('MA_MERCHANT_OOS', 1);
			Configuration::updateValue('MA_CUSTOMER_QTY', 1);
			Configuration::updateValue('MA_ORDER_EDIT', 1);
			Configuration::updateValue('MA_RETURN_SLIP', 1);
			Configuration::updateValue('MA_MERCHANT_MAILS', Configuration::get('PS_SHOP_EMAIL'));
			Configuration::updateValue('MA_LAST_QTIES', (int)Configuration::get('PS_LAST_QTIES'));
			Configuration::updateGlobalValue('MA_MERCHANT_COVERAGE', 0);
			Configuration::updateGlobalValue('MA_PRODUCT_COVERAGE', 0);

			$sql = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.MailAlert::$definition['table'].'`
				(
					`id_customer` int(10) unsigned NOT NULL,
					`customer_email` varchar(128) NOT NULL,
					`id_product` int(10) unsigned NOT NULL,
					`id_product_attribute` int(10) unsigned NOT NULL,
					`id_shop` int(10) unsigned NOT NULL,
					`id_lang` int(10) unsigned NOT NULL,
					PRIMARY KEY  (`id_customer`,`customer_email`,`id_product`,`id_product_attribute`,`id_shop`)
				) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';

			if (!Db::getInstance()->execute($sql))
				return false;
		}

		return true;
	}

	public function uninstall($delete_params = true)
	{
		if ($delete_params)
		{
			Configuration::deleteByName('MA_MERCHANT_ORDER');
			Configuration::deleteByName('MA_MERCHANT_OOS');
			Configuration::deleteByName('MA_CUSTOMER_QTY');
			Configuration::deleteByName('MA_MERCHANT_MAILS');
			Configuration::deleteByName('MA_LAST_QTIES');
			Configuration::deleteByName('MA_MERCHANT_COVERAGE');
			Configuration::deleteByName('MA_PRODUCT_COVERAGE');
			Configuration::deleteByName('MA_ORDER_EDIT');
			Configuration::deleteByName('MA_RETURN_SLIP');

			if (!Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.MailAlert::$definition['table']))
				return false;
		}

		return parent::uninstall();
	}

	public function reset()
	{
		if (!$this->uninstall(false))
			return false;
		if (!$this->install(false))
			return false;

		return true;
	}

	public function getContent()
	{
		$this->html = '';

		$this->postProcess();

		$this->html .= $this->renderForm();

		return $this->html;
	}

	protected function postProcess()
	{
		$errors = array();

		if (Tools::isSubmit('submitMailAlert'))
		{
			if (!Configuration::updateValue('MA_CUSTOMER_QTY', (int)Tools::getValue('MA_CUSTOMER_QTY')))
				$errors[] = $this->l('Cannot update settings');
		}
		else if (Tools::isSubmit('submitMAMerchant'))
		{
			$emails = (string)Tools::getValue('MA_MERCHANT_MAILS');

			if (!$emails || empty($emails))
				$errors[] = $this->l('Please type one (or more) e-mail address');
			else
			{
				$emails = str_replace(',', self::__MA_MAIL_DELIMITOR__, $emails);
				$emails = explode(self::__MA_MAIL_DELIMITOR__, $emails);
				foreach ($emails as $k => $email)
				{
					$email = trim($email);
					if (!empty($email) && !Validate::isEmail($email))
					{
						$errors[] = $this->l('Invalid e-mail:').' '.Tools::safeOutput($email);
						break;
					}
					elseif (!empty($email) && count($email) > 0)
						$emails[$k] = $email;
					else
						unset($emails[$k]);
				}

				$emails = implode(self::__MA_MAIL_DELIMITOR__, $emails);

				if (!Configuration::updateValue('MA_MERCHANT_MAILS', (string)$emails))
					$errors[] = $this->l('Cannot update settings');
				elseif (!Configuration::updateValue('MA_MERCHANT_ORDER', (int)Tools::getValue('MA_MERCHANT_ORDER')))
					$errors[] = $this->l('Cannot update settings');
				elseif (!Configuration::updateValue('MA_MERCHANT_OOS', (int)Tools::getValue('MA_MERCHANT_OOS')))
					$errors[] = $this->l('Cannot update settings');
				elseif (!Configuration::updateValue('MA_LAST_QTIES', (int)Tools::getValue('MA_LAST_QTIES')))
					$errors[] = $this->l('Cannot update settings');
				elseif (!Configuration::updateGlobalValue('MA_MERCHANT_COVERAGE', (int)Tools::getValue('MA_MERCHANT_COVERAGE')))
					$errors[] = $this->l('Cannot update settings');
				elseif (!Configuration::updateGlobalValue('MA_PRODUCT_COVERAGE', (int)Tools::getValue('MA_PRODUCT_COVERAGE')))
					$errors[] = $this->l('Cannot update settings');
				elseif (!Configuration::updateGlobalValue('MA_ORDER_EDIT', (int)Tools::getValue('MA_ORDER_EDIT')))
					$errors[] = $this->l('Cannot update settings');
				elseif (!Configuration::updateGlobalValue('MA_RETURN_SLIP', (int)Tools::getValue('MA_RETURN_SLIP')))
					$errors[] = $this->l('Cannot update settings');
			}
		}

		if (count($errors) > 0)
			$this->html .= $this->displayError(implode('<br />', $errors));
		else
			$this->html .= $this->displayConfirmation($this->l('Settings updated successfully'));

		$this->init();
	}

	public function getAllMessages($id)
	{
		$messages = Db::getInstance()->executeS('
			SELECT `message`
			FROM `'._DB_PREFIX_.'message`
			WHERE `id_order` = '.(int)$id.'
			ORDER BY `id_message` ASC');
		$result = array();
		foreach ($messages as $message)
			$result[] = $message['message'];

		return implode('<br/>', $result);
	}

	public function hookActionValidateOrder($params)
	{
		if (!$this->merchant_order || empty($this->merchant_mails))
			return;

		// Getting differents vars
		$context = Context::getContext();
		$id_lang = (int)$context->language->id;
		$id_shop = (int)$context->shop->id;
		$currency = $params['currency'];
		$order = $params['order'];
		$customer = $params['customer'];
		$configuration = Configuration::getMultiple(
			array(
				'PS_SHOP_EMAIL',
				'PS_MAIL_METHOD',
				'PS_MAIL_SERVER',
				'PS_MAIL_USER',
				'PS_MAIL_PASSWD',
				'PS_SHOP_NAME',
				'PS_MAIL_COLOR'
			), $id_lang, null, $id_shop
		);
		$delivery = new Address((int)$order->id_address_delivery);
		$invoice = new Address((int)$order->id_address_invoice);
		$order_date_text = Tools::displayDate($order->date_add);
		$carrier = new Carrier((int)$order->id_carrier);
		$message = $this->getAllMessages($order->id);

		if (!$message || empty($message))
			$message = $this->l('No message');

		$items_table = '';

		$products = $params['order']->getProducts();
		$customized_datas = Product::getAllCustomizedDatas((int)$params['cart']->id);
		Product::addCustomizationPrice($products, $customized_datas);
		foreach ($products as $key => $product)
		{
			$unit_price = Product::getTaxCalculationMethod($customer->id) == PS_TAX_EXC ? $product['product_price'] : $product['product_price_wt'];

			$customization_text = '';
			if (isset($customized_datas[$product['product_id']][$product['product_attribute_id']]))
			{
				foreach ($customized_datas[$product['product_id']][$product['product_attribute_id']][$order->id_address_delivery] as $customization)
				{
					if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD]))
						foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text)
							$customization_text .= $text['name'].': '.$text['value'].'<br />';

					if (isset($customization['datas'][Product::CUSTOMIZE_FILE]))
						$customization_text .= count($customization['datas'][Product::CUSTOMIZE_FILE]).' '.$this->l('image(s)').'<br />';

					$customization_text .= '---<br />';
				}
				if (method_exists('Tools', 'rtrimString'))
					$customization_text = Tools::rtrimString($customization_text, '---<br />');
				else
					$customization_text = preg_replace('/---<br \/>$/', '', $customization_text);
			}

			$url = $context->link->getProductLink($product['product_id']);
			$items_table .=
				'<tr style="background-color:'.($key % 2 ? '#DDE2E6' : '#EBECEE').';">
					<td style="padding:0.6em 0.4em;">'.$product['product_reference'].'</td>
					<td style="padding:0.6em 0.4em;">
						<strong><a href="'.$url.'">'.$product['product_name'].'</a>'
							.(isset($product['attributes_small']) ? ' '.$product['attributes_small'] : '')
							.(!empty($customization_text) ? '<br />'.$customization_text : '')
						.'</strong>
					</td>
					<td style="padding:0.6em 0.4em; text-align:right;">'.Tools::displayPrice($unit_price, $currency, false).'</td>
					<td style="padding:0.6em 0.4em; text-align:center;">'.(int)$product['product_quantity'].'</td>
					<td style="padding:0.6em 0.4em; text-align:right;">'
						.Tools::displayPrice(($unit_price * $product['product_quantity']), $currency, false)
					.'</td>
				</tr>';
		}
		foreach ($params['order']->getCartRules() as $discount)
		{
			$items_table .=
				'<tr style="background-color:#EBECEE;">
						<td colspan="4" style="padding:0.6em 0.4em; text-align:right;">'.$this->l('Voucher code:').' '.$discount['name'].'</td>
					<td style="padding:0.6em 0.4em; text-align:right;">-'.Tools::displayPrice($discount['value'], $currency, false).'</td>
			</tr>';
		}
		if ($delivery->id_state)
			$delivery_state = new State((int)$delivery->id_state);
		if ($invoice->id_state)
			$invoice_state = new State((int)$invoice->id_state);

		if (Product::getTaxCalculationMethod($customer->id) == PS_TAX_EXC)
			$total_products = $order->getTotalProductsWithoutTaxes();
		else
			$total_products = $order->getTotalProductsWithTaxes();

		$order_state = $params['orderStatus'];

		// Filling-in vars for email
		$template_vars = array(
			'{firstname}' => $customer->firstname,
			'{lastname}' => $customer->lastname,
			'{email}' => $customer->email,
			'{delivery_block_txt}' => MailAlert::getFormatedAddress($delivery, "\n"),
			'{invoice_block_txt}' => MailAlert::getFormatedAddress($invoice, "\n"),
			'{delivery_block_html}' => MailAlert::getFormatedAddress(
				$delivery, '<br />', array(
					'firstname' => '<span style="color:'.$configuration['PS_MAIL_COLOR'].'; font-weight:bold;">%s</span>',
					'lastname' => '<span style="color:'.$configuration['PS_MAIL_COLOR'].'; font-weight:bold;">%s</span>'
				)
			),
			'{invoice_block_html}' => MailAlert::getFormatedAddress(
				$invoice, '<br />', array(
					'firstname' => '<span style="color:'.$configuration['PS_MAIL_COLOR'].'; font-weight:bold;">%s</span>',
					'lastname' => '<span style="color:'.$configuration['PS_MAIL_COLOR'].'; font-weight:bold;">%s</span>'
				)
			),
			'{delivery_company}' => $delivery->company,
			'{delivery_firstname}' => $delivery->firstname,
			'{delivery_lastname}' => $delivery->lastname,
			'{delivery_address1}' => $delivery->address1,
			'{delivery_address2}' => $delivery->address2,
			'{delivery_city}' => $delivery->city,
			'{delivery_postal_code}' => $delivery->postcode,
			'{delivery_country}' => $delivery->country,
			'{delivery_state}' => $delivery->id_state ? $delivery_state->name : '',
			'{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile,
			'{delivery_other}' => $delivery->other,
			'{invoice_company}' => $invoice->company,
			'{invoice_firstname}' => $invoice->firstname,
			'{invoice_lastname}' => $invoice->lastname,
			'{invoice_address2}' => $invoice->address2,
			'{invoice_address1}' => $invoice->address1,
			'{invoice_city}' => $invoice->city,
			'{invoice_postal_code}' => $invoice->postcode,
			'{invoice_country}' => $invoice->country,
			'{invoice_state}' => $invoice->id_state ? $invoice_state->name : '',
			'{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile,
			'{invoice_other}' => $invoice->other,
			'{order_name}' => $order->reference,
			'{order_status}' => $order_state->name,
			'{shop_name}' => $configuration['PS_SHOP_NAME'],
			'{date}' => $order_date_text,
			'{carrier}' => (($carrier->name == '0') ? $configuration['PS_SHOP_NAME'] : $carrier->name),
			'{payment}' => Tools::substr($order->payment, 0, 32),
			'{items}' => $items_table,
			'{total_paid}' => Tools::displayPrice($order->total_paid, $currency),
			'{total_products}' => Tools::displayPrice($total_products, $currency),
			'{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency),
			'{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency),
			'{total_tax_paid}' => Tools::displayPrice(
				($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl),
				$currency,
				false
			),
			'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency),
			'{currency}' => $currency->sign,
			'{gift}' => (bool)$order->gift,
			'{gift_message}' => $order->gift_message,
			'{message}' => $message
		);

		// Shop iso
		$iso = Language::getIsoById((int)Configuration::get('PS_LANG_DEFAULT'));

		// Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients
		$merchant_mails = explode(self::__MA_MAIL_DELIMITOR__, $this->merchant_mails);
		foreach ($merchant_mails as $merchant_mail)
		{
			// Default language
			$mail_id_lang = $id_lang;
			$mail_iso = $iso;

			// Use the merchant lang if he exists as an employee
			$results = Db::getInstance()->executeS('
				SELECT `id_lang` FROM `'._DB_PREFIX_.'employee`
				WHERE `email` = \''.pSQL($merchant_mail).'\'
			');
			if ($results)
			{
				$user_iso = Language::getIsoById((int)$results[0]['id_lang']);
				if ($user_iso)
				{
					$mail_id_lang = (int)$results[0]['id_lang'];
					$mail_iso = $user_iso;
				}
			}

			$dir_mail = false;
			if (file_exists(dirname(__FILE__).'/mails/'.$mail_iso.'/new_order.txt') &&
				file_exists(dirname(__FILE__).'/mails/'.$mail_iso.'/new_order.html'))
				$dir_mail = dirname(__FILE__).'/mails/';

			if (file_exists(_PS_MAIL_DIR_.$mail_iso.'/new_order.txt') &&
				file_exists(_PS_MAIL_DIR_.$mail_iso.'/new_order.html'))
				$dir_mail = _PS_MAIL_DIR_;

			if ($dir_mail)
				Mail::Send(
					$mail_id_lang,
					'new_order',
					sprintf(Mail::l('New order : #%d - %s', $mail_id_lang), $order->id, $order->reference),
					$template_vars,
					$merchant_mail,
					null,
					$configuration['PS_SHOP_EMAIL'],
					$configuration['PS_SHOP_NAME'],
					null,
					null,
					$dir_mail,
					null,
					$id_shop
				);
		}
	}

	public function hookActionProductOutOfStock($params)
	{
		if (!$this->customer_qty ||
			!Configuration::get('PS_STOCK_MANAGEMENT') ||
			Product::isAvailableWhenOutOfStock($params['product']->out_of_stock))
			return;

		$context = Context::getContext();
		$id_product = (int)$params['product']->id;
		$id_product_attribute = 0;
		$id_customer = (int)$context->customer->id;

		if ((int)$context->customer->id <= 0)
			$this->context->smarty->assign('email', 1);
		elseif (MailAlert::customerHasNotification($id_customer, $id_product, $id_product_attribute, (int)$context->shop->id))
			return;

		$this->context->smarty->assign(
			array(
				'id_product' => $id_product,
				'id_product_attribute' => $id_product_attribute,
				'id_module' => $this->id
			)
		);

		return $this->display(__FILE__, 'product.tpl');
	}

	public function hookActionUpdateQuantity($params)
	{
		$id_product = (int)$params['id_product'];
		$id_product_attribute = (int)$params['id_product_attribute'];

		$quantity = (int)$params['quantity'];
		$context = Context::getContext();
		$id_shop = (int)$context->shop->id;
		$id_lang = (int)$context->language->id;
		$product = new Product($id_product, false, $id_lang, $id_shop, $context);
		$product_has_attributes = $product->hasAttributes();
		$configuration = Configuration::getMultiple(
			array(
				'MA_LAST_QTIES',
				'PS_STOCK_MANAGEMENT',
				'PS_SHOP_EMAIL',
				'PS_SHOP_NAME'
			), null, null, $id_shop
		);
		$ma_last_qties = (int)$configuration['MA_LAST_QTIES'];

		$check_oos = ($product_has_attributes && $id_product_attribute) || (!$product_has_attributes && !$id_product_attribute);

		if ($check_oos &&
			$product->active == 1 &&
			(int)$quantity <= $ma_last_qties &&
			!(!$this->merchant_oos || empty($this->merchant_mails)) &&
			$configuration['PS_STOCK_MANAGEMENT'])
		{
			$iso = Language::getIsoById($id_lang);
			$product_name = Product::getProductName($id_product, $id_product_attribute, $id_lang);
			$template_vars = array(
				'{qty}' => $quantity,
				'{last_qty}' => $ma_last_qties,
				'{product}' => $product_name
			);

			// Do not send mail if multiples product are created / imported.
			if (!defined('PS_MASS_PRODUCT_CREATION') &&
				file_exists(dirname(__FILE__).'/mails/'.$iso.'/productoutofstock.txt') &&
				file_exists(dirname(__FILE__).'/mails/'.$iso.'/productoutofstock.html'))
			{
				// Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients
				$merchant_mails = explode(self::__MA_MAIL_DELIMITOR__, $this->merchant_mails);
				foreach ($merchant_mails as $merchant_mail)
				{
					Mail::Send(
						$id_lang,
						'productoutofstock',
						Mail::l('Product out of stock', $id_lang),
						$template_vars,
						$merchant_mail,
						null,
						(string)$configuration['PS_SHOP_EMAIL'],
						(string)$configuration['PS_SHOP_NAME'],
						null,
						null,
						dirname(__FILE__).'/mails/',
						false,
						$id_shop
					);
				}
			}
		}

		if ($this->customer_qty && $quantity > 0)
			MailAlert::sendCustomerAlert((int)$product->id, (int)$params['id_product_attribute']);
	}

	public function hookActionProductAttributeUpdate($params)
	{
		$sql = '
			SELECT `id_product`, `quantity`
			FROM `'._DB_PREFIX_.'stock_available`
			WHERE `id_product_attribute` = '.(int)$params['id_product_attribute'];

		$result = Db::getInstance()->getRow($sql);

		if ($this->customer_qty && $result['quantity'] > 0)
			MailAlert::sendCustomerAlert((int)$result['id_product'], (int)$params['id_product_attribute']);
	}

	public function hookDisplayCustomerAccount()
	{
		return $this->customer_qty ? $this->display(__FILE__, 'my-account.tpl') : null;
	}

	public function hookDisplayMyAccountBlock($params)
	{
		return $this->hookDisplayCustomerAccount($params);
	}

	public function hookActionProductDelete($params)
	{
		$sql = '
			DELETE FROM `'._DB_PREFIX_.MailAlert::$definition['table'].'`
			WHERE `id_product` = '.(int)$params['product']->id;

		Db::getInstance()->execute($sql);
	}

	public function hookActionAttributeDelete($params)
	{
		if ($params['deleteAllAttributes'])
			$sql = '
				DELETE FROM `'._DB_PREFIX_.MailAlert::$definition['table'].'`
				WHERE `id_product` = '.(int)$params['id_product'];
		else
			$sql = '
				DELETE FROM `'._DB_PREFIX_.MailAlert::$definition['table'].'`
				WHERE `id_product_attribute` = '.(int)$params['id_product_attribute'].'
				AND `id_product` = '.(int)$params['id_product'];

		Db::getInstance()->execute($sql);
	}

	public function hookActionProductCoverage($params)
	{
		// if not advanced stock management, nothing to do
		if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'))
			return;

		// retrieves informations
		$id_product = (int)$params['id_product'];
		$id_product_attribute = (int)$params['id_product_attribute'];
		$warehouse = $params['warehouse'];
		$product = new Product($id_product);

		if (!Validate::isLoadedObject($product))
			return;

		if (!$product->advanced_stock_management)
			return;

		// sets warehouse id to get the coverage
		if (!Validate::isLoadedObject($warehouse))
			$id_warehouse = 0;
		else
			$id_warehouse = (int)$warehouse->id;

		// coverage of the product
		$warning_coverage = (int)Configuration::getGlobalValue('MA_PRODUCT_COVERAGE');

		$coverage = StockManagerFactory::getManager()->getProductCoverage($id_product, $id_product_attribute, $warning_coverage, $id_warehouse);

		// if we need to send a notification
		if ($product->active == 1 &&
			($coverage < $warning_coverage) && !empty($this->merchant_mails) &&
			Configuration::getGlobalValue('MA_MERCHANT_COVERAGE'))
		{
			$context = Context::getContext();
			$id_lang = (int)$context->language->id;
			$id_shop = (int)$context->shop->id;
			$iso = Language::getIsoById($id_lang);
			$product_name = Product::getProductName($id_product, $id_product_attribute, $id_lang);
			$template_vars = array(
				'{current_coverage}' => $coverage,
				'{warning_coverage}' => $warning_coverage,
				'{product}' => pSQL($product_name)
			);

			if (file_exists(dirname(__FILE__).'/mails/'.$iso.'/productcoverage.txt') &&
				file_exists(dirname(__FILE__).'/mails/'.$iso.'/productcoverage.html'))
			{
				// Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients
				$merchant_mails = explode(self::__MA_MAIL_DELIMITOR__, $this->merchant_mails);
				foreach ($merchant_mails as $merchant_mail)
				{
					Mail::Send(
						$id_lang,
						'productcoverage',
						Mail::l('Stock coverage', $id_lang),
						$template_vars,
						$merchant_mail,
						null,
						(string)Configuration::get('PS_SHOP_EMAIL'),
						(string)Configuration::get('PS_SHOP_NAME'),
						null,
						null,
						dirname(__FILE__).'/mails/',
						null,
						$id_shop
					);
				}
			}
		}
	}

	public function hookDisplayHeader()
	{
		$this->page_name = Dispatcher::getInstance()->getController();
		if (in_array($this->page_name, array('product', 'account')))
		{
			$this->context->controller->addJS($this->_path.'js/mailalerts.js');
			$this->context->controller->addCSS($this->_path.'css/mailalerts.css', 'all');
		}
	}

	/**
	 * Send a mail when a customer return an order.
	 *
	 * @param array $params Hook params.
	 */
	public function hookActionOrderReturn($params)
	{
		if (!$this->return_slip || empty($this->return_slip))
			return;

		$context = Context::getContext();
		$id_lang = (int)$context->language->id;
		$id_shop = (int)$context->shop->id;
		$configuration = Configuration::getMultiple(
			array(
				'PS_SHOP_EMAIL',
				'PS_MAIL_METHOD',
				'PS_MAIL_SERVER',
				'PS_MAIL_USER',
				'PS_MAIL_PASSWD',
				'PS_SHOP_NAME',
				'PS_MAIL_COLOR'
			), $id_lang, null, $id_shop
		);

		// Shop iso
		$iso = Language::getIsoById((int)Configuration::get('PS_LANG_DEFAULT'));

		$order = new Order((int)$params['orderReturn']->id_order);
		$customer = new Customer((int)$params['orderReturn']->id_customer);
		$delivery = new Address((int)$order->id_address_delivery);
		$invoice = new Address((int)$order->id_address_invoice);
		$order_date_text = Tools::displayDate($order->date_add);
		if ($delivery->id_state)
			$delivery_state = new State((int)$delivery->id_state);
		if ($invoice->id_state)
			$invoice_state = new State((int)$invoice->id_state);

		$order_return_products = OrderReturn::getOrdersReturnProducts($params['orderReturn']->id, $order);

		$items_table = '';
		foreach ($order_return_products as $key => $product)
		{
			$url = $context->link->getProductLink($product['product_id']);
			$items_table .=
				'<tr style="background-color:'.($key % 2 ? '#DDE2E6' : '#EBECEE').';">
					<td style="padding:0.6em 0.4em;">'.$product['product_reference'].'</td>
					<td style="padding:0.6em 0.4em;">
						<strong><a href="'.$url.'">'.$product['product_name'].'</a>
					</strong>
					</td>
					<td style="padding:0.6em 0.4em; text-align:center;">'.(int)$product['product_quantity'].'</td>
				</tr>';
		}

		$template_vars = array(
			'{firstname}' => $customer->firstname,
			'{lastname}' => $customer->lastname,
			'{email}' => $customer->email,
			'{delivery_block_txt}' => MailAlert::getFormatedAddress($delivery, "\n"),
			'{invoice_block_txt}' => MailAlert::getFormatedAddress($invoice, "\n"),
			'{delivery_block_html}' => MailAlert::getFormatedAddress(
				$delivery, '<br />', array(
					'firstname' => '<span style="color:'.$configuration['PS_MAIL_COLOR'].'; font-weight:bold;">%s</span>',
					'lastname' => '<span style="color:'.$configuration['PS_MAIL_COLOR'].'; font-weight:bold;">%s</span>'
				)
			),
			'{invoice_block_html}' => MailAlert::getFormatedAddress(
				$invoice, '<br />', array(
					'firstname' => '<span style="color:'.$configuration['PS_MAIL_COLOR'].'; font-weight:bold;">%s</span>',
					'lastname' => '<span style="color:'.$configuration['PS_MAIL_COLOR'].'; font-weight:bold;">%s</span>'
				)
			),
			'{delivery_company}' => $delivery->company,
			'{delivery_firstname}' => $delivery->firstname,
			'{delivery_lastname}' => $delivery->lastname,
			'{delivery_address1}' => $delivery->address1,
			'{delivery_address2}' => $delivery->address2,
			'{delivery_city}' => $delivery->city,
			'{delivery_postal_code}' => $delivery->postcode,
			'{delivery_country}' => $delivery->country,
			'{delivery_state}' => $delivery->id_state ? $delivery_state->name : '',
			'{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile,
			'{delivery_other}' => $delivery->other,
			'{invoice_company}' => $invoice->company,
			'{invoice_firstname}' => $invoice->firstname,
			'{invoice_lastname}' => $invoice->lastname,
			'{invoice_address2}' => $invoice->address2,
			'{invoice_address1}' => $invoice->address1,
			'{invoice_city}' => $invoice->city,
			'{invoice_postal_code}' => $invoice->postcode,
			'{invoice_country}' => $invoice->country,
			'{invoice_state}' => $invoice->id_state ? $invoice_state->name : '',
			'{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile,
			'{invoice_other}' => $invoice->other,
			'{order_name}' => $order->reference,
			'{shop_name}' => $configuration['PS_SHOP_NAME'],
			'{date}' => $order_date_text,
			'{items}' => $items_table,
			'{message}' => Tools::purifyHTML($params['orderReturn']->question),
		);

		// Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients
		$merchant_mails = explode(self::__MA_MAIL_DELIMITOR__, $this->merchant_mails);
		foreach ($merchant_mails as $merchant_mail)
		{
			// Default language
			$mail_id_lang = $id_lang;
			$mail_iso = $iso;

			// Use the merchant lang if he exists as an employee
			$results = Db::getInstance()->executeS('
				SELECT `id_lang` FROM `'._DB_PREFIX_.'employee`
				WHERE `email` = \''.pSQL($merchant_mail).'\'
			');
			if ($results)
			{
				$user_iso = Language::getIsoById((int)$results[0]['id_lang']);
				if ($user_iso)
				{
					$mail_id_lang = (int)$results[0]['id_lang'];
					$mail_iso = $user_iso;
				}
			}

			$dir_mail = false;
			if (file_exists(dirname(__FILE__).'/mails/'.$mail_iso.'/return_slip.txt') &&
				file_exists(dirname(__FILE__).'/mails/'.$mail_iso.'/return_slip.html'))
				$dir_mail = dirname(__FILE__).'/mails/';

			if (file_exists(_PS_MAIL_DIR_.$mail_iso.'/return_slip.txt') &&
				file_exists(_PS_MAIL_DIR_.$mail_iso.'/return_slip.html'))
				$dir_mail = _PS_MAIL_DIR_;

			if ($dir_mail)
				Mail::Send(
					$mail_id_lang,
					'return_slip',
					sprintf(Mail::l('New return from order #%d - %s', $mail_id_lang), $order->id, $order->reference),
					$template_vars,
					$merchant_mail,
					null,
					$configuration['PS_SHOP_EMAIL'],
					$configuration['PS_SHOP_NAME'],
					null,
					null,
					$dir_mail,
					null,
					$id_shop
				);
		}
	}


	/**
	 * Send a mail when an order is modified.
	 *
	 * @param array $params Hook params.
	 */
	public function hookActionOrderEdited($params)
	{
		if (!$this->order_edited || empty($this->order_edited))
			return;

		$order = $params['order'];

		$data = array(
			'{lastname}' => $order->getCustomer()->lastname,
			'{firstname}' => $order->getCustomer()->firstname,
			'{id_order}' => (int)$order->id,
			'{order_name}' => $order->getUniqReference()
		);
		$pos = strpos($order->getCustomer()->email, "amazon.fr");
		if ($pos === false)
		{
		Mail::Send(
			(int)$order->id_lang,
			'order_changed',
			Mail::l('Your order has been changed', (int)$order->id_lang),
			$data,
			$order->getCustomer()->email,
			$order->getCustomer()->firstname.' '.$order->getCustomer()->lastname,
			null, null, null, null, _PS_MAIL_DIR_, true, (int)$order->id_shop);
			
	}
	}

	public function hookActionDeleteGDPRCustomer($customer)
	{
		if (!empty($customer['email']) && Validate::isEmail($customer['email'])) {
			$sql = "DELETE FROM "._DB_PREFIX_."mailalert_customer_oos WHERE customer_email = '".pSQL($customer['email'])."'";
			if (Db::getInstance()->execute($sql)) {
				return json_encode(true);
			}
			return json_encode($this->l('Mail alert: Unable to delete customer using email.'));
		}
	}
	public function hookActionExportGDPRData($customer)
	{
		if (!Tools::isEmpty($customer['email']) && Validate::isEmail($customer['email'])) {
			$sql = "SELECT * FROM "._DB_PREFIX_."mailalert_customer_oos WHERE customer_email = '".pSQL($customer['email'])."'";
			if ($res = Db::getInstance()->ExecuteS($sql)) {
				return json_encode($res);
			}
			return json_encode($this->l('Mail alert: Unable to export customer using email.'));
		}
	}

	public function renderForm()
	{
		$fields_form_1 = array(
			'form' => array(
				'legend' => array(
					'title' => $this->l('Customer notifications'),
					'icon' => 'icon-cogs'
				),
				'input' => array(
					array(
						'type' => 'switch',
						'is_bool' => true, //retro compat 1.5
						'label' => $this->l('Product availability'),
						'name' => 'MA_CUSTOMER_QTY',
						'desc' => $this->l('Gives the customer the option of receiving a notification when an out-of-stock product is available again.'),
						'values' => array(
							array(
								'id' => 'active_on',
								'value' => 1,
								'label' => $this->l('Enabled')
							),
							array(
								'id' => 'active_off',
								'value' => 0,
								'label' => $this->l('Disabled')
							)
						),
					),
					array(
						'type' => 'switch',
						'is_bool' => true, //retro compat 1.5
						'label' => $this->l('Order edit'),
						'name' => 'MA_ORDER_EDIT',
						'desc' => $this->l('Send a notification to the customer when an order is edited.'),
						'values' => array(
							array(
								'id' => 'active_on',
								'value' => 1,
								'label' => $this->l('Enabled')
							),
							array(
								'id' => 'active_off',
								'value' => 0,
								'label' => $this->l('Disabled')
							)
						),
					),
				),
				'submit' => array(
					'title' => $this->l('Save'),
					'class' => 'btn btn-default pull-right',
					'name' => 'submitMailAlert',
				)
			),
		);

		$fields_form_2 = array(
			'form' => array(
				'legend' => array(
					'title' => $this->l('Merchant notifications'),
					'icon' => 'icon-cogs'
				),
				'input' => array(
					array(
						'type' => 'switch',
						'is_bool' => true, //retro compat 1.5
						'label' => $this->l('New order'),
						'name' => 'MA_MERCHANT_ORDER',
						'desc' => $this->l('Receive a notification when an order is placed.'),
						'values' => array(
							array(
								'id' => 'active_on',
								'value' => 1,
								'label' => $this->l('Enabled')
							),
							array(
								'id' => 'active_off',
								'value' => 0,
								'label' => $this->l('Disabled')
							)
						),
					),
					array(
						'type' => 'switch',
						'is_bool' => true, //retro compat 1.5
						'label' => $this->l('Out of stock'),
						'name' => 'MA_MERCHANT_OOS',
						'desc' => $this->l('Receive a notification if the available quantity of a product is below the following threshold.'),
						'values' => array(
							array(
								'id' => 'active_on',
								'value' => 1,
								'label' => $this->l('Enabled')
							),
							array(
								'id' => 'active_off',
								'value' => 0,
								'label' => $this->l('Disabled')
							)
						),
					),
					array(
						'type' => 'text',
						'label' => $this->l('Threshold'),
						'name' => 'MA_LAST_QTIES',
						'class' => 'fixed-width-xs',
						'desc' => $this->l('Quantity for which a product is considered out of stock.'),
					),
					array(
						'type' => 'switch',
						'is_bool' => true, //retro compat 1.5
						'label' => $this->l('Coverage warning'),
						'name' => 'MA_MERCHANT_COVERAGE',
						'desc' => $this->l('Receive a notification when a product has insufficient coverage.'),
						'values' => array(
							array(
								'id' => 'active_on',
								'value' => 1,
								'label' => $this->l('Enabled')
							),
							array(
								'id' => 'active_off',
								'value' => 0,
								'label' => $this->l('Disabled')
							)
						),
					),
					array(
						'type' => 'text',
						'label' => $this->l('Coverage'),
						'name' => 'MA_PRODUCT_COVERAGE',
						'class' => 'fixed-width-xs',
						'desc' => $this->l('Stock coverage, in days. Also, the stock coverage of a given product will be calculated based on this number.'),
					),
					array(
						'type' => 'switch',
						'is_bool' => true, //retro compat 1.5
						'label' => $this->l('Returns'),
						'name' => 'MA_RETURN_SLIP',
						'desc' => $this->l('Receive a notification when a customer requests a merchandise return.'),
						'values' => array(
							array(
								'id' => 'active_on',
								'value' => 1,
								'label' => $this->l('Enabled')
							),
							array(
								'id' => 'active_off',
								'value' => 0,
								'label' => $this->l('Disabled')
							)
						),
					),
					array(
						'type' => 'textarea',
						'cols' => 36,
						'rows' => 4,
						'label' => $this->l('E-mail addresses'),
						'name' => 'MA_MERCHANT_MAILS',
						'desc' => $this->l('One e-mail address per line (e.g. [email protected]).'),
					),
				),
				'submit' => array(
					'title' => $this->l('Save'),
					'class' => 'btn btn-default pull-right',
					'name' => 'submitMAMerchant',
				)
			),
		);

		$helper = new HelperForm();
		$helper->show_toolbar = false;
		$helper->table = $this->table;
		$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
		$helper->default_form_language = $lang->id;
		$helper->module = $this;
		$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
		$helper->identifier = $this->identifier;
		$helper->submit_action = 'submitMailAlertConfiguration';
		$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
			.'&configure='.$this->name
			.'&tab_module='.$this->tab
			.'&module_name='.$this->name;
		$helper->token = Tools::getAdminTokenLite('AdminModules');
		$helper->tpl_vars = array(
			'fields_value' => $this->getConfigFieldsValues(),
			'languages' => $this->context->controller->getLanguages(),
			'id_language' => $this->context->language->id
		);

		return $helper->generateForm(array($fields_form_1, $fields_form_2));
	}

	public function getConfigFieldsValues()
	{
		return array(
			'MA_CUSTOMER_QTY' => Tools::getValue('MA_CUSTOMER_QTY', Configuration::get('MA_CUSTOMER_QTY')),
			'MA_MERCHANT_ORDER' => Tools::getValue('MA_MERCHANT_ORDER', Configuration::get('MA_MERCHANT_ORDER')),
			'MA_MERCHANT_OOS' => Tools::getValue('MA_MERCHANT_OOS', Configuration::get('MA_MERCHANT_OOS')),
			'MA_LAST_QTIES' => Tools::getValue('MA_LAST_QTIES', Configuration::get('MA_LAST_QTIES')),
			'MA_MERCHANT_COVERAGE' => Tools::getValue('MA_MERCHANT_COVERAGE', Configuration::get('MA_MERCHANT_COVERAGE')),
			'MA_PRODUCT_COVERAGE' => Tools::getValue('MA_PRODUCT_COVERAGE', Configuration::get('MA_PRODUCT_COVERAGE')),
			'MA_MERCHANT_MAILS' => Tools::getValue('MA_MERCHANT_MAILS', Configuration::get('MA_MERCHANT_MAILS')),
			'MA_ORDER_EDIT' => Tools::getValue('MA_ORDER_EDIT', Configuration::get('MA_ORDER_EDIT')),
			'MA_RETURN_SLIP' => Tools::getValue('MA_RETURN_SLIP', Configuration::get('MA_RETURN_SLIP')),
		);
	}
}

il est possible que je n'aie pas les yeux en face des trous :-) 

 

merci

Link to comment
Share on other sites

c'est bien là qu'est l'os ... 

Les fichiers copiés hier sont ceux provenant du zip que j'avais créé du 1.6.7 avant la maj.

Je joins le dossier zippé du module mailalerts, provenant du téléchargement du site en version 1..6.1.7 en vue de l'upload sur mon serveur afin de faire la maj.

 

Bon, depuis le clone ancienne version, j'ai testé 2 commandes, l'une en colissimo, l'autre en retrait au magasin, pour voir si le module faisait bien ce qu'on m'en avait dit. Mais le ou les mails ne sont jamais arrivés (pourtant visibles dans la liste des emails, en BO).

Test de l'envoi de mail ok

fichier lang.php bien présent

mode maintenance responsable ???
 

mailalerts.zip

Link to comment
Share on other sites

je commence à me demander si le client n'a pas rêvé ... car en vérifiant dans Préférences, Email, sur une commande avec livraison en magasin, je vois bien qu'un mail lui a été envoyé ...

Ou alors, le filtre est en aval ...

Link to comment
Share on other sites

pardon, suis un peu fatiguée ... le mail dont je parle, c'est normal qu'il l'ait reçu car c'est une commande avec retrait en magasin.
Si on ne trouve rien dans les fichiers, il est possible qu'il y ait eu une maj du module depuis sa modif car en affichant les emails triés sur new_order, je vois qu'effectivement il n'y a eu des notfs que pour les commandes avec retrait en magasin du 27/01 au 14/02. Mais après, pour Prestashop, un mail partait à l'admin pour chaque nouvelle commande ... 
Les intitulés diffèrent (mais le modèle est toujours order_new) : depuis que toutes les alertes sont envoyées : " New order : #6392 - OIXGKBLMQ". Mais quand c'était seulement les commandes à venir chercher en magasin, entre le 27/01 et le 14/02  : "Nouvelle commande - 005813 - Retrait au magasin". Ensuite, c'est le même intitulé New order ... Et effectivement, dans mailalerts.php j'ai cette ligne :

$mail_id_lang,
					'new_order',
					sprintf(Mail::l('New order : #%d - %s', $mail_id_lang), $order->id, $order->reference),

Donc il y a bien eu modif du module et c'est pas la peine de chercher plus loin (même si le gars m'affirme qu'il ne recevait que les bons mails jusqu'au 18)

Alors, maintenant, la question est : comment refaire la même chose ? Comment limiter l'envoi de la notif à l'admin du site seulement pour un choix de livraison ??
J'ai déjà cherché justement pour essayer de retrouver quel fichier aurait pu avoir été modifié, mais je n'ai rien trouvé en ce sens.

 

Auriez-vous une idée ?

Merci d'avance

Link to comment
Share on other sites

pfff ... le client vient de se renseigner auprès de son magasin ... hé oui ! depuis le 14/02, ils recevaient bien tous les mails, mais n'avaient rien dit parce qu'ils pensaient que c'était normal .

Donc je vous ai emm..és pour rien, et j'y ai perdu quelques heures ... et je vous ai fait perdre votre temps aussi, désolée 😞

Link to comment
Share on other sites

	public function hookActionValidateOrder($params)
	{
		if (!$this->merchant_order || empty($this->merchant_mails))
			return;

		// Getting differents vars
		$context = Context::getContext();
		$id_lang = (int)$context->language->id;
		$id_shop = (int)$context->shop->id;
		$currency = $params['currency'];
		$order = $params['order'];
		$customer = $params['customer'];
		$configuration = Configuration::getMultiple(
			array(
				'PS_SHOP_EMAIL',
				'PS_MAIL_METHOD',
				'PS_MAIL_SERVER',
				'PS_MAIL_USER',
				'PS_MAIL_PASSWD',
				'PS_SHOP_NAME',
				'PS_MAIL_COLOR'
			), $id_lang, null, $id_shop
		);
		$delivery = new Address((int)$order->id_address_delivery);
		$invoice = new Address((int)$order->id_address_invoice);
		$order_date_text = Tools::displayDate($order->date_add);
		$carrier = new Carrier((int)$order->id_carrier);
if ($carrier->reference != ID de référence du transporteur requis)
   return;
   .... (suite du code)

 

  • Thanks 1
Link to comment
Share on other sites

Hello Eolia,

Ca marche en ajoutant les 2 lignes sur le fichier mailalerts.php du module. Encore un tout grand merci et désolée du retour seulement maintenant.

Pour ceux que cela intéresse, la tournure exacte est :

if ($carrier->id_reference != 29)
		return;

Il faut aller voir dans la base de données quelle est l'id_reference du transporteur car elle n'apparaît pas en BO.

 

Mais ... car il y a toujours un mails ...

Afin de ne plus avoir de souci en cas de mise à jour j'ai voulu overrider le fichier et ai donc créé un dossier mailalerts dans override/modules, dans lequel j'ai mis un fichier mailalerts.php contenant ces lignes

<?php

if (!defined('_PS_VERSION_'))
	exit;
class MailAlertsOverride extends MailAlerts
{
public function hookActionValidateOrder($params)
	{
		if (!$this->merchant_order || empty($this->merchant_mails))
			return;

		// Getting differents vars
		$context = Context::getContext();
		$id_lang = (int)$context->language->id;
		$id_shop = (int)$context->shop->id;
		$currency = $params['currency'];
		$order = $params['order'];
		$customer = $params['customer'];
		$configuration = Configuration::getMultiple(
			array(
				'PS_SHOP_EMAIL',
				'PS_MAIL_METHOD',
				'PS_MAIL_SERVER',
				'PS_MAIL_USER',
				'PS_MAIL_PASSWD',
				'PS_SHOP_NAME',
				'PS_MAIL_COLOR'
			), $id_lang, null, $id_shop
		);
		$delivery = new Address((int)$order->id_address_delivery);
		$invoice = new Address((int)$order->id_address_invoice);
		$order_date_text = Tools::displayDate($order->date_add);
		$carrier = new Carrier((int)$order->id_carrier);
		if ($carrier->id_reference != 29)
		return;
		$message = $this->getAllMessages($order->id);

		if (!$message || empty($message))
			$message = $this->l('No message');

		$items_table = '';

		$products = $params['order']->getProducts();
		$customized_datas = Product::getAllCustomizedDatas((int)$params['cart']->id);
		Product::addCustomizationPrice($products, $customized_datas);
		foreach ($products as $key => $product)
		{
			$unit_price = Product::getTaxCalculationMethod($customer->id) == PS_TAX_EXC ? $product['product_price'] : $product['product_price_wt'];

			$customization_text = '';
			if (isset($customized_datas[$product['product_id']][$product['product_attribute_id']]))
			{
				foreach ($customized_datas[$product['product_id']][$product['product_attribute_id']][$order->id_address_delivery] as $customization)
				{
					if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD]))
						foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text)
							$customization_text .= $text['name'].': '.$text['value'].'<br />';

					if (isset($customization['datas'][Product::CUSTOMIZE_FILE]))
						$customization_text .= count($customization['datas'][Product::CUSTOMIZE_FILE]).' '.$this->l('image(s)').'<br />';

					$customization_text .= '---<br />';
				}
				if (method_exists('Tools', 'rtrimString'))
					$customization_text = Tools::rtrimString($customization_text, '---<br />');
				else
					$customization_text = preg_replace('/---<br \/>$/', '', $customization_text);
			}

			$url = $context->link->getProductLink($product['product_id']);
			$items_table .=
				'<tr style="background-color:'.($key % 2 ? '#DDE2E6' : '#EBECEE').';">
					<td style="padding:0.6em 0.4em;">'.$product['product_reference'].'</td>
					<td style="padding:0.6em 0.4em;">
						<strong><a href="'.$url.'">'.$product['product_name'].'</a>'
							.(isset($product['attributes_small']) ? ' '.$product['attributes_small'] : '')
							.(!empty($customization_text) ? '<br />'.$customization_text : '')
						.'</strong>
					</td>
					<td style="padding:0.6em 0.4em; text-align:right;">'.Tools::displayPrice($unit_price, $currency, false).'</td>
					<td style="padding:0.6em 0.4em; text-align:center;">'.(int)$product['product_quantity'].'</td>
					<td style="padding:0.6em 0.4em; text-align:right;">'
						.Tools::displayPrice(($unit_price * $product['product_quantity']), $currency, false)
					.'</td>
				</tr>';
		}
		foreach ($params['order']->getCartRules() as $discount)
		{
			$items_table .=
				'<tr style="background-color:#EBECEE;">
						<td colspan="4" style="padding:0.6em 0.4em; text-align:right;">'.$this->l('Voucher code:').' '.$discount['name'].'</td>
					<td style="padding:0.6em 0.4em; text-align:right;">-'.Tools::displayPrice($discount['value'], $currency, false).'</td>
			</tr>';
		}
		if ($delivery->id_state)
			$delivery_state = new State((int)$delivery->id_state);
		if ($invoice->id_state)
			$invoice_state = new State((int)$invoice->id_state);

		if (Product::getTaxCalculationMethod($customer->id) == PS_TAX_EXC)
			$total_products = $order->getTotalProductsWithoutTaxes();
		else
			$total_products = $order->getTotalProductsWithTaxes();

		$order_state = $params['orderStatus'];

		// Filling-in vars for email
		$template_vars = array(
			'{firstname}' => $customer->firstname,
			'{lastname}' => $customer->lastname,
			'{email}' => $customer->email,
			'{delivery_block_txt}' => MailAlert::getFormatedAddress($delivery, "\n"),
			'{invoice_block_txt}' => MailAlert::getFormatedAddress($invoice, "\n"),
			'{delivery_block_html}' => MailAlert::getFormatedAddress(
				$delivery, '<br />', array(
					'firstname' => '<span style="color:'.$configuration['PS_MAIL_COLOR'].'; font-weight:bold;">%s</span>',
					'lastname' => '<span style="color:'.$configuration['PS_MAIL_COLOR'].'; font-weight:bold;">%s</span>'
				)
			),
			'{invoice_block_html}' => MailAlert::getFormatedAddress(
				$invoice, '<br />', array(
					'firstname' => '<span style="color:'.$configuration['PS_MAIL_COLOR'].'; font-weight:bold;">%s</span>',
					'lastname' => '<span style="color:'.$configuration['PS_MAIL_COLOR'].'; font-weight:bold;">%s</span>'
				)
			),
			'{delivery_company}' => $delivery->company,
			'{delivery_firstname}' => $delivery->firstname,
			'{delivery_lastname}' => $delivery->lastname,
			'{delivery_address1}' => $delivery->address1,
			'{delivery_address2}' => $delivery->address2,
			'{delivery_city}' => $delivery->city,
			'{delivery_postal_code}' => $delivery->postcode,
			'{delivery_country}' => $delivery->country,
			'{delivery_state}' => $delivery->id_state ? $delivery_state->name : '',
			'{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile,
			'{delivery_other}' => $delivery->other,
			'{invoice_company}' => $invoice->company,
			'{invoice_firstname}' => $invoice->firstname,
			'{invoice_lastname}' => $invoice->lastname,
			'{invoice_address2}' => $invoice->address2,
			'{invoice_address1}' => $invoice->address1,
			'{invoice_city}' => $invoice->city,
			'{invoice_postal_code}' => $invoice->postcode,
			'{invoice_country}' => $invoice->country,
			'{invoice_state}' => $invoice->id_state ? $invoice_state->name : '',
			'{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile,
			'{invoice_other}' => $invoice->other,
			'{order_name}' => $order->reference,
			'{order_status}' => $order_state->name,
			'{shop_name}' => $configuration['PS_SHOP_NAME'],
			'{date}' => $order_date_text,
			'{carrier}' => (($carrier->name == '0') ? $configuration['PS_SHOP_NAME'] : $carrier->name),
			'{payment}' => Tools::substr($order->payment, 0, 32),
			'{items}' => $items_table,
			'{total_paid}' => Tools::displayPrice($order->total_paid, $currency),
			'{total_products}' => Tools::displayPrice($total_products, $currency),
			'{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency),
			'{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency),
			'{total_tax_paid}' => Tools::displayPrice(
				($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl),
				$currency,
				false
			),
			'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency),
			'{currency}' => $currency->sign,
			'{gift}' => (bool)$order->gift,
			'{gift_message}' => $order->gift_message,
			'{message}' => $message
		);

		// Shop iso
		$iso = Language::getIsoById((int)Configuration::get('PS_LANG_DEFAULT'));

		// Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients
		$merchant_mails = explode(self::__MA_MAIL_DELIMITOR__, $this->merchant_mails);
		foreach ($merchant_mails as $merchant_mail)
		{
			// Default language
			$mail_id_lang = $id_lang;
			$mail_iso = $iso;

			// Use the merchant lang if he exists as an employee
			$results = Db::getInstance()->executeS('
				SELECT `id_lang` FROM `'._DB_PREFIX_.'employee`
				WHERE `email` = \''.pSQL($merchant_mail).'\'
			');
			if ($results)
			{
				$user_iso = Language::getIsoById((int)$results[0]['id_lang']);
				if ($user_iso)
				{
					$mail_id_lang = (int)$results[0]['id_lang'];
					$mail_iso = $user_iso;
				}
			}

			$dir_mail = false;
			if (file_exists(dirname(__FILE__).'/mails/'.$mail_iso.'/new_order.txt') &&
				file_exists(dirname(__FILE__).'/mails/'.$mail_iso.'/new_order.html'))
				$dir_mail = dirname(__FILE__).'/mails/';

			if (file_exists(_PS_MAIL_DIR_.$mail_iso.'/new_order.txt') &&
				file_exists(_PS_MAIL_DIR_.$mail_iso.'/new_order.html'))
				$dir_mail = _PS_MAIL_DIR_;

			if ($dir_mail)
				Mail::Send(
					$mail_id_lang,
					'new_order',
					sprintf(Mail::l('New order : #%d - %s', $mail_id_lang), $order->id, $order->reference),
					$template_vars,
					$merchant_mail,
					null,
					$configuration['PS_SHOP_EMAIL'],
					$configuration['PS_SHOP_NAME'],
					null,
					null,
					$dir_mail,
					null,
					$id_shop
				);
		}
	}
}	

Du coup, plus de mail envoyé du tout !

J'ai bien sûr supprimé les 2 lignes dans le mailaerts.php d'origine, supprimé class_index, etc. Désactiver les surcharges est sur Non ...

 

Qu'est-ce que j'oublie ???

 

Merci d'avance !!!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...