Skip to content
Snippets Groups Projects
Verified Commit ce3871c4 authored by Florian Azizian's avatar Florian Azizian
Browse files

FEAT #13679 TIME 2:15 refactoring notification alerts

parent 1dea5597
No related branches found
No related tags found
No related merge requests found
Showing
with 133 additions and 689 deletions
<?php
/**
* alert_engine Class
*
* Contains all the specific functions of the diff engine
* @package core
* @version 1.0
* @since 10/2005
* @license GPL
* @author Laurent Giovannoni <dev@maarch.org>
*/
class alert_engine extends Database
{
/**
* Redefinition of the alert_engine object constructor
*/
function __construct()
{
$args = func_get_args();
if (count($args) < 1) parent::__construct();
else parent::__construct($args[0]);
}
/**
* Allow to know when the next Easter come
*
* @param date $year
*/
public function WhenEasterCelebrates($year = null)
{
if (is_null($year))
{
$year = (int)date ('Y');
}
$iN = $year - 1900;
$iA = $iN%19;
$iB = floor (((7*$iA)+1)/19);
$iC = ((11*$iA)-$iB+4)%29;
$iD = floor ($iN/4);
$iE = ($iN-$iC+$iD+31)%7;
$time = 25-$iC-$iE;
if($time > 0)
{
$WhenEasterCelebrates = strtotime ($year.'/04/'.$time);
}
else
{
$WhenEasterCelebrates = strtotime ($year.'/03/'.(31+$time));
}
return $WhenEasterCelebrates;
}
/**
* Allow to know when the next open day come
*
* @param date $Date in timestamp format
* @param int $Delta
* @param boolean $isMinus
*/
public function WhenOpenDay($Date, $Delta, $isMinus = false, $calendarType = null)
{
if ($calendarType <> 'calendar' && $calendarType <> 'workingDay') {
$calendarType = $_SESSION['features']['type_calendar'];
}
if (empty($calendarType)) {
$calendarType = 'workingDay';
}
if($calendarType == 'calendar') {
if ($isMinus) {
return date('Y-m-d H:i:s', $Date + (86400*-$Delta));
} else {
return date('Y-m-d H:i:s', $Date + (86400*$Delta));
}
} elseif($calendarType == 'workingDay') {
$Hollidays = array (
'1_1',
'1_5',
'8_5',
'14_7',
'15_8',
'1_11',
'11_11',
'25_12'
);
//TODO: Case to erase because not used
if (!empty($_SESSION['features']['type_calendar'])) {
require_once 'core/class/class_db_pdo.php';
$db = new Database();
$stmt = $db->query("select * from parameters where id like 'alert_stop%'");
while ($result = $stmt->fetchObject()) {
if ($result->param_value_date <> '') {
$compare = $this->compare_date($result->param_value_date, date("d-m-Y"));
//take the alert stop only if > now
if ($compare == 'date1' || $compare == 'equal') {
$dateExploded = explode("-", str_replace(" 00:00:00", "", $result->param_value_date));
array_push($Hollidays, (int)$dateExploded[2] . "_" . (int)$dateExploded[1]);
}
}
}
}
//var_dump($Hollidays);
if (function_exists ('easter_date')) {
$WhenEasterCelebrates = easter_date((int)date('Y'), $Date);
} else {
$WhenEasterCelebrates = $this->getEaster((int)date('Y'), $Date);
}
$Hollidays[] = date ('j_n', $WhenEasterCelebrates);
$Hollidays[] = date ('j_n', $WhenEasterCelebrates + (86400*39));
$Hollidays[] = date ('j_n', $WhenEasterCelebrates + (86400*49));
$iEnd = $Delta * 86400;
$i = 0;
while ($i < $iEnd) {
$i = strtotime ('+1 day', $i);
if ($isMinus) {
if (in_array(
date('w', $Date-$i),array (0,6)
) || in_array (date ('j_n', $Date-$i), $Hollidays)
) {
$iEnd = strtotime ('+1 day', $iEnd);
$Delta ++;
}
} else {
if (
in_array(
date('w', $Date+$i),array (0,6)
) || in_array (date ('j_n', $Date+$i), $Hollidays)
) {
$iEnd = strtotime ('+1 day', $iEnd);
$Delta ++;
}
}
}
if ($isMinus) {
return date('Y-m-d H:i:s', $Date + (86400*-$Delta));
} else {
return date('Y-m-d H:i:s', $Date + (86400*$Delta));
}
}
}
/**
* Allow to know the next date to treat
*
* @param int $delay Delay in days
* @param boolean $isMinus true if minus
*/
public function date_max_treatment($delay, $isMinus = false)
{
$result = $this->WhenOpenDay(
strtotime (strftime("%Y")."-".strftime("%m")."-".strftime("%d")),
$delay,
$isMinus
);
return $result;
}
/**
* Allow to know the next date to treat
*
* @param int $delay Delay in days
* @param boolean $isMinus true if minus
*/
public function processDelayDate($date, $delay, $isMinus = false)
{
$date = date('Y-m-d', $date);
$result = $this->WhenOpenDay(
$date,
$delay,
$isMinus
);
return $result;
}
function dateFR2Time($date, $addHours = false)
{
if($addHours == false){
list($day, $month, $year) = explode('/', $date);
$timestamp = mktime(0, 0, 0, $month, $day, $year);
return $timestamp;
}elseif($addHours == true){
list($day, $month, $year) = explode('/', $date);
$timestamp = mktime(23, 59, 59, $month, $day, $year);
return $timestamp;
}
}
}
<?php
/** Logger class
*
* @author Laurent Giovannoni <dev@maarch.org>
**/
class Logger4Php
{
/**
* Array of errors levels
*
* @protected
**/
protected $error_levels = array('DEBUG' => 0, 'INFO' => 1, 'NOTICE' => 2, 'WARNING' => 3, 'ERROR' => 4);
/**
* Maps each handler with its log threshold.
*
* @protected
**/
protected $mapping;
/**
* Minimum log level
*
* @protected
**/
protected $threshold_level;
/**
* Path to log4Php library
*
* @protected
**/
protected $log4PhpLibrary;
/**
* Name of the logger
*
* @protected
**/
protected $log4PhpLogger;
/**
* Name of the business code
*
* @protected
**/
protected $log4PhpBusinessCode;
/**
* Path of the param of log4php
*
* @protected
**/
protected $log4PhpConfigPath;
/**
* Name of the batch
*
* @protected
**/
protected $log4PhpBatchName;
/** Class constructor
*
* Inits the threshold level
*
* @param $threshold_level (string) Threshold level (set to 'INFO' by default)
**/
function __construct($threshold_level = 'WARNING')
{
$this->threshold_level = $threshold_level;
$this->mapping = array_fill(0, count($this->error_levels), array());
}
/** Writes error message in current handlers
*
* writes only if the error level is greater or equal the threshold level
*
* @param $msg (string) Error message
* @param $error_level (string) Error level (set to 'INFO' by default)
* @param $error_code (integer) Error code (set to 0 by default)
**/
public function write($msg, $error_level = 'INFO', $error_code = 0, $other_params = array())
{
if (!array_key_exists($error_level, $this->error_levels)) {
$error_level = 'INFO';
}
$foundLogger = false;
if ($this->error_levels[$error_level] >= $this->error_levels[$this->threshold_level]) {
for ($i=$this->error_levels[$error_level];$i>=0;$i--) {
foreach ($this->mapping[$i] as $handler) {
$handler->write($msg, $error_level, $error_code, $other_params);
if (
get_class($handler) == 'FileHandler'
&& (isset($this->log4PhpLibrary)
&& !empty($this->log4PhpLibrary))
) {
if ($error_code == 0) {
$result = 'OK';
} else {
$result = 'KO';
$msg = '%error_code:' . $error_code . '% ' . $msg;
}
require_once($this->log4PhpLibrary);
$remote_ip = '127.0.0.1';
Logger::configure($this->log4PhpConfigPath);
$logger = Logger::getLogger($this->log4PhpLogger);
$searchPatterns = array('%ACCESS_METHOD%',
'%RESULT%',
'%BUSINESS_CODE%',
'%HOW%',
'%WHAT%',
'%REMOTE_IP%',
'%BATCH_NAME%'
);
$replacePatterns = array('Script',
$result,
$this->log4PhpBusinessCode,
'UP',
$msg,
$remote_ip,
$this->log4PhpBatchName
);
$logLine = str_replace($searchPatterns,
$replacePatterns,
'[%ACCESS_METHOD%][%RESULT%]'
. '[%BUSINESS_CODE%][%HOW%][%WHAT%][%BATCH_NAME%]'
);
$this->writeLog4php($logger, $logLine, $error_level);
}
}
}
}
}
/**
*
* write a log entry with a specific log level
* @param object $logger Log4php logger
* @param string $logLine Line we want to trace
* @param enum $level Log level
*/
function writeLog4php($logger, $logLine, $level) {
switch ($level) {
case 'DEBUG':
$logger->debug($logLine);
break;
case 'INFO':
$logger->info($logLine);
break;
case 'WARNING':
$logger->warn($logLine);
break;
case 'ERROR':
$logger->error($logLine);
break;
case 'FATAL':
$logger->fatal($logLine);
break;
}
}
/** Adds a new handler in the current handlers array
*
* @param $handler (object) Handler object
**/
public function add_handler(&$handler, $error_level = NULL)
{
if(!isset($handler))
return false;
if(!isset($error_level) || !array_key_exists($error_level, $this->error_levels))
{
$error_level = $this->threshold_level;
}
$this->mapping[$this->error_levels[$error_level]][] = $handler;
return true;
}
/** Adds a new handler in the current handlers array
*
* @param $handler (object) Handler object
**/
public function change_handler_log_level(&$handler, $log_level )
{
if (!isset($handler) || !isset($log_level))
return false;
if (!array_key_exists($log_level, $this->error_levels)) {
return false;
}
for ($i=0; $i<count($this->mapping);$i++) {
for($j=0;$j<count($this->mapping[$i]);$j++) {
if($handler == $this->mapping[$i][$j]) {
unset($this->mapping[$i][$j]);
}
}
}
$this->mapping = array_values($this->mapping);
$this->mapping[$this->error_levels[$log_level]][] = $handler;
return true;
}
/** Sets treshold level
*
* @param $treshold (string) treshold level
**/
public function set_threshold_level($treshold)
{
if (isset($treshold) && array_key_exists($treshold, $this->error_levels)) {
$this->threshold_level = $treshold;
return true;
}
$this->threshold_level = 'WARNING';
return false;
}
/** Sets log4Php library path
*
* @param $log4PhpLibrary (string) path
**/
public function set_log4PhpLibrary($log4PhpLibrary)
{
if (isset($log4PhpLibrary) && !empty($log4PhpLibrary)) {
if (file_exists($log4PhpLibrary)) {
$this->log4PhpLibrary = $log4PhpLibrary;
return true;
} else {
return false;
}
}
return false;
}
/** Sets log4php logger name
*
* @param $log4PhpLogger (string) logger name
**/
public function set_log4PhpLogger($log4PhpLogger)
{
if (isset($log4PhpLogger) && !empty($log4PhpLogger)) {
$this->log4PhpLogger = $log4PhpLogger;
return true;
}
$this->log4PhpLogger = 'loggerTechnique';
return false;
}
/** Sets log4php path to log4php xml config
*
* @param $log4PhpPath (string) path to log4php xml config
**/
public function set_log4PhpConfigPath($log4PhpConfigPath)
{
if (isset($log4PhpConfigPath) && !empty($log4PhpConfigPath)) {
if (file_exists($log4PhpConfigPath)) {
$this->log4PhpConfigPath = $log4PhpConfigPath;
return true;
} else {
return false;
}
}
return false;
}
/** Sets log4php business code
*
* @param $log4PhpBusinessCode (string) business code
**/
public function set_log4PhpBusinessCode($log4PhpBusinessCode)
{
if (isset($log4PhpBusinessCode) && !empty($log4PhpBusinessCode)) {
$this->log4PhpBusinessCode = $log4PhpBusinessCode;
return true;
}
$this->log4PhpBusinessCode = 'Maarch';
return false;
}
/** Sets log4php batch name
*
* @param $log4PhpBatchName (string) BatchName
**/
public function set_log4PhpBatchName($log4PhpBatchName)
{
if (isset($log4PhpBatchName) && !empty($log4PhpBatchName)) {
$this->log4PhpBatchName = $log4PhpBatchName;
return true;
}
$this->log4PhpBatchName = 'MaarchBatch';
return false;
}
/** Class destructor
*
* Calls handlers destructors
**/
function __destruct()
{
for($i=0; $i<count($this->mapping);$i++)
{
foreach($this->mapping[$i] as $handler)
{
unset($handler);
}
}
}
}
...@@ -151,7 +151,7 @@ while ($state != 'END') { ...@@ -151,7 +151,7 @@ while ($state != 'END') {
preg_match_all('#\[(\w+)]#', $event['event_info'], $result); preg_match_all('#\[(\w+)]#', $event['event_info'], $result);
$basket_id = $result[1]; $basket_id = $result[1];
if ($event['table_name'] == $coll_table || $event['table_name'] == $coll_view) { if ($event['table_name'] == 'res_letterbox' || $event['table_name'] == 'res_view_letterbox') {
$res_id = $event['record_id']; $res_id = $event['record_id'];
} else { } else {
continue; continue;
...@@ -191,9 +191,9 @@ while ($state != 'END') { ...@@ -191,9 +191,9 @@ while ($state != 'END') {
'events' => $basket_list['events'], 'events' => $basket_list['events'],
'notification' => $notification, 'notification' => $notification,
'maarchUrl' => $maarchUrl, 'maarchUrl' => $maarchUrl,
'coll_id' => $coll_id, 'coll_id' => 'letterbox_coll',
'res_table' => $coll_table, 'res_table' => 'res_letterbox',
'res_view' => $coll_view, 'res_view' => 'res_view_letterbox',
); );
$html = \ContentManagement\controllers\MergeController::mergeNotification(['templateId' => $notification['template_id'], 'params' => $params]); $html = \ContentManagement\controllers\MergeController::mergeNotification(['templateId' => $notification['template_id'], 'params' => $params]);
......
...@@ -113,10 +113,6 @@ try { ...@@ -113,10 +113,6 @@ try {
\SrcCore\models\DatabasePDO::reset(); \SrcCore\models\DatabasePDO::reset();
new \SrcCore\models\DatabasePDO(['customId' => $customID]); new \SrcCore\models\DatabasePDO(['customId' => $customID]);
$coll_id = 'letterbox_coll';
$coll_table = 'res_letterbox';
$coll_view = 'res_view_letterbox';
$GLOBALS['errorLckFile'] = $GLOBALS['batchDirectory'] . DIRECTORY_SEPARATOR $GLOBALS['errorLckFile'] = $GLOBALS['batchDirectory'] . DIRECTORY_SEPARATOR
. $customIDPath . $GLOBALS['batchName'] . '_error.lck'; . $customIDPath . $GLOBALS['batchName'] . '_error.lck';
$GLOBALS['lckFile'] = $GLOBALS['batchDirectory'] . DIRECTORY_SEPARATOR $GLOBALS['lckFile'] = $GLOBALS['batchDirectory'] . DIRECTORY_SEPARATOR
......
...@@ -113,10 +113,6 @@ try { ...@@ -113,10 +113,6 @@ try {
\SrcCore\models\DatabasePDO::reset(); \SrcCore\models\DatabasePDO::reset();
new \SrcCore\models\DatabasePDO(['customId' => $customID]); new \SrcCore\models\DatabasePDO(['customId' => $customID]);
$coll_id = 'letterbox_coll';
$coll_table = 'res_letterbox';
$coll_view = 'res_view_letterbox';
$GLOBALS['errorLckFile'] = $GLOBALS['batchDirectory'] . DIRECTORY_SEPARATOR $GLOBALS['errorLckFile'] = $GLOBALS['batchDirectory'] . DIRECTORY_SEPARATOR
. $customIDPath . $GLOBALS['batchName'] . '_error.lck'; . $customIDPath . $GLOBALS['batchName'] . '_error.lck';
$GLOBALS['lckFile'] = $GLOBALS['batchDirectory'] . DIRECTORY_SEPARATOR $GLOBALS['lckFile'] = $GLOBALS['batchDirectory'] . DIRECTORY_SEPARATOR
......
...@@ -98,10 +98,6 @@ $GLOBALS['batchDirectory'] = $maarchDirectory . 'modules' ...@@ -98,10 +98,6 @@ $GLOBALS['batchDirectory'] = $maarchDirectory . 'modules'
set_include_path(get_include_path() . PATH_SEPARATOR . $maarchDirectory); set_include_path(get_include_path() . PATH_SEPARATOR . $maarchDirectory);
// COLLECTION
$collTable = 'res_letterbox';
$collView = 'res_view_letterbox';
// INCLUDES // INCLUDES
try { try {
Bt_myInclude($GLOBALS['maarchDirectory'] . 'vendor/autoload.php'); Bt_myInclude($GLOBALS['maarchDirectory'] . 'vendor/autoload.php');
...@@ -113,8 +109,6 @@ try { ...@@ -113,8 +109,6 @@ try {
exit(); exit();
} }
$alert_engine = new alert_engine($GLOBALS['configFile']);
$GLOBALS['errorLckFile'] = $GLOBALS['batchDirectory'] . DIRECTORY_SEPARATOR $GLOBALS['errorLckFile'] = $GLOBALS['batchDirectory'] . DIRECTORY_SEPARATOR
. $customIDPath . $GLOBALS['batchName'] . '_error.lck'; . $customIDPath . $GLOBALS['batchName'] . '_error.lck';
$GLOBALS['lckFile'] = $GLOBALS['batchDirectory'] . DIRECTORY_SEPARATOR $GLOBALS['lckFile'] = $GLOBALS['batchDirectory'] . DIRECTORY_SEPARATOR
......
...@@ -66,7 +66,7 @@ while ($state != 'END') { ...@@ -66,7 +66,7 @@ while ($state != 'END') {
// Diffusion type specific res_id // Diffusion type specific res_id
Bt_writeLog(['level' => 'INFO', 'message' => "Getting document ids using diffusion type '".$notification['diffusion_type']."'"]); Bt_writeLog(['level' => 'INFO', 'message' => "Getting document ids using diffusion type '".$notification['diffusion_type']."'"]);
$res_id = false; $res_id = false;
if ($event['table_name'] == $coll_table || $event['table_name'] == $coll_view) { if ($event['table_name'] == 'res_letterbox' || $event['table_name'] == 'res_view_letterbox') {
$res_id = $event['record_id']; $res_id = $event['record_id'];
} else { } else {
$res_id = \Notification\controllers\DiffusionTypesController::getItemsToNotify(['request' => 'res_id', 'notification' => $notification, 'event' => $event]); $res_id = \Notification\controllers\DiffusionTypesController::getItemsToNotify(['request' => 'res_id', 'notification' => $notification, 'event' => $event]);
...@@ -121,7 +121,7 @@ while ($state != 'END') { ...@@ -121,7 +121,7 @@ while ($state != 'END') {
} }
if (count($recipients) === 0) { if (count($recipients) === 0) {
Bt_writeLog(['level' => 'WARNING', 'message' => 'No recipient found']); Bt_writeLog(['level' => 'WARN', 'message' => 'No recipient found']);
\Notification\models\NotificationsEventsModel::update([ \Notification\models\NotificationsEventsModel::update([
'set' => ['exec_date' => 'CURRENT_TIMESTAMP', 'exec_result' => 'INFO: no recipient found'], 'set' => ['exec_date' => 'CURRENT_TIMESTAMP', 'exec_result' => 'INFO: no recipient found'],
'where' => ['event_stack_sid = ?'], 'where' => ['event_stack_sid = ?'],
...@@ -153,9 +153,9 @@ while ($state != 'END') { ...@@ -153,9 +153,9 @@ while ($state != 'END') {
'events' => $tmpNotif['events'], 'events' => $tmpNotif['events'],
'notification' => $notification, 'notification' => $notification,
'maarchUrl' => $maarchUrl, 'maarchUrl' => $maarchUrl,
'coll_id' => $coll_id, 'coll_id' => 'letterbox_coll',
'res_table' => $coll_table, 'res_table' => 'res_letterbox',
'res_view' => $coll_view, 'res_view' => 'res_view_letterbox',
); );
$html = \ContentManagement\controllers\MergeController::mergeNotification(['templateId' => $notification['template_id'], 'params' => $params]); $html = \ContentManagement\controllers\MergeController::mergeNotification(['templateId' => $notification['template_id'], 'params' => $params]);
if (strlen($html) === 0) { if (strlen($html) === 0) {
......
...@@ -7,170 +7,121 @@ include('load_stack_letterbox_alerts.php'); ...@@ -7,170 +7,121 @@ include('load_stack_letterbox_alerts.php');
$state = 'LOAD_ALERTS_NOTIFS'; $state = 'LOAD_ALERTS_NOTIFS';
while ($state <> 'END') { while ($state <> 'END') {
if (isset($GLOBALS['logger'])) { Bt_writeLog(['level' => 'INFO', 'message' => 'STATE:' . $state]);
$GLOBALS['logger']->write('STATE:' . $state, 'INFO');
}
switch ($state) { switch ($state) {
/**********************************************************************/ /**********************************************************************/
/* LOAD_ALERTS_NOTIFS */ /* LOAD_ALERTS_NOTIFS */
/* Load parameters */ /* Load parameters */
/**********************************************************************/ /**********************************************************************/
case 'LOAD_ALERTS_NOTIFS' : case 'LOAD_ALERTS_NOTIFS':
$query = "SELECT count(1) as count FROM " $alertRecordset = \Notification\models\NotificationModel::get(['select' => ['notification_sid', 'event_id'], 'where' => ['event_id in (?)'], 'data' => [['alert1', 'alert2']]]);
. _NOTIFICATIONS_TABLE_NAME if (empty($alertRecordset)) {
. " WHERE event_id IN ('alert1', 'alert2') "; Bt_exitBatch(0, 'No alert set');
$stmt = Bt_doQuery($db, $query); }
$totalAlertsToProcess = $stmt->fetchObject()->count; Bt_writeLog(['level' => 'INFO', 'message' => count($alertRecordset) . " notifications set for mail alerts"]);
$query = "SELECT notification_sid, event_id FROM "
. _NOTIFICATIONS_TABLE_NAME $alertNotifs = [];
. " WHERE event_id IN ('alert1', 'alert2') "; foreach ($alertRecordset as $value) {
$stmt = Bt_doQuery($db, $query); $alertNotifs[$value['event_id']][] = $value['notification_sid'];
if ($totalAlertsToProcess === 0) { }
Bt_exitBatch(0, 'No alert parametered'); $state = 'LOAD_DOCTYPES';
} break;
$logger->write($totalAlertsToProcess . " notifications parametered for mail alerts", 'INFO');
$GLOBALS['alert_notifs'] = array();
while ($alertRecordset = $stmt->fetchObject()) {
$GLOBALS['alert_notifs'][$alertRecordset->event_id][] = $alertRecordset->notification_sid;
}
$state = 'LOAD_DOCTYPES';
break;
/**********************************************************************/
/* LOAD_DOCTYPES */
/* Load parameters */
/**********************************************************************/
case 'LOAD_DOCTYPES' :
$query = "SELECT count(1) as count FROM doctypes";
$stmt = Bt_doQuery($db, $query);
$totalDocTypes = $stmt->fetchObject()->count;
$query = "SELECT * FROM doctypes";
$stmt = Bt_doQuery($db, $query);
$GLOBALS['doctypes'] = array();
while ($doctypeRecordset = $stmt->fetchObject()) {
$GLOBALS['doctypes'][$doctypeRecordset->type_id] = $doctypeRecordset;
}
$logger->write($totalDocTypes . " document types parametered", 'INFO');
$state = 'LIST_DOCS';
break;
/**********************************************************************/
/* LIST_DOCS */
/* List the resources to proccess for alarms */
/**********************************************************************/
case 'LIST_DOCS' :
$query = "SELECT count(1) as count"
. " FROM " . $collView
. " WHERE closing_date IS null"
. " AND status NOT IN ('CLO', 'DEL', 'END')"
. " AND (flag_alarm1 = 'N' OR flag_alarm2 = 'N')"
. " AND process_limit_date IS NOT NULL";
$stmt = Bt_doQuery($GLOBALS['db'], $query);
$totalDocsToProcess = $stmt->fetchObject()->count;
$query = "SELECT res_id, type_id, process_limit_date, flag_alarm1, flag_alarm2"
. " FROM " . $collView
. " WHERE closing_date IS null"
. " AND status NOT IN ('CLO', 'DEL', 'END')"
. " AND (flag_alarm1 = 'N' OR flag_alarm2 = 'N')"
. " AND process_limit_date IS NOT NULL";
$stmt = Bt_doQuery($GLOBALS['db'], $query);
$currentDoc = 0;
if ($totalDocsToProcess === 0) {
Bt_exitBatch(0, 'No document to process');
}
$logger->write($totalDocsToProcess . " documents to process (i.e. not closed, at least one alert to send)", 'INFO');
$GLOBALS['docs'] = array();
while ($DocRecordset = $stmt->fetchObject()) {
$GLOBALS['docs'][] = $DocRecordset;
}
$state = 'A_DOC';
break;
/**********************************************************************/ /**********************************************************************/
/* A_DOC */ /* LOAD_DOCTYPES */
/* Add notification to event_stack for each notif to be sent */ /* Load parameters */
/**********************************************************************/ /**********************************************************************/
case 'A_DOC' : case 'LOAD_DOCTYPES':
if($currentDoc < $totalDocsToProcess) { $doctypes = \Doctype\models\DoctypeModel::get();
$myDoc = $GLOBALS['docs'][$currentDoc]; $doctypes = array_column($doctypes, null, 'type_id');
$myDoc->process_limit_date = str_replace("-", "/", $db->format_date($myDoc->process_limit_date)); Bt_writeLog(['level' => 'INFO', 'message' => count($doctypes) . " document types set"]);
$logger->write("Processing document #" . $myDoc->res_id, 'INFO'); $state = 'LIST_DOCS';
break;
$myDoctype = $GLOBALS['doctypes'][$myDoc->type_id]; /**********************************************************************/
if(!$myDoctype) { /* LIST_DOCS */
Bt_exitBatch(1, 'Unknown document type ' . $myDoc->type_id); /* List the resources to proccess for alarms */
/**********************************************************************/
case 'LIST_DOCS':
$resources = \Resource\models\ResModel::get([
'select' => ['res_id', 'type_id', 'process_limit_date', 'flag_alarm1', 'flag_alarm2'],
'where' => ['closing_date IS null', 'status NOT IN (?)', '(flag_alarm1 = \'N\' OR flag_alarm2 = \'N\')', 'process_limit_date IS NOT NULL'],
'data' => [['CLO', 'DEL', 'END']]
]);
if (empty($resources)) {
Bt_exitBatch(0, 'No document to process');
} }
$logger->write("Document type id is #" . $myDoc->type_id, 'INFO'); $totalDocsToProcess = count($resources);
Bt_writeLog(['level' => 'INFO', 'message' => $totalDocsToProcess . " documents to process (i.e. not closed, at least one alert to send)"]);
$state = 'A_DOC';
break;
// Alert 1 = limit - n days /**********************************************************************/
if($myDoc->flag_alarm1 != 'Y' && $myDoc->flag_alarm2 != 'Y') { /* A_DOC */
$convertedDate = $alert_engine->dateFR2Time($myDoc->process_limit_date); /* Add notification to event_stack for each notif to be sent */
$date = $alert_engine->WhenOpenDay($convertedDate, (integer)$myDoctype->delay1, true); /**********************************************************************/
$process_date = $db->dateformat($date, '-'); case 'A_DOC':
echo PHP_EOL . "$myDoc->process_limit_date - " . (integer)$myDoctype->delay1 . " days : " . $process_date; foreach ($resources as $myDoc) {
$compare = $alert_engine->compare_date($process_date, date("d-m-Y")); Bt_writeLog(['level' => 'INFO', 'message' => "Processing document #" . $myDoc['res_id']]);
echo PHP_EOL . $compare;
if($compare == 'date2' || $compare == 'equal') { $myDoctype = $doctypes[$myDoc['type_id']];
$logger->write("Alarm 1 will be sent", 'INFO'); if (!$myDoctype) {
$info = 'Relance 1 pour traitement du document No' . $myDoc->res_id . ' avant date limite.'; Bt_writeLog(['level' => 'WARN', 'message' => 'Unknown document type ' . $myDoc['type_id']]);
if(count($GLOBALS['alert_notifs']['alert1']) > 0) { continue;
foreach($GLOBALS['alert_notifs']['alert1'] as $notification_sid) { }
$query = "INSERT INTO " . _NOTIF_EVENT_STACK_TABLE_NAME Bt_writeLog(['level' => 'INFO', 'message' => "Document type id is #" . $myDoc['type_id']]);
. " (notification_sid, table_name, record_id, user_id, event_info" $user = \User\models\UserModel::getByLogin(['login' => 'superadmin', 'select' => ['id']]);
. ", event_date)"
. " VALUES(" . $notification_sid . ", '" // Alert 1 = limit - n days
. $collView . "', '" . $myDoc->res_id . "', 'superadmin', '" . $info . "', " if ($myDoc['flag_alarm1'] != 'Y' && $myDoc['flag_alarm2'] != 'Y') {
. $db->current_datetime() . ")"; $processDate = \Resource\controllers\IndexingController::calculateProcessDate(['date' => $myDoc['process_limit_date'], 'delay' => $myDoctype['delay1'], 'sub' => true]);
Bt_doQuery($db, $query); if (strtotime($processDate) <= time()) {
Bt_writeLog(['level' => 'INFO', 'message' => "Alarm 1 will be sent"]);
$info = 'Relance 1 pour traitement du document No' . $myDoc['res_id'] . ' avant date limite.';
if (count($alertNotifs['alert1']) > 0) {
foreach ($alertNotifs['alert1'] as $notification_sid) {
\Notification\models\NotificationsEventsModel::create([
'notification_sid' => $notification_sid,
'table_name' => 'res_view_letterbox',
'record_id' => $myDoc['res_id'],
'user_id' => $user['id'],
'event_info' => $info
]);
}
} }
\Resource\models\ResModel::update(['set' => ['flag_alarm1' => 'Y', 'alarm1_date' => 'CURRENT_TIMESTAMP'], 'where' => ['res_id = ?'], 'data' => [$myDoc['res_id']]]);
} }
$query = "UPDATE res_letterbox SET flag_alarm1 = 'Y', alarm1_date = " . $db->current_datetime()
. " WHERE res_id = " . $myDoc->res_id;
Bt_doQuery($db, $query);
} }
}
// Alert 2 = limit + n days // Alert 2 = limit + n days
if($myDoc->flag_alarm2 != 'Y') { if ($myDoc['flag_alarm2'] != 'Y') {
$convertedDate = $alert_engine->dateFR2Time($myDoc->process_limit_date); $processDate = \Resource\controllers\IndexingController::calculateProcessDate(['date' => $myDoc['process_limit_date'], 'delay' => $myDoctype['delay2']]);
$date = $alert_engine->WhenOpenDay($convertedDate, (integer)$myDoctype->delay2); if (strtotime($processDate) <= time()) {
$process_date = $db->dateformat($date, '-'); Bt_writeLog(['level' => 'INFO', 'message' => "Alarm 2 will be sent"]);
echo PHP_EOL . "$myDoc->process_limit_date + " . (integer)$myDoctype->delay2 . " days : " . $process_date; $info = 'Relance 2 pour traitement du document No' . $myDoc['res_id'] . ' apres date limite.';
$compare = $alert_engine->compare_date($process_date, date("d-m-Y")); if (count($alertNotifs['alert2']) > 0) {
echo PHP_EOL . $compare; foreach ($alertNotifs['alert2'] as $notification_sid) {
if($compare == 'date2' || $compare == 'equal') { \Notification\models\NotificationsEventsModel::create([
$logger->write("Alarm 2 will be sent", 'INFO'); 'notification_sid' => $notification_sid,
$info = 'Relance 2 pour traitement du document No' . $myDoc->res_id . ' apres date limite.'; 'table_name' => 'res_view_letterbox',
if(count($GLOBALS['alert_notifs']['alert2']) > 0) { 'record_id' => $myDoc['res_id'],
foreach($GLOBALS['alert_notifs']['alert2'] as $notification_sid) { 'user_id' => $user['id'],
$query = "INSERT INTO " . _NOTIF_EVENT_STACK_TABLE_NAME 'event_info' => $info
. " (notification_sid, table_name, record_id, user_id, event_info" ]);
. ", event_date)" }
. " VALUES(" . $notification_sid . ", '"
. $collView . "', '" . $myDoc->res_id . "', 'superadmin', '" . $info . "', "
. $db->current_datetime() . ")";
Bt_doQuery($db, $query);
} }
\Resource\models\ResModel::update(['set' => ['flag_alarm1' => 'Y', 'flag_alarm2' => 'Y', 'alarm2_date' => 'CURRENT_TIMESTAMP'], 'where' => ['res_id = ?'], 'data' => [$myDoc['res_id']]]);
} }
$query = "UPDATE res_letterbox SET flag_alarm1 = 'Y', flag_alarm2 = 'Y', alarm2_date = " . $db->current_datetime()
. " WHERE res_id = " . $myDoc->res_id;
Bt_doQuery($db, $query);
} }
} }
$currentDoc++;
$state = 'A_DOC';
} else {
$state = 'END'; $state = 'END';
} break;
break;
} }
} }
$GLOBALS['logger']->write('End of process', 'INFO'); Bt_writeLog(['level' => 'INFO', 'message' => 'End of process']);
Bt_logInDataBase( Bt_logInDataBase($totalDocsToProcess, 0, 'process without error');
$totalDocsToProcess, 0, 'process without error'
);
//$GLOBALS['db']->disconnect();
unlink($GLOBALS['lckFile']); unlink($GLOBALS['lckFile']);
exit($GLOBALS['exitCode']); exit($GLOBALS['exitCode']);
?>
...@@ -33,7 +33,6 @@ class DocserverTypeModelAbstract ...@@ -33,7 +33,6 @@ class DocserverTypeModelAbstract
'limit' => empty($aArgs['limit']) ? 0 : $aArgs['limit'] 'limit' => empty($aArgs['limit']) ? 0 : $aArgs['limit']
]); ]);
return $aDocserverTypes; return $aDocserverTypes;
} }
......
...@@ -25,11 +25,16 @@ abstract class NotificationModelAbstract ...@@ -25,11 +25,16 @@ abstract class NotificationModelAbstract
{ {
public static function get(array $aArgs = []) public static function get(array $aArgs = [])
{ {
ValidatorModel::arrayType($aArgs, ['select']); ValidatorModel::arrayType($aArgs, ['select', 'where', 'orderBy']);
ValidatorModel::intType($aArgs, ['limit']);
$aNotifications = DatabaseModel::select([ $aNotifications = DatabaseModel::select([
'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'],
'table' => ['notifications'], 'table' => ['notifications'],
'where' => empty($aArgs['where']) ? [] : $aArgs['where'],
'data' => empty($aArgs['data']) ? [] : $aArgs['data'],
'order_by' => empty($aArgs['orderBy']) ? [] : $aArgs['orderBy'],
'limit' => empty($aArgs['limit']) ? 0 : $aArgs['limit']
]); ]);
return $aNotifications; return $aNotifications;
......
...@@ -360,7 +360,11 @@ class IndexingController ...@@ -360,7 +360,11 @@ class IndexingController
$processDelayUpdated = 1; $processDelayUpdated = 1;
for ($i = 1; $i <= $args['delay']; $i++) { for ($i = 1; $i <= $args['delay']; $i++) {
$tmpDate = new \DateTime($args['date']); $tmpDate = new \DateTime($args['date']);
$tmpDate->add(new \DateInterval("P{$i}D")); if ($args['sub']) {
$tmpDate->sub(new \DateInterval("P{$i}D"));
} else {
$tmpDate->add(new \DateInterval("P{$i}D"));
}
if (in_array($tmpDate->format('N'), [6, 7]) || in_array($tmpDate->format('d-m'), $hollidays)) { if (in_array($tmpDate->format('N'), [6, 7]) || in_array($tmpDate->format('d-m'), $hollidays)) {
++$args['delay']; ++$args['delay'];
} }
...@@ -369,10 +373,18 @@ class IndexingController ...@@ -369,10 +373,18 @@ class IndexingController
} }
} }
$date->add(new \DateInterval("P{$processDelayUpdated}D")); if ($args['sub']) {
$date->sub(new \DateInterval("P{$processDelayUpdated}D"));
} else {
$date->add(new \DateInterval("P{$processDelayUpdated}D"));
}
} else { } else {
// Calendar or empty delay // Calendar or empty delay
$date->add(new \DateInterval("P{$args['delay']}D")); if ($args['sub']) {
$date->sub(new \DateInterval("P{$args['delay']}D"));
} else {
$date->add(new \DateInterval("P{$args['delay']}D"));
}
} }
return $date->format('Y-m-d'); return $date->format('Y-m-d');
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment