Merge branch 'ticket-13814-mailAlertUpdate'

This commit is contained in:
Marion Muszynski 2017-08-22 12:34:46 +02:00
commit 8288d10a39
7 changed files with 508 additions and 71 deletions

View File

@ -2,7 +2,7 @@
<html> <html>
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Message Alert Problèmes techniques</title> <title>Message Alert {contact}</title>
</head> </head>
<body> <body>
<table style="font-family: tahoma,arial,sans-serif; font-size: 12px; color:#000000; width: 100%;"> <table style="font-family: tahoma,arial,sans-serif; font-size: 12px; color:#000000; width: 100%;">
@ -13,7 +13,7 @@
</tr> </tr>
<tr><td>&nbsp;</td></tr> <tr><td>&nbsp;</td></tr>
<tr> <tr>
<td align="left" style="background: #514c8c; color:#ffffff; font-size: 12px; font-weight:bold; padding: 0.5em 1em;">Vous avez reçu {limit} messages ou plus concernant des problèmes techniques en {hours}H.</td> <td align="left" style="background: #514c8c; color:#ffffff; font-size: 12px; font-weight:bold; padding: 0.5em 1em;">Vous avez reçu {limit} messages ou plus concernant {contact} en {hours}H.</td>
</tr> </tr>
<tr><td>&nbsp;</td></tr> <tr><td>&nbsp;</td></tr>
<tr> <tr>

View File

@ -1 +1 @@
Vous avez reçu {limit} messages ou plus concernant des problèmes techniques en {hours}H Vous avez reçu {limit} messages ou plus concernant {contact} en {hours}H

View File

@ -1,38 +1,332 @@
<?php <?php
class AdminAntAlert extends AdminTab { include_once(_PS_MODULE_DIR_.'/ant_alert/ant_alert.php');
public function postProcess() { require_once(PS_ADMIN_DIR . '/helpers/HelperFormBootstrap.php');
if(($limit = Tools::getValue('ant_alert_limit')) !== FALSE) {
Configuration::updateValue('ANT_ALTER_LIMIT', (int) $limit);
}
if($hours = Tools::getValue('ant_alert_hours')) {
Configuration::updateValue('ANT_ALTER_HOURS', (int) $hours);
}
}
public function display() {
global $cookie;
echo ' class AdminAntAlert extends AdminTab {
<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
<fieldset> protected $_html;
<legend><img src="../img/admin/AdminTools.gif" alt="" />'.$this->l('Configuration Alert').'</legend> public $module_name;
<p>'.$this->l('Last send : ').Configuration::get('ANT_ALTER_DATESEND').'<p> public $config_tab;
<div style="overflow: auto;"> public $controller;
<label style="font-weight:normal; padding-top: 1px; width: 250px">'.$this->l('Limit (mail number before sending alert)').'</label> public $helperForm;
<div class="margin-form"> public $_object;
<input value="'. Configuration::get('ANT_ALTER_LIMIT') .'" type="text" size="120" name="ant_alert_limit">
</div> public function __construct($config_tab = true)
</div> {
<div style="overflow: auto;"> parent::__construct();
<label style="font-weight:normal; padding-top: 1px; width: 250px">'.$this->l('Time (in hours, ex: by 24h)').'</label> $this->_object = false;
<div class="margin-form"> $this->controller = 'AdminModules';
<input value="'. Configuration::get('ANT_ALTER_HOURS') .'" type="text" size="120" name="ant_alert_hours"> $this->module_name = 'ant_alert';
</div> $this->config_tab = (bool)$config_tab;
</div> if ($config_tab) {
<div class="margin-form"> $this->controller = 'AdminAntAlert';
<input value="'. $this->l('Sauvegarder') .'" type="submit" name="saveAntAlert" class="button"> }
</div> $this->helperForm = new HelperFormBootstrap();
</fieldset> $this->helperForm->_select2 = true;
</form> $this->helperForm->_inputSwitch = true;
<br class="clear" />';
} }
protected function _postProcess()
{
if (Tools::isSubmit('newAlert')) {
} elseif (Tools::isSubmit('addAlert')) {
$this->_addOrUpdateAlert(false);
} elseif (Tools::isSubmit('editAlert')) {
$this->_addOrUpdateAlert(true);
} elseif (Tools::isSubmit('loadAlert') && Tools::getValue('id')) {
$this->_object = new AntAlert((int)Tools::getValue('id'));
} elseif (Tools::isSubmit('deleteAlert') && Tools::getValue('id')) {
$deleted_alert = new AntAlert((int)Tools::getValue('id'));
$res = $deleted_alert->delete();
if ($res) {
$this->_html .= HelperFormBootstrap::displaySuccess($this->l('Alert deleted : #') . (int)Tools::getValue('id'));
} else {
$this->_html .= HelperFormBootstrap::displayErrors($this->l('Alert cannot be deleted : #') . (int)Tools::getValue('id'));
}
return $res;
}
}
protected function _addOrUpdateAlert($edit = false)
{
if ($edit) {
$alert = new AntAlert((int)Tools::getValue('id_alert'));
} else {
$alert = new AntAlert();
$alert->date_last_sent = date("Y-m-d H:i:s");
}
$alert->id_contact = (int)Tools::getValue('id_contact');
$alert->limit = (int)Tools::getValue('limit');
$alert->hours = (int)Tools::getValue('hours');
$alert->enabled = (int)Tools::getValue('enabled');
if ($alert->save()) {
if ($edit) {
$this->_html .= HelperFormBootstrap::displaySuccess($this->l('Alert has been updated'));
} else {
$this->_html .= HelperFormBootstrap::displaySuccess($this->l('Alert has been created'));
}
} else {
$this->_html .= HelperFormBootstrap::displayErrors($this->l('Error occured while updating alert'));
}
}
public function display()
{
parent::displayForm();
$this->_html = '';
$this->_postProcess();
$this->_addCss();
$this->_html .= $this->helperForm->renderStyle();
$this->_displayForm();
$this->_displayList();
$this->_html .='<div class="clearfix"></div>';
$this->_addJs();
$this->_html .= $this->helperForm->renderScript();
echo $this->_html;
}
protected function _addJs()
{
$this->helperForm->_js .= '<script type="text/javascript"></script>';
}
protected function _addCss()
{
$this->helperForm->_css .='
.table tr th {
background: #565485;
background: rgba(86,84,133,0.9);
color: #fff;
font-size: 12px;
}
.table tr:nth-child(even) {
background: #F1F1F1;
}
.table .input-group-btn .btn {
padding: 4px 5px;
color: #504d8b;
}
.table .input-group-btn .btn .anticon{
font-size: 12px;
}
.bg-grey{
background: #EFEFEF;
border-radius:4px;
}
.bg-grey .div-title {
border-bottom: 2px solid #504D8B;
}
';
}
protected function _displayList()
{
global $cookie, $currentIndex;
$id_lang = (int)$cookie->id_lang;
$contacts = Contact::getContacts($cookie->id_lang);
$alerts = AntAlert::getAlerts(false);
$_current_index = ($this->config_tab ? $currentIndex . '&token=' . Tools::getAdminTokenLite($this->controller) : $_SERVER['REQUEST_URI']);
$this->_html .='
<div class="col-md-12">
<div class="panel">
<div class="panel-title">
<h2><span class="text-rose anticon anticon-list"></span> '.$this->l('Liste des Alertes').'</h2>
<div class="clearfix"></div>
</div>
<div class="panel-content">
<table class="table table-custombordered" style="width: 100%;">
<thead>
<tr>
<th class="text-left">'.$this->l('ID').'</th>
<th class="text-left">'.$this->l('Contact').'</th>
<th class="text-left">'.$this->l('Limite par heures').'</th>
<th class="text-left">'.$this->l('Dernier envoi').'</th>
<th class="text-center">'.$this->l('Active').'</th>
<th class="text-center">'.$this->l('Action').'</th>
</tr>
</thead>
<tbody>';
foreach ($alerts as $alert)
{
$current_contact = $this->_search($contacts,'id_contact',(int)$alert['id_contact']);
$this->_html .='
<tr>
<td valign="middle" align="left">#'.$alert['id_alert'].'</td>
<td valign="middle" align="left"><b>'.$current_contact['name'].'</b></td>
<td valign="middle" align="left"><b>'.$alert['limit'].' <i class="glyphicon glyphicon-envelope"></i> / '.$alert['hours'].'h</b></td>
<td valign="middle" align="left"><i class="glyphicon glyphicon-time"></i> '.date('d/m/Y H:i',strtotime($alert['date_last_sent'])).'</td>
<td align="center">'.((int)$alert['enabled']?'<span class="anticon anticon-checkmark text-green-light"></span>':'<span class="anticon anticon-cross text-rose"></span>').'</td>
<td valign="middle" align="center">
<div class="input-group-btn" role="group" aria-label="...">
<a href="'.$_current_index.'&loadAlert=1&id='.$alert['id_alert'].'" class="btn btn-default"><span class="anticon anticon-pencil2"></span></a>
<a href="'.$_current_index.'&deleteAlert=1&id='.$alert['id_alert'].'" class="btn btn-default"><span class="anticon anticon-bin"></span></a>
</div>
</td>
</tr>';
}
$this->_html .='
</tbody>
</table>
</div>
</div>
</div>';
}
private function _displayForm()
{
global $cookie, $currentIndex;
if (Validate::isLoadedObject($this->_object)){
$alert = $this->_object;
}
$contacts = Contact::getContacts($cookie->id_lang);
$alreadyUsedContacts = AntAlert::getAlreadyUsedContacts();
foreach($contacts as $contact) {
$id_contacts[(int)$contact['id_contact']] = array(
'label' => $contact['name'],
'value' => (int) $contact['id_contact']
);
if(isset($alert) && $alert->id_contact==$contact['id_contact']) {
$id_contacts[(int)$contact['id_contact']]['selected'] = true;
}elseif(in_array($contact['id_contact'], $alreadyUsedContacts)){
$id_contacts[(int)$contact['id_contact']]['disabled'] = true;
}
}
$this->helperForm->_forms = array(
array(
'action' => $currentIndex . '&token=' . Tools::getAdminTokenLite('AdminAntAlert'),
'title' => '<span class="text-rose glyphicon glyphicon-tags"></span> '.$this->l('Alerte'),
'class' => 'form-horizontal',
'class_div' => 'col-md-12',
'sections' => array(
array(
'class' => 'col-md-6',
'inputs' => array(
array(
'type' => 'select2',
'name' => 'id_contact',
// 'label-class' => 'col-md-5',
// 'input-class' => 'col-md-6',
'label' => $this->l('Contact'),
'options' => $id_contacts,
),
array(
'type' => 'simpleText',
'name' => 'limit',
'label-class' => 'col-md-3',
'input-class' => 'col-md-6',
'label' => $this->l('Limit'),
'default' => (isset($alert)?$alert->limit:'')
),
array(
'type' => 'simpleText',
'name' => 'hours',
'label-class' => 'col-md-3',
'input-class' => 'col-md-6',
'label' => $this->l('Hours'),
'default' => (isset($alert)?$alert->hours:'')
),
array(
'type' => 'switch',
'label' => $this->l('Active'),
'label-class' => 'col-md-3',
'input-class' => 'col-md-6',
'class-group' => 'switch',
'name' => 'enabled',
'title' => ' ',
'default' => (isset($alert)?($alert->enabled==0?0:1):1),
'checked' => (isset($alert)?($alert->enabled==0?0:1):1),
),
),
'actions' => array(),
'actions-class' => 'text-right',
),
array(
'class' => 'col-md-6 bg-grey',
'title' => '<span class="anticon anticon-info"></span> Informations',
'inputs' => array(),
'info_html' => '
<p>La limite des messages est par heures et par type de contact.</p>
<br>
Par exemple :</p>
<ul>
<li style="font-size:13px;">Limite <b>50</b> en <b>1</b> heure pour le contact "Retour/Echange" </li>
</ul>
<p>Ici un mail d\'alerte se déclenche après 1h si 50 messages ou plus, concernant les Retour/Echange, ont été envoyés.</p>
<p>Une seule alerte par type de contact possible !</p>
<p></p>'
),
),
'actions' => array(),
'actions-class' => 'text-right',
)
);
if (isset($alert)) {
$this->helperForm->_forms[0]['sections'][0]['title'] = "Editer une alerte";
$this->helperForm->_forms[0]['sections'][0]['inputs'][] = array(
'type' => 'hidden',
'name' => 'id_alert',
'value' => $alert->id,
'class' => 'large'
);
$this->helperForm->_forms[0]['sections'][0]['actions'] = array(
array(
'type' => 'submit',
'class' => 'btn-default',
'name' => 'newAlert',
'value' => $this->l('Nouvelle Alerte')
),
array(
'type' => 'submit',
'class' => 'btn-primary',
'name' => 'editAlert',
'value' => $this->l('Editer l\'alerte')
),
);
} else {
$this->helperForm->_forms[0]['sections'][0]['title'] = "Ajouter une alerte";
$this->helperForm->_forms[0]['sections'][0]['actions'] = array(
array(
'type' => 'submit',
'class' => 'btn-primary',
'name' => 'addAlert',
'value' => $this->l('Ajouter l\'alerte')
),
);
}
$this->helperForm->renderForm();
}
public function _search($array, $key, $value)
{
$results = array();
if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
return $array;
}
foreach ($array as $subarray) {
$results = array_merge($results, $this->_search($subarray, $key, $value));
}
}
return $results;
}
} }

View File

@ -2,6 +2,8 @@
if (!defined('_PS_VERSION_')) if (!defined('_PS_VERSION_'))
exit; exit;
include_once(_PS_MODULE_DIR_.'/ant_alert/models/AntAlert.php');
class Ant_Alert extends Module class Ant_Alert extends Module
{ {
@ -21,7 +23,23 @@ class Ant_Alert extends Module
public function install() public function install()
{ {
# Add tables
$query = '
CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'ant_alert` (
`id_alert` INTEGER NOT NULL AUTO_INCREMENT,
`enabled` BOOL NOT NULL,
`id_contact` INTEGER NOT NULL,
`limit` INTEGER NOT NULL,
`hours` INTEGER NOT NULL,
`date_add` DATETIME NOT NULL,
`date_upd` DATETIME NOT NULL,
`date_last_sent` DATETIME NOT NULL,
PRIMARY KEY(`id_alert`,`id_contact`)
) ENGINE=MyIsam DEFAULT CHARSET=utf8
';
if(!Db::getInstance()->Execute($query)) {
return false;
}
$hooks = array( $hooks = array(
'ant_alert' => array('Ant Alert', 'Called when a message of technical error is sent'), 'ant_alert' => array('Ant Alert', 'Called when a message of technical error is sent'),
@ -46,9 +64,9 @@ class Ant_Alert extends Module
} }
# Set default configuration values # Set default configuration values
Configuration::updateValue('ANT_ALTER_LIMIT', 10); // Configuration::updateValue('ANT_ALTER_LIMIT', 10);
Configuration::updateValue('ANT_ALTER_HOURS', 24); // Configuration::updateValue('ANT_ALTER_HOURS', 24);
Configuration::updateValue('ANT_ALTER_DATESEND', date('Y-m-d H:i:s')); // Configuration::updateValue('ANT_ALTER_DATESEND', date('Y-m-d H:i:s'));
return true; return true;
} }
@ -69,38 +87,44 @@ class Ant_Alert extends Module
public function hookAnt_Alert($params) { public function hookAnt_Alert($params) {
global $cookie; global $cookie;
$date = new Datetime(Configuration::get('ANT_ALTER_DATESEND')); $alert = AntAlert::getAlertByContact((int)$params['id_contact']);
$now = new Datetime; if($alert && (int)$alert->enabled == 1) {
$date = new Datetime($alert->date_last_sent);
$now = new Datetime;
$dteDiff = $date->diff($now); $dteDiff = $date->diff($now);
if ((int)$dteDiff->format("%H") >= (int)Configuration::get('ANT_ALTER_HOURS')) { // prod if ((int)$dteDiff->format("%H") >= (int)$alert->hours) { // prod
$open_messages = Db::getInstance()->getRow('
SELECT COUNT(*) as total $open_messages = Db::getInstance()->getRow('
FROM '._DB_PREFIX_.'customer_thread ct SELECT COUNT(*) as total
WHERE ct.status = "open" FROM '._DB_PREFIX_.'customer_thread ct
GROUP BY ct.id_contact HAVING COUNT(*) > 0 AND ct.id_contact = 4' WHERE ct.status = "open"
); GROUP BY ct.id_contact HAVING COUNT(*) > 0 AND ct.id_contact ='.(int)$alert->id_contact
if ((int)$open_messages['total'] >= (int)Configuration::get('ANT_ALTER_LIMIT')) {
// dev
// $to = array('marion@antadis.com');
// prod
$to = array(
'frederic@bebeboutik.com',
'jacques@bebeboutik.com',
'valentin@bebeboutik.com',
); );
$data = array( if ((int)$open_messages['total'] >= (int)$alert->limit) {
'{limit}' => (int)Configuration::get('ANT_ALTER_LIMIT'), // dev
'{hours}' => (int)Configuration::get('ANT_ALTER_HOURS'), $to = array('marion@antadis.com');
); // prod
foreach ($to as $email) { // $to = array(
if(Mail::Send((int)$cookie->id_lang, 'ant_alert', 'Alert error', $data, $to)) { // 'frederic@bebeboutik.com',
Configuration::updateValue('ANT_ALTER_DATESEND', date('Y-m-d H:i:s')); // 'jacques@bebeboutik.com',
// 'valentin@bebeboutik.com',
// );
$contact = new Contact((int)$alert->id_contact,2);
$data = array(
'{limit}' => (int)$alert->limit,
'{hours}' => (int)$alert->hours,
'{contact}' => $contact->name,
);
foreach ($to as $email) {
if(Mail::Send(2, 'ant_alert', 'Alert error', $data, $to)) {
$alert->date_last_sent = date('Y-m-d H:i:s');
$alert->save();
}
} }
} }
} }
} }
} }
} }

View File

@ -0,0 +1,119 @@
<?php
class AntAlert extends ObjectModel
{
public $id_alert;
public $enabled;
public $id_contact;
public $limit;
public $hours;
public $date_add;
public $date_upd;
public $date_last_sent;
protected $fieldsRequired = array('id_contact','limit','hours');
protected $fieldsValidate = array(
'id_alert' => 'isUnsignedId',
'enabled' => 'isBool',
'id_contact' => 'isUnsignedId',
'limit' => 'isInt',
'hours' => 'isInt',
'date_add' => 'isDate',
'date_upd' => 'isDate',
'date_last_sent' => 'isDate',
);
protected $table = 'ant_alert';
protected $identifier = 'id_alert';
public function getFields()
{
parent::validateFields();
$fields['id_alert'] = (int)$this->id_alert;
$fields['enabled'] = (int)$this->enabled;
$fields['id_contact'] = (int)$this->id_contact;
$fields['limit'] = (int)$this->limit;
$fields['hours'] = (int)$this->hours;
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
$fields['date_last_sent'] = pSQL($this->date_last_sent);
return $fields;
}
public function delete()
{
return true;
}
/**
* Get demands
* @param $states array get only demands in specific states
* @return Array Groups
*/
public static function getAlerts($enabled = true, $where = false)
{
if($where){
return Db::getInstance()->executeS('
SELECT *
FROM `'._DB_PREFIX_.'ant_alert` at
WHERE '.$where.'
'.($enabled ? ' AND at.`enabled` = 1' : '').'
');
} else {
return Db::getInstance()->executeS('
SELECT *
FROM `'._DB_PREFIX_.'ant_alert` at
WHERE 1
'.($enabled ? ' AND at.`enabled` = 1' : '').'
');
}
}
public function save($nullValues = false, $autodate = true)
{
if (parent::save($nullValues,$autodate)) {
return true;
}
}
public static function getAlertByContact($id_contact)
{
$id = Db::getInstance()->getValue("
SELECT `id_alert`
FROM `"._DB_PREFIX_."ant_alert`
WHERE `id_contact` = " .(int)$id_contact
);
if($id) {
return new AntAlert((int)$id);
}
return false;
}
public static function getAlreadyUsedContacts()
{
$id_contacts = array();
foreach(Db::getInstance()->executeS("
SELECT DISTINCT `id_contact`
FROM `"._DB_PREFIX_."ant_alert`"
) as $row){
$id_contacts[(int)$row['id_contact']] = (int)$row['id_contact'];
}
return $id_contacts;
}
public static function isExistAndEnabled($id_contact)
{
return Db::getInstance()->getValue("
SELECT `id_alert`
FROM `"._DB_PREFIX_."ant_alert`
WHERE `id_contact` = " .(int)$id_contact."
AND `enabled` = 1"
);
}
}

View File

@ -239,7 +239,7 @@ if (Tools::isSubmit('submitMessage')) {
else else
$errors[] = Tools::displayError('An error occurred while sending message.'); $errors[] = Tools::displayError('An error occurred while sending message.');
} }
Module::hookExec('ant_alert', array('id_contact' => (int)($id_contact)));
Module::hookExec('ant_alerthack', array( Module::hookExec('ant_alerthack', array(
'email' => $from, 'email' => $from,
'id_customer' => (isset($customer->id)?$customer->id:false), 'id_customer' => (isset($customer->id)?$customer->id:false),

View File

@ -202,7 +202,7 @@ class ContactController extends ContactControllerCore {
$this->errors[] = Tools::displayError('An error occurred while sending message.'); $this->errors[] = Tools::displayError('An error occurred while sending message.');
} }
Module::hookExec('ant_alert', array()); Module::hookExec('ant_alert', array('id_contact' => (int)($id_contact)));
Module::hookExec('ant_alerthack', array( Module::hookExec('ant_alerthack', array(
'email' => $from, 'email' => $from,
'id_customer' => (isset($customer->id)?$customer->id:false), 'id_customer' => (isset($customer->id)?$customer->id:false),