Sfoglia il codice sorgente

fixed bug in Notify

Piotr Labudda 8 anni fa
parent
commit
10eea1f507

+ 1 - 1
SE/bash_install_check.php

@@ -52,7 +52,7 @@ $token = Router::getRoute('Cron')->generateCliAuthToken($keyToken, $cronTaskName
 $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE";
 if ('biuro.biall-net.pl' == $_SERVER['SERVER_NAME']) $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE/version-git";
 
-//file_get_contents("https://{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task=sendNofity");
+//file_get_contents("https://{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task=sendNotify");
 function runUrlTask($url) {
 	$ch = curl_init();
 	curl_setopt($ch, CURLOPT_VERBOSE, true);

+ 5 - 5
SE/bash_sync_perms.php

@@ -217,7 +217,7 @@ class SyncPerms {
 		else if ($arg2 == 'users') self::usersAction();
 		else if ($arg2 == 'usersAll') self::usersAllAction();
 		else if ($arg2 == 'SyncPermsCustomTables') self::task__SyncPermsCustomTables();
-		else if ($arg2 == 'sendNofity') self::sendNofity();
+		else if ($arg2 == 'sendNotify') self::sendNotify();
 		else self::task__default();
 	}
 
@@ -450,7 +450,7 @@ class SyncPerms {
 			$dbgTime->lastTime = $dbgTime->curTime;
 		}
 
-		self::sendNofity();
+		self::sendNotify();
 
 		Lib::loadClass('Router');
 		echo "DBG: UrlAction_WmsGenerate->doGenerate() START...\n";
@@ -458,9 +458,9 @@ class SyncPerms {
 		echo "DBG: UrlAction_WmsGenerate->doGenerate() END\n";
 	}
 
-	public static function sendNofity() {
+	public static function sendNotify() {
 		Lib::loadClass('Router');
-		$cronTaskName = 'sendNofity';
+		$cronTaskName = 'sendNotify';
 		$keyToken = 'bach_sync_perms';
 		$token = Router::getRoute('Cron')->generateCliAuthToken($keyToken, $cronTaskName, 300 * 10);
 		echo "DBG: token = '{$token}'" . "\n";
@@ -468,7 +468,7 @@ class SyncPerms {
 		$baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE";
 		if ('biuro.biall-net.pl' == $_SERVER['SERVER_NAME']) $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE/version-git";
 
-		//file_get_contents("https://{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task=sendNofity");
+		//file_get_contents("https://{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task=sendNotify");
 
 		function runUrlTask($url) {
 		  $ch = curl_init();

+ 3 - 3
SE/se-lib/Route/Cron-test.php

@@ -10,7 +10,7 @@ if (isset($_SERVER["argv"][1])) {
 
 Lib::loadClass('Router');
 $keyToken = 'bach_sync_perms';
-$token = Router::getRoute('Cron')->generateCliAuthToken($keyToken, 'sendNofity', 300 * 10);
+$token = Router::getRoute('Cron')->generateCliAuthToken($keyToken, 'sendNotify', 300 * 10);
 echo "DBG: token = '{$token}'" . "\n";
 
 //echo "DBG: IP(biuro.biall-net.pl) = '" . gethostbyname('biuro.biall-net.pl') . "'" . "\n";
@@ -20,7 +20,7 @@ $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE";
 if ('biuro.biall-net.pl' == $_SERVER['SERVER_NAME']) $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE/version-git";
 //if ('biuro.biall-net.pl' == $_SERVER['SERVER_NAME']) $baseUrl = "https://{$_SERVER['SERVER_NAME']}/dev-pl/se-master";
 
-//file_get_contents("https://{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task=sendNofity");
+//file_get_contents("https://{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task=sendNotify");
 
 function runUrlTask($url) {
   $ch = curl_init();
@@ -33,7 +33,7 @@ function runUrlTask($url) {
   curl_close($ch);
   return $return;
 }
-$string = runUrlTask("{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task=sendNofity");
+$string = runUrlTask("{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task=sendNotify");
 echo "DBG: string -----------------------\n{$string}\nEOF string---------------------------------\n";
 
 die("\n\n.EOF\n");

+ 40 - 37
SE/se-lib/Route/Cron.php

@@ -23,36 +23,36 @@ class Route_Cron extends RouteBase {
 
 	public function generateCliAuthToken($cliKey, $task, $ttl = 300) {
 		$generatedToken = uniqid();
-    $parts = array();
-    $parts[] = $generatedToken;
+		$parts = array();
+		$parts[] = $generatedToken;
 		$parts[] = $task;
-    $parts[] = $ttl;
-    $parts[] = time();
-    $token = implode(",", $parts);
+		$parts[] = $ttl;
+		$parts[] = time();
+		$token = implode(",", $parts);
 		$sqlCliKey = "CronCliAuthToken:{$cliKey}";
-    $sth = DB::getPDO()->prepare("
-      insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
-        values ( :cliKey, :token )
-        on duplicate key update CONF_VAL = :token
-    ");
+		$sth = DB::getPDO()->prepare("
+			insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
+			values ( :cliKey, :token )
+			on duplicate key update CONF_VAL = :token
+		");
 		$sth->bindValue(':cliKey', $sqlCliKey, PDO::PARAM_STR);
 		$sth->bindValue(':token', $token, PDO::PARAM_STR);
 		$sth->execute();
-    return $generatedToken;
-  }
+		return $generatedToken;
+	}
 
 	public function authByToken() {
 		$cliKey = V::get('_key', '', $_REQUEST);
-    $cliToken = V::get('_token', '', $_REQUEST);
+		$cliToken = V::get('_token', '', $_REQUEST);
 
 		$sqlCliKey = "CronCliAuthToken:{$cliKey}";
 		$sth = DB::getPDO()->prepare("
-      select c.CONF_VAL
+			select c.CONF_VAL
 			from CRM_CONFIG c
-      where CONF_KEY = :cliKey
+			where CONF_KEY = :cliKey
 			order by c.ID desc
 			limit 1
-    ");
+		");
 		$sth->bindValue(':cliKey', $sqlCliKey, PDO::PARAM_STR);
 		$sth->execute();
 		$rawToken = $sth->fetch();
@@ -79,48 +79,51 @@ class Route_Cron extends RouteBase {
 		$_SESSION['ADM_NAME'] = 'Anonymous';
 		$_SESSION['ADM_ACCOUNT'] = $_SERVER['REMOTE_ADDR'];
 		$_SESSION['ADM_ADMIN_LEVEL'] = 10;
+		$_SESSION['ADM_ID'] = 9999999999;
 		DBG::_('DBG_CRON', '>1', 'rawToken', array('createDateTimestamp'=>$createDateTimestamp, 'ttl'=>$ttl, 'cur'=>time()), __CLASS__, __FUNCTION__, __LINE__);
 		$this->runTask($task);
   }
 
 	public function defaultAction() {
-		SE_Layout::gora();
-		?>
-<div class="container">
-	<h1>Cron</h1>
-	...
-</div>
-		<?php
-		SE_Layout::dol();
+		Lib::loadClass('UI');
+		UI::gora();
+		echo UI::h('div', [ 'class' => "container" ], [
+			UI::h('h1', [], "Cron"),
+			"...",
+		]);
+		UI::dol();
 	}
 
 	public function dbgClearNofityAction() {
-		SE_Layout::gora();
+		Lib::loadClass('UI');
+		UI::gora();
 		try {
-			DB::getPDO()->exec("update `CRM_NOTIFY` set `last_exec_time` = null");
-			SE_Layout::alert('info', "Notify cleared");
+			DB::getPDO()->execSql("update `CRM_NOTIFY` set `last_exec_time` = null");
+			UI::alert('info', "Notify cleared");
 		} catch (Exception $e) {
-			SE_Layout::alert('danger', "Error: " . $e->getMessage());
+			UI::alert('danger', "Error: " . $e->getMessage());
 		}
-		SE_Layout::dol();
+		UI::dol();
 	}
 
 	public function dbgChangeNofityToDayBeforeAction() {
-		SE_Layout::gora();
+		Lib::loadClass('UI');
+		UI::gora();
 		try {
-			DB::getPDO()->exec("update `CRM_NOTIFY` set `last_exec_time` = DATE_SUB(NOW(), INTERVAL 1 DAY)");
-			SE_Layout::alert('info', "Notify cleared");
+			DB::getPDO()->execSql("update `CRM_NOTIFY` set `last_exec_time` = DATE_SUB(NOW(), INTERVAL 1 DAY)");
+			UI::alert('info', "Notify cleared");
 		} catch (Exception $e) {
-			SE_Layout::alert('danger', "Error: " . $e->getMessage());
+			UI::alert('danger', "Error: " . $e->getMessage());
 		}
-		SE_Layout::dol();
+		UI::dol();
 	}
 
-	public function sendNofityAction() {
+	public function sendNotifyAction() {
+		Lib::loadClass('UI');
 		$notify = Router::getRoute('Notify');
 		$todoReminders = array();
 
-		if (V::get('DBG_CRON', null, $_GET) > 0) SE_Layout::gora();
+		if (V::get('DBG_CRON', null, $_GET) > 0) UI::gora();
 		echo '<div class="container">' . "\n";
 		echo '<h1>Cron</h1>' . "\n";
 		try {
@@ -152,7 +155,7 @@ class Route_Cron extends RouteBase {
 			}
 			if (V::get('DBG_CRON', null, $_GET) > 0) DBG::table("reminders state - after", DB::getPDO()->fetchAll("select * from CRM_NOTIFY order by last_exec_time limit 20"), __CLASS__, __FUNCTION__, __LINE__);
 		} catch (Exception $e) {
-			SE_Layout::alert('danger', "#" . $e->getLine() . ":" . $e->getMessage());
+			UI::alert('danger', "#" . $e->getLine() . ":" . $e->getMessage());
 		}
 		echo "\n" . '</div>';// .container
 		echo "\n.EOF\n";

+ 9 - 1
SE/se-lib/Route/Debug.php

@@ -397,9 +397,11 @@ class Route_Debug extends RouteBase {
     $logPath = "{$this->logPathPrefix}se-{$type}-{$logName}.log";
     if (!file_exists($logPath)) throw new Exception("Log file not exists");
     $content = file_get_contents($logPath);
+	$lastTime = '';
     UI::table([
       'cols' => [
         'date',
+        'diff',
         'type',
         'msg',
         'log',
@@ -409,7 +411,7 @@ class Route_Debug extends RouteBase {
         'trace' => "Cick to show trace"
       ],
       'rows' => array_map(
-        function ($line) {
+        function ($line) use (&$lastTime) {
           if (empty($line)) return [];
           $dbg = @json_decode($line, $assoc = true);
           if (null == $dbg && 0 !== json_last_error()) {
@@ -418,8 +420,14 @@ class Route_Debug extends RouteBase {
               'msg' => "Error Processing Request - Parse json error: " . json_last_error()
             ];
           }
+		  $timeDiff = (!$lastTime)
+		  	? ''
+			: V::milisecondsStringDiff($dbg['date'], $lastTime)
+		  ; // TODO: $dbg['date'] - $lastTime;
+		  $lastTime = $dbg['date'];
           return [
             'date' => '<nobr>' . $dbg['date'] . '</nobr>',
+            'diff' => '<nobr>' . $timeDiff . '</nobr>',
             '@style[date]' => "width:1%",
             'type' => $dbg['type'],
             '@style[type]' => "width:1%",

+ 118 - 124
SE/se-lib/Route/Notify.php

@@ -5,7 +5,9 @@ Lib::loadClass('RouteBase');
 Lib::loadClass('Przypomnij');
 Lib::loadClass('Request');
 Lib::loadClass('TypespecialVariable');
-Lib::loadClass('Route_UserMsgs');
+Lib::loadClass('UI');
+Lib::loadClass('Router');
+Lib::loadClass('DBG');
 
 /*
 # Nofitication System:
@@ -33,21 +35,21 @@ class Route_Notify extends RouteBase {
 	}
 
 	public function defaultAction() {
-		SE_Layout::gora();
-		SE_Layout::menu();
+		UI::gora();
+		UI::menu();
 		try {
 			$usrLogin = User::getLogin();
 			$this->formUserTableReminder($usrLogin);
 		} catch (Exception $e) {
-			SE_Layout::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage());
+			UI::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage());
 		}
-		SE_Layout::dol();
+		UI::dol();
 	}
 
 	public function remindersPanelAction() {
 		$usrLogin = User::getLogin();
-		SE_Layout::gora();
-		//SE_Layout::menu();
+		UI::gora();
+		//UI::menu();
 
 		{// init args
 			$usrLogin = User::getLogin();
@@ -63,17 +65,16 @@ class Route_Notify extends RouteBase {
 		}
 
 		if ('1' == V::get('send', 0, $_POST, 'int')) {
-			SE_Layout::alert('warning', "TODO: fix send, mark as sent");
+			UI::alert('warning', "TODO: fix send, mark as sent");
 			//$this->send($usrLogin, $notifyTypeList);
 			//$this->markAsSent($usrLogin, $notifyTypeList);
 		}
 
-		$urlParts = array();// index.php?_route=Notify&_task=generateUserReminders&usrLogin=magdalena.cichosz&reminder[]=msgs
-		$urlQuery = array('_route' => "Notify"
-										, '_task' => 'generateUserReminders'
-										, 'usrLogin' => $usrLogin
-										, 'reminder' => array_values($notifyTypeList));
-		$previewLink = Request::getUriDirName() . "/index.php?" . http_build_query($urlQuery);
+		$previewLink = $this->getLink('generateUserReminders', [
+			'usrLogin' => $usrLogin,
+			'reminder' => array_values($notifyTypeList),
+		]);
+		$generateBaseLink = $this->getLink('generateUserReminders');
 
 		$lastSentDate = 'brak';// TODO: getLastSendData($usrLogin);
 		$typeSpecialUserLogin = TypespecialVariable::getInstance(-1, '__USER_LOGIN');
@@ -124,31 +125,33 @@ class Route_Notify extends RouteBase {
 		</form>
 	</div>
 </div>
-<script>
-function refreshPreview() {
-	var frm = document.getElementById('reminderPanelForm'),
-			baseUrl = '<?php echo Request::getUriDirName(); ?>',
-			previewLink = '';
-
-	previewLink = baseUrl + '/index.php?_route=Notify&_task=generateUserReminders';
-	previewLink += '&usrLogin=' + frm['usrLogin'].value;
-	for (var i in frm['reminder[]']) {
-		console.log('frm[reminder[]]['+i+']', frm['reminder[]'][i].value, ' checked:', frm['reminder[]'][i].checked);
-		if (frm['reminder[]'][i].checked) {
-			previewLink += '&reminder[]=' + frm['reminder[]'][i].value;
-		}
-	}
-	console.log('frm[reminder[]].', frm['reminder[]']);
-	console.log('frm[reminder[]].value', frm['reminder[]'].value);
-	console.log('previewLink:', previewLink);
-	document.getElementById('reminderPreview').src = previewLink;
-}
-</script>
-<div>
-	<iframe id="reminderPreview" src="<?php echo $previewLink; ?>" style="width:100%;height:500px;max-height:500px;overflow:scroll;border:2px solid silver"></iframe>
-</div>
 <?php
-		SE_Layout::dol();
+		echo UI::h('script', [], "
+			function refreshPreview() {
+				var frm = document.getElementById('reminderPanelForm'),
+					previewLink = '';
+
+				previewLink = '{$generateBaseLink}' + '&usrLogin=' + frm['usrLogin'].value;
+				for (var i in frm['reminder[]']) {
+					// console.log('frm[reminder[]]['+i+']', frm['reminder[]'][i].value, ' checked:', frm['reminder[]'][i].checked);
+					if (frm['reminder[]'][i].checked) {
+						previewLink += '&reminder[]=' + frm['reminder[]'][i].value;
+					}
+				}
+				// console.log('frm[reminder[]].', frm['reminder[]']);
+				// console.log('frm[reminder[]].value', frm['reminder[]'].value);
+				// console.log('previewLink:', previewLink);
+				document.getElementById('reminderPreview').src = previewLink;
+			}
+		");
+		echo UI::h('div', [], [
+			UI::h('iframe', [
+				'id' => "reminderPreview",
+				'src' => $previewLink,
+				'style' => "width:100%;height:500px;max-height:500px;overflow:scroll;border:2px solid silver"
+			]),
+		]);
+		UI::dol();
 	}
 
 	public function typeSpecialUserLoginAction() {
@@ -182,18 +185,18 @@ function refreshPreview() {
 	 * @param $userReminders {'once_a_day' => {$type => $last_exec_time}, 'immediately' => {$type => $last_exec_time}}
 	 */
 	public function sendUserReminders($who, $userReminders, $forceMail = null) {
-		DBG::_('DBG_NTF', '>1', "reminders.1", $userReminders, __CLASS__, __FUNCTION__, __LINE__);
+		// DBG::_('DBG_NTF', '>1', "reminders.1", $userReminders, __CLASS__, __FUNCTION__, __LINE__);
 		// remove duplicates
 		if (!empty($userReminders['once_a_day']) && !empty($userReminders['immediately'])) {
 			foreach ($userReminders['once_a_day'] as $what => $last_exec) {
 				if (array_key_exists($what, $userReminders['immediately'])) {
-					DBG::_('DBG_NTF', '>2', "skip immediately '{$what}' for '{$who}'", $userReminders['immediately'][$what], __CLASS__, __FUNCTION__, __LINE__);
+					// DBG::_('DBG_NTF', '>2', "skip immediately '{$what}' for '{$who}'", $userReminders['immediately'][$what], __CLASS__, __FUNCTION__, __LINE__);
 					unset($userReminders['immediately'][$what]);
 				}
 			}
 			if (empty($userReminders['immediately'])) unset($userReminders['immediately']);
 		}
-		DBG::_('DBG_NTF', '>1', "reminders.2", $userReminders, __CLASS__, __FUNCTION__, __LINE__);
+		// DBG::_('DBG_NTF', '>1', "reminders.2", $userReminders, __CLASS__, __FUNCTION__, __LINE__);
 		foreach ($userReminders as $when => $listWhat) {
 			if (!empty($listWhat)) {
 				$reminders = array_keys($listWhat);
@@ -256,24 +259,21 @@ function refreshPreview() {
 	}
 
 	public function getUserMainMail($usrLogin) {
-		$user = null;
-		$sth = DB::getPDO()->prepare("
-		select u.ID, u.ADM_ACCOUNT as login, u.EMAIL_LOCAL_ACCOUNT_ADDRESS as aliasy
-		from ADMIN_USERS u
-		where u.ADM_ACCOUNT = :usr_login
-		");
-		$sth->bindValue(':usr_login', $usrLogin, PDO::PARAM_STR);
-		$sth->execute();
-		$user = $sth->fetch();
+		$sqlUserLogin = DB::getPDO()->quote($usrLogin);
+		$sql = "
+			select u.ID, u.ADM_ACCOUNT as login, u.EMAIL_LOCAL_ACCOUNT_ADDRESS as aliasy
+			from ADMIN_USERS u
+			where u.ADM_ACCOUNT = {$sqlUserLogin}
+		";
+		$user = DB::getPDO()->fetchFirst($sql);
 		if (!$user) throw new Exception("User not found");
-
 		if (empty($user['aliasy'])) throw new Exception("Brak lokalnego adresu email");
 		$aliasy = explode(' ', trim($user['aliasy']));
 		return reset($aliasy);
 	}
 
 	public function markAsSent($usrLogin, $reminders, $when) {
-//		$sqlReminderTypes = "'" . implode("','", $notifyTypeList) . "'";
+		// $sqlReminderTypes = "'" . implode("','", $notifyTypeList) . "'";
 		$sqlReminderTypes = "'" . implode("','", array_keys($reminders)) . "'";
 		$sth = DB::getPDO()->prepare("
 			update CRM_NOTIFY
@@ -381,9 +381,9 @@ function refreshPreview() {
 		}
 		if (!$idTblZasob || !$idRecord) return '#';
 
-		$urlQuery = array('MENU_INIT' => "VIEWTABLE_AJAX"
-										, 'ZASOB_ID' => $idTblZasob);
-		return Request::getUriDirName() . "/index.php?" . http_build_query($urlQuery) . "#EDIT/{$idRecord}";
+		return Router::getRoute('ViewTableajax')->getLink('', [
+			'namespace' => ACL::getNamespaceFromId($idTblZasob),
+		]) . "#EDIT/{$idRecord}";
 	}
 
 	public function readMsgLink($usrLogin, $todo) {
@@ -394,11 +394,7 @@ function refreshPreview() {
 		if (!$idMsg) return '#' . json_encode($todo);
 		if (!$idMsg) return '#';
 
-		$urlQuery = array('_route' => "UserMsgs"
-											, '_task' => 'read'
-											, 'usrLogin' => $usrLogin
-											, 'id' => $idMsg);
-		return Request::getUriDirName() . "/index.php?" . http_build_query($urlQuery);
+		return Router::getRoute('UserMsgs')->getLink('read', [ 'usrLogin' => $usrLogin, 'id' => $idMsg ]);
 	}
 
 	public function inlineCss($cssSelector) {
@@ -568,9 +564,9 @@ function refreshPreview() {
 				if (!$task->_show) continue;
 				if (
 					$task->A_CLASSIFIED != ''
-					and !(in_array($task->A_CLASSIFIED, $usrGroupNames))
-					and $task->A_ADM_COMPANY != ''
-					and !(in_array($task->A_ADM_COMPANY, $usrGroupNames))
+					&& !(in_array($task->A_CLASSIFIED, $usrGroupNames))
+					&& $task->A_ADM_COMPANY != ''
+					&& !(in_array($task->A_ADM_COMPANY, $usrGroupNames))
 					// !($allowedUsers[$task->_l_app]) - to jest bez sensu - wystarczy widocznosc sprawy?
 				) {
 					continue;
@@ -610,66 +606,67 @@ function refreshPreview() {
 		if ('_add_table_reminder' == $subTask) {
 			try {
 				$this->addUserTableReminder($usrLogin, $_POST);
-				SE_Layout::alert('info', "Dodano powiadomienie");
+				UI::alert('info', "Dodano powiadomienie");
 			} catch (PDOException $e) {
 				if (!empty($e->errorInfo) && !empty($e->errorInfo[1]) && '1062' == $e->errorInfo[1]) {
-					SE_Layout::alert('warning', "Powiadomienie tego typu zostało już wcześniej dodane");
+					UI::alert('warning', "Powiadomienie tego typu zostało już wcześniej dodane");
 				} else {
-					SE_Layout::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage() . '<br>' . "Info: " . json_encode($e->errorInfo));
+					UI::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage() . '<br>' . "Info: " . json_encode($e->errorInfo));
 				}
 			} catch (Exception $e) {
-				SE_Layout::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage());
+				UI::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage());
 			}
 		}
 		else if ('_rm_table_reminder' == $subTask) {
 			try {
 				$this->removeUserTableReminder($_POST);
-				SE_Layout::alert('info', "Usunięto powiadomienie");
+				UI::alert('info', "Usunięto powiadomienie");
 			} catch (Exception $e) {
-				SE_Layout::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage());
+				UI::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage());
 			}
 		}
 		$userNotifyList = $this->getUserNotifyList($usrLogin);
 		$userMail = $this->getUserMainMail($usrLogin);
 		$whatLabelsForOnceADay = $this->getFieldValueLabels('what', $userNotifyList, $when = 'once_a_day');
 		$whatLabelsForImmediately = $this->getFieldValueLabels('what', $userNotifyList, $when = 'immediately');
-		?>
-	<h1>Powiadomienia dla <code><?php echo $usrLogin; ?></code></h1>
-	<p><i>Będą wysyłane na adres: <?php echo $userMail; ?></i></p>
-	<?php if (empty($userNotifyList)) : ?>
-		<?php SE_Layout::alert('warning', "Brak zdefiniowanych powiadomień"); ?>
-	<?php else : ?>
-		<table class="table table-hovered">
-			<thead>
-				<tr>
-					<th>rodzaj</th>
-					<th>jak często</th>
-					<th>utworzony</th>
-					<th>ostatnio uruchomiony</th>
-					<th></th>
-				</tr>
-			</thead>
-			<tbody>
-				<?php foreach ($userNotifyList as $notify) : ?>
-					<tr>
-						<td><?php echo $this->printValue('what', $notify['what']); ?></td>
-						<td><?php echo $this->printValue('when', $notify['when']); ?></td>
-						<td><?php echo $notify['_created']; ?></td>
-						<td><?php echo ($notify['last_exec_time'])? $notify['last_exec_time'] : '<i>brak danych</i>'; ?></td>
-						<td>
-							<form method="post" class="form-inline">
-								<input type="hidden" name="_subTask" value="_rm_table_reminder">
-								<input type="hidden" name="who" value="<?php echo $usrLogin; ?>">
-								<input type="hidden" name="what" value="<?php echo $notify['what']; ?>">
-								<input type="hidden" name="when" value="<?php echo $notify['when']; ?>">
-								<button class="btn btn-link btn-xs" onclick="return confirm('Czy usunąć powiadomienie?')" type="submit"><i class="glyphicon glyphicon-remove" style="color:red;opacity:0.4;"></i></button>
-							</form>
-						</td>
-					</tr>
-				<?php endforeach; ?>
-			</tbody>
-		</table>
-	<?php endif; ?>
+		echo UI::h('h1', [], "Powiadomienia dla <code>{$usrLogin}</code>");
+		echo UI::h('p', [ 'style' => "font-style:italic" ], [
+			"Będą wysyłane na adres: {$userMail}. ",
+			UI::h('a', [
+				'href' => $this->getLink('generateUserReminders', [
+					'usrLogin' => $usrLogin,
+				])
+			], 'podgląd'),
+		]);
+		if (empty($userNotifyList)) {
+			UI::alert('warning', "Brak zdefiniowanych powiadomień");
+		} else {
+			UI::table([ // <table class="table table-hover">
+				'disable_lp' => true,
+				'@class' => 'table table-hover',
+				'cell_padding' => 8,
+				'rows' => array_map(function ($notify) {
+					return [
+						'rodzaj' => $this->printValue('what', $notify['what']),
+						'jak często' => $this->printValue('when', $notify['when']),
+						'utworzony' => $notify['_created'],
+						'ostatnio uruchomiony' => $notify['last_exec_time'] ? $notify['last_exec_time'] : '<i>brak danych</i>',
+						'#' => UI::h('form', [ 'method' => "post", 'class' => "form-inline" ], [
+							UI::h('input', [ 'type' => "hidden", 'name' => "_subTask", 'value' => "_rm_table_reminder" ]),
+							UI::h('input', [ 'type' => "hidden", 'name' => "who", 'value' => $usrLogin ]),
+							UI::h('input', [ 'type' => "hidden", 'name' => "what", 'value' => $notify['what'] ]),
+							UI::h('input', [ 'type' => "hidden", 'name' => "when", 'value' => $notify['when'] ]),
+							UI::h('button', [
+								'class' => "btn btn-link btn-xs",
+								'onclick' => "return confirm('Czy usunąć powiadomienie?')",
+								'type' => "submit"
+							], '<i class="glyphicon glyphicon-remove" style="color:red;opacity:0.4;"></i>'),
+						]),
+					];
+				}, $userNotifyList)
+			]);
+		}
+	?>
 
 	<?php if (!empty($whatLabelsForOnceADay)) : ?>
 	<hr>
@@ -797,7 +794,7 @@ function refreshPreview() {
 				$sqlValues[] = "( {$sqlWho}, {$sqlWhat}, {$sqlWhen}, NOW() )";
 			}
 			$sqlValues = implode(", ", $sqlValues);
-			$pdo->exec("
+			$pdo->execSql("
 				insert ignore into `CRM_NOTIFY` (
 					`who`,
 					`what`,
@@ -824,25 +821,22 @@ function refreshPreview() {
 			$bindValues['what'] = array($what, PDO::PARAM_STR);
 			$bindValues['when'] = array($when, PDO::PARAM_STR);
 			$pdo->bindValues($sth, $bindValues);
-//		try {
+			// try {
 				$sth->execute();
-//		} catch (PDOException $e) {
-//			throw new Exception("Błąd bazy danych: " . json_encode($e->errorInfo));
-//		} catch (Exception $e) {
-//			throw $e;
-//		}
+			// } catch (PDOException $e) {
+			// 	throw new Exception("Błąd bazy danych: " . json_encode($e->errorInfo));
+			// } catch (Exception $e) {
+			// 	throw $e;
+			// }
 		}
 	}
 
 	public function getUserNotifyList($usrLogin) {
-		$sth = DB::getPDO()->prepare("
+		return DB::getPDO()->fetchAll("
 			select n.*
 			from `CRM_NOTIFY` n
 			where n.`who` = '{$usrLogin}'
 		");
-		$sth->execute();
-		$notifyTypeList = $sth->fetchAll();
-		return $notifyTypeList;
 	}
 
 	public function getTodoList($limit = 10, $whenTypes = array()) {
@@ -993,11 +987,11 @@ function refreshPreview() {
 			$expectedStruct['_created'] = array('type'=>'datetime', 'is_nullable'=>false);// `_created` datetime
 			$expectedStruct['uniq_key_1'] = array('type'=>'UNIQUE KEY', 'key_fields'=>array('who','when','what'));// UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
 			$expectedStruct['key_who'] = array('type'=>'KEY', 'key_fields'=>array('who'));// KEY `key_who` (`who`)
-//			$expectedStruct['t1'] = array('type'=>'varchar', 'max_length'=>300, 'default_value'=>null);
-//			$expectedStruct['t2'] = array('type'=>'int');
-//			$expectedStruct['t3'] = array('type'=>'int', 'num_precision'=>11, 'default_value'=>null);
-//			$expectedStruct['t_dec_11_x'] = array('type'=>'decimal', 'num_precision'=>11);
-//			$expectedStruct['t_dec_11_2'] = array('type'=>'decimal', 'num_precision'=>11, 'num_scale'=>2);
+			// $expectedStruct['t1'] = array('type'=>'varchar', 'max_length'=>300, 'default_value'=>null);
+			// $expectedStruct['t2'] = array('type'=>'int');
+			// $expectedStruct['t3'] = array('type'=>'int', 'num_precision'=>11, 'default_value'=>null);
+			// $expectedStruct['t_dec_11_x'] = array('type'=>'decimal', 'num_precision'=>11);
+			// $expectedStruct['t_dec_11_2'] = array('type'=>'decimal', 'num_precision'=>11, 'num_scale'=>2);
 			$expectedStruct['t_int'] = array('type'=>'int');
 			$expectedStruct['t_tinyint'] = array('type'=>'tinyint');
 			$expectedStruct['t_smallint'] = array('type'=>'smallint');
@@ -1092,7 +1086,7 @@ function refreshPreview() {
 	public function reinstall($force = false) {
 		$sqlList = array();
 		$pdo = DB::getPDO();
-		$sqlCreate = <<<EOF_SQL_CREATE
+		$sqlCreate = "
 			CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
 				`who` varchar(20) NOT NULL
 				, `when` varchar(255) NOT NULL
@@ -1102,7 +1096,7 @@ function refreshPreview() {
 				, UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
 				, KEY `key_who` (`who`)
 			) ENGINE=MyISAM DEFAULT CHARSET=latin2
-EOF_SQL_CREATE;
+		";
 		/*
 			`CRM_NOTIFY`:
 				- who - user login

+ 1 - 6
SE/se-lib/Route/Status.php

@@ -190,7 +190,7 @@ class Route_Status extends RouteBase {
     ");
     UI::hButtonAjaxOnResponse("activateUserDebug", /* payload, n */ "
       p5UI__notifyAjaxCallback(payload)
-      console.log('activateUserDebug :: payload', payload)
+      // console.log('activateUserDebug :: payload', payload)
       if ('success' !== payload.type) return false
       if (payload.body && 'active' in payload.body) {
         if (payload.body.active) {
@@ -198,11 +198,6 @@ class Route_Status extends RouteBase {
         } else {
           n.parentNode.classList.remove('active')
         }
-        // if (!n.parentNode.classList.contains('active')) {
-        //   n.parentNode.classList.add('active')
-        // } else {
-        //   n.parentNode.classList.remove('active')
-        // }
       }
     ");
   }

+ 10 - 6
SE/se-lib/User.php

@@ -50,18 +50,22 @@ class User {
 	public static function _fetchMoreUserData() {
 		$login = self::getLogin();
 		if (empty($login)) return false;
-		$sql = "select `ID`, `INICJALY_HANDLOWCA`, `EMPLOYEE_TYPE`
-				, `DEFAULT_ACL_GROUP`
-			from `ADMIN_USERS`
+		$sql = "
+			select u.ID as ADM_ID
+				, u.INICJALY_HANDLOWCA as ADM_INICJALY_HANDLOWCA
+				, u.EMPLOYEE_TYPE
+				, u.DEFAULT_ACL_GROUP
+			from `ADMIN_USERS` u
 			where `ADM_ACCOUNT`='{$login}'
-			limit 1
 		";
 		if ($userInfo = DB::getPDO()->fetchFirst($sql)) {
-			$_SESSION['ADM_ID'] = $userInfo['ID'];
-			$_SESSION['ADM_INICJALY_HANDLOWCA'] = $userInfo['INICJALY_HANDLOWCA'];
+			$_SESSION['ADM_ID'] = $userInfo['ADM_ID'];
+			$_SESSION['ADM_INICJALY_HANDLOWCA'] = $userInfo['ADM_INICJALY_HANDLOWCA'];
 			$_SESSION['EMPLOYEE_TYPE'] = $userInfo['EMPLOYEE_TYPE'];
 			$_SESSION['DEFAULT_ACL_GROUP'] = $userInfo['DEFAULT_ACL_GROUP'];
+			return $userInfo;
 		}
+		return [];
 	}
 
 	public static function logged() {

+ 23 - 1
SE/se-lib/V.php

@@ -568,5 +568,27 @@ EOF';
 		arrayToXML_rec($array, $dom, $root);
 		return $dom->saveXML();
 	}
-		
+
+	// date("Y-m-d H:i:s") . substr((string)microtime(), 1, 6),
+	// a: '2017-07-25 13:06:15.59124',
+	// b: '2017-07-25 13:06:15.56161',
+	// result:              '0.02963'
+	public static function milisecondsStringDiff($a, $b) {
+		if (25 != strlen($a)) return "Wrong length in 1st arg";
+		if (25 != strlen($b)) return "Wrong length in 2nd arg";
+		$aTime = array_sum([
+			intVal(substr($a, 11, 2)) * 100000 * 60 * 60, // hour
+			intVal(substr($a, 14, 2)) * 100000 * 60, // min
+			intVal(substr($a, 17, 2)) * 100000, // sec
+			intVal(substr($a, 20, 5)), // mili sec (5 digits)
+		]);
+		$bTime = array_sum([
+			intVal(substr($b, 11, 2)) * 100000 * 60 * 60, // hour
+			intVal(substr($b, 14, 2)) * 100000 * 60, // min
+			intVal(substr($b, 17, 2)) * 100000, // sec
+			intVal(substr($b, 20, 5)), // mili sec (5 digits)
+		]);
+		return sprintf("%0.5f", abs($aTime - $bTime) / 100000);
+	}
+
 }