TableMsgs.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. <?php
  2. Lib::loadClass('Router');
  3. Lib::loadClass('RouteBase');
  4. Lib::loadClass('TypespecialVariable');
  5. class Route_TableMsgs extends RouteBase {
  6. var $_listLimit = 20;
  7. public function handleAuth() {
  8. if (!User::logged()) {
  9. User::authByRequest();
  10. }
  11. }
  12. public function defaultAction() {
  13. SE_Layout::gora();
  14. SE_Layout::menu();
  15. $this->menu();
  16. SE_Layout::dol();
  17. }
  18. public function menu() {
  19. $usrLogin = User::getLogin();
  20. ?>
  21. <ul>
  22. <li>TODO: ...</li>
  23. </ul>
  24. <?php
  25. }
  26. public function tableRowAction() {
  27. $idTable = V::get('idTable', 0, $_REQUEST, 'int');
  28. $idRow = V::get('idRow', 0, $_REQUEST, 'int');
  29. if ($idTable <= 0) throw new HttpException("Błęny numer tabeli", 400);
  30. if ($idRow <= 0) throw new HttpException("Błęny numer tabeli", 400);
  31. SE_Layout::gora();
  32. SE_Layout::menu();
  33. try {
  34. $this->tableRowMsgs($idTable, $idRow);
  35. } catch (Exception $e) {
  36. SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
  37. }
  38. SE_Layout::dol();
  39. }
  40. public function tableRowMsgs($idTable, $idRow) {
  41. $tblAcl = User::getAcl()->getTableAcl($idTable);
  42. $tableName = $tblAcl->getName();
  43. $record = $tblAcl->getItem($idRow);
  44. $args = array();
  45. $args['to_type'] = V::get('to_type', '', $_POST);
  46. $args['to'] = V::get("to-{$args['to_type']}", '', $_POST);
  47. $args['msg'] = V::get('msg', '', $_POST);
  48. $arrorsList = array();
  49. $createdId = 0;
  50. if (!empty($_POST)) {
  51. try {
  52. $this->_validate($args);
  53. $createdId = $this->_create($args, $tableName, $idRow);
  54. if ($createdId > 0) {
  55. $args['to'] = '';
  56. $args['msg'] = '';
  57. }
  58. } catch(Exception $e) {
  59. $arrorsList[] = $e->getMessage();
  60. }
  61. }
  62. $msgsList = $this->_getMsgs('inbox', $tableName, $idRow);
  63. $totalReadMsgs = 0;
  64. $totalUnreadMsgs = 0;
  65. foreach ($msgsList as $ind => $msg) {
  66. if ($msg['_read']) {
  67. $totalReadMsgs++;
  68. } else {
  69. $totalUnreadMsgs++;
  70. }
  71. }
  72. $sentMsgsList = $this->_getMsgs('sent', $tableName, $idRow);
  73. $removedMsgsList = $this->_getMsgs('removed', $tableName, $idRow);
  74. ?>
  75. <style type="text/css">
  76. .tblMsgsListItem { cursor:pointer; }
  77. </style>
  78. <div class="container">
  79. <h3><i class="glyphicon glyphicon-envelope"></i> Wiadomości powiązane z rekordem nr <code><?php echo $idRow; ?></code>
  80. <br><small>z tabeli <a href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $idTable; ?>"><?php echo $tblAcl->getLabel(); ?></a></small>
  81. </h3>
  82. <?php if ($createdId > 0) : ?>
  83. <?php echo SE_Layout::alert('info', "Wysłano wiadomość nr '{$createdId}'"); ?>
  84. <?php endif; ?>
  85. <div>
  86. <ul class="nav nav-tabs" role="tablist">
  87. <li>
  88. <a href="#tbl-msgs-compose"><i class="glyphicon glyphicon-plus"></i> Nowa wiadomość</a>
  89. </li>
  90. <li role="presentation" class="active"><a href="#odebrane" aria-controls="odebrane" role="tab" data-toggle="tab">Odebrane <em>(<?php echo $totalUnreadMsgs; ?>)</em></a></li>
  91. <li role="presentation"><a href="#wyslane" aria-controls="wyslane" role="tab" data-toggle="tab">Wysłane</em></a></li>
  92. <li role="presentation"><a href="#kosz" aria-controls="kosz" role="tab" data-toggle="tab">Kosz</em></a></li>
  93. </ul>
  94. <div class="tab-content" style="margin-bottom:15px">
  95. <div role="tabpanel" class="tab-pane active" id="odebrane" style="border-style:none solid solid solid; border-width:1px; border-color:#ddd;">
  96. <?php $this->_printTableMsgsList('inbox', $msgsList, $idTable, $idRow); ?>
  97. </div>
  98. <div role="tabpanel" class="tab-pane" id="wyslane" style="border-style:none solid solid solid; border-width:1px; border-color:#ddd;">
  99. <?php $this->_printTableMsgsList('sent', $sentMsgsList, $idTable, $idRow); ?>
  100. </div>
  101. <div role="tabpanel" class="tab-pane" id="kosz" style="border-style:none solid solid solid; border-width:1px; border-color:#ddd;">
  102. <?php $this->_printTableMsgsList('removed', $removedMsgsList, $idTable, $idRow); ?>
  103. </div>
  104. </div>
  105. </div>
  106. <div class="panel panel-default" id="tbl-msgs-compose">
  107. <div class="panel-heading">Wyślij nową wiadomość</div>
  108. <div class="panel-body">
  109. <?php if (!empty($arrorsList)) : ?>
  110. <?php foreach ($arrorsList as $errMsg) : ?>
  111. <div class="alert alert-danger"><?php echo $errMsg; ?></div>
  112. <?php endforeach; ?>
  113. <?php endif; ?>
  114. <?php $this->_printMsgForm($args); ?>
  115. </div>
  116. </div>
  117. </div>
  118. <script>
  119. function tblMsgsLoadMoreRows(n) {
  120. var nNode = jQuery(n),
  121. lastMsgId = nNode.data('last_msg_id'),
  122. listType = nNode.data('list_type')
  123. ;
  124. nNode.blur();
  125. function tblMsgsSetNoMoreRows(btnLoadMoreNode) {
  126. btnLoadMoreNode.closest('td').css({color:'silver'}).html('Brak starszych wiadomości');
  127. }
  128. if (lastMsgId <= 0) {
  129. tblMsgsSetNoMoreRows(nNode);
  130. }
  131. function tblMsgsAddMsgToList(msg, btnLoadMoreNode, listType) {
  132. var tbodyNode = btnLoadMoreNode.closest('tfoot').prev('tbody'),
  133. trNode = jQuery('<tr></tr>'),
  134. tdIdNode = jQuery('<td></td>'),
  135. tdMsgNode = jQuery('<td></td>'),
  136. tdDateNode = jQuery('<td style="white-space:nowrap;"></td>'),
  137. actionTask = (listType == 'inbox')? 'read' : 'view',
  138. msgLink = ''
  139. ;
  140. trNode.addClass('tblMsgsListItem');
  141. if (msg['_read']) trNode.addClass('active');
  142. if ('read' === actionTask || 'view' === actionTask) {
  143. msgLink = '<?php echo Request::getPathUri() . 'index.php?_route=TableMsgs'; ?>';
  144. msgLink += '&idTable=<?php echo $idTable; ?>&idRow=<?php echo $idRow; ?>';
  145. msgLink += '&id=' + msg['_raw']['ID'];
  146. msgLink += '&_task=' + actionTask;
  147. trNode.attr('onclick', "window.location.href='" + msgLink + "'");
  148. }
  149. tdIdNode.append(msg['_raw']['ID']);
  150. tdIdNode.appendTo(trNode);
  151. tdMsgNode.append('<div style="overflow:hidden; white-space:nowrap; text-overflow:ellipsis;">' + msg['message'] + '</div>');
  152. msgMetaInfo = 'od ' + msg['_raw']['A_RECORD_CREATE_AUTHOR'] + ' do ';
  153. if ('everyone' == msg['_raw']['userTargetType']) {
  154. msgMetaInfo += 'wszystkich';
  155. } else if ('user' == msg['_raw']['userTargetType']) {
  156. msgMetaInfo += msg['_raw']['userTargetName'];
  157. } else if ('group' == msg['_raw']['userTargetType']) {
  158. msgMetaInfo += 'grupy ' + msg['_raw']['userTargetName'];
  159. }
  160. tdMsgNode.append('<div class="text-muted" style="font-style:italic;">' + msgMetaInfo + '</div>');
  161. tdMsgNode.appendTo(trNode);
  162. tdDateNode.append(msg['_raw']['A_RECORD_CREATE_DATE']);
  163. if (msg['_readDate']) {
  164. tdDateNode.append('<div class="text-muted" style="font-style:italic" title="Przeczytano ' + msg['_readDate'] + '">' + msg['_readDate'] + '</div>');
  165. } else {
  166. tdDateNode.append('<div class="text-muted" style="font-style:italic" title="Wiadomość nie została jeszcze odczytana">nieodczytana</div>');
  167. }
  168. tdDateNode.appendTo(trNode);
  169. trNode.hide();
  170. trNode.appendTo(tbodyNode);
  171. trNode.show('slow');
  172. };
  173. jQuery.ajax({
  174. data: {},
  175. dataType: 'json',
  176. type: "POST",
  177. url: 'index.php?_route=TableMsgs&_task=loadMoreRows&listType=' + listType + '&lastMsgId=' + lastMsgId + '&tableName=<?php echo $tableName; ?>' + '&idRow=<?php echo $idRow; ?>'
  178. })
  179. .done(function(data, textStatus, jqXHR) {
  180. var listLimit = <?php echo $this->_listLimit; ?>,
  181. i = 0,
  182. lastMsgId = 0,
  183. hasMore = false
  184. ;
  185. if (!data || !data.msgs || !data.keysOrder) {
  186. jQuery.notify('Wystąpiły błędy podczas pobierania listy wiadomości', 'error');
  187. return false;
  188. }
  189. data.keysOrder.forEach(function(key) {
  190. if (i < listLimit) {
  191. lastMsgId = key;
  192. tblMsgsAddMsgToList(data.msgs[key], nNode, listType);
  193. } else {
  194. hasMore = true;
  195. }
  196. i++;
  197. });
  198. if (!hasMore) {
  199. tblMsgsSetNoMoreRows(nNode);
  200. }
  201. nNode.data('last_msg_id', lastMsgId);
  202. })
  203. .fail(function(jqXHR) {
  204. if (jqXHR.responseJSON) {
  205. jQuery.notify('Nie udało się pobrać listy wiadomości', 'error');
  206. }
  207. else {
  208. var txt = jqXHR.responseText || 'Nie udało się pobrać listy wiadomości';
  209. if (jqXHR.status == 404) {
  210. jQuery.notify(jqXHR.responseText, 'error');
  211. } else {
  212. jQuery.notify(jqXHR.responseText, 'warn');
  213. }
  214. }
  215. });
  216. }
  217. </script>
  218. <?php
  219. //DBG::_(true, true, "_POST", $_POST, __CLASS__, __FUNCTION__, __LINE__);
  220. //DBG::_(true, true, "tblAcl", $tblAcl, __CLASS__, __FUNCTION__, __LINE__);
  221. //DBG::_(true, true, "record", $record, __CLASS__, __FUNCTION__, __LINE__);
  222. //DBG::_(true, true, "msgsList", $msgsList, __CLASS__, __FUNCTION__, __LINE__);
  223. //throw new Exception("TODO: ...");
  224. }
  225. public function loadMoreRowsAction() {
  226. $tableName = V::get('tableName', '', $_GET, 'word');
  227. $idRow = V::get('idRow', 0, $_GET, 'int');
  228. $lastMsgId = V::get('lastMsgId', 0, $_GET, 'int');
  229. $listType = V::get('listType', '', $_GET, 'word');
  230. if ($idRow <= 0) throw new HttpException("Wrong param id row", 404);
  231. if (!$tableName) throw new HttpException("Wrong param table name", 404);
  232. if ($lastMsgId <= 0) throw new HttpException("Wrong param lastMsgId", 404);
  233. if (!in_array($listType, array('inbox','sent','removed'))) throw new HttpException("Wrong param listType", 404);
  234. $resultData = new stdClass();
  235. $resultData->msgs = $this->_getMsgs($listType, $tableName, $idRow, $lastMsgId);
  236. $resultData->keysOrder = array_keys($resultData->msgs);
  237. echo json_encode($resultData);
  238. }
  239. public function _printTableMsgsList($listType, $msgsList, $idTable, $idRow) {
  240. $msgsTotal = count($msgsList);
  241. $listLimit = $this->_listLimit;
  242. $lastMsgId = 0;
  243. $actionTask = ($listType == 'inbox')? 'read' : 'view';
  244. ?>
  245. <table class="tblMsgsList table table-hovered" style="margin-bottom:0; table-layout:fixed;">
  246. <thead>
  247. <tr>
  248. <th style="width:60px">#</th>
  249. <th>wiadomość</th>
  250. <th style="width:130px">data</th>
  251. </tr>
  252. </thead>
  253. <tbody>
  254. <?php if ($msgsTotal <= 0) : ?>
  255. <tr>
  256. <td colspan="3"><em class="text-muted" style="padding-left:60px;">Brak wiadomości</em></td>
  257. </tr>
  258. <?php else : ?>
  259. <?php $i = 0; foreach ($msgsList as $idMsg => $msg) : $i++; if ($i > $listLimit) break; $lastMsgId = $idMsg; ?>
  260. <?php
  261. $onClick = '';
  262. $msgLink = Request::getPathUri() . 'index.php?_route=TableMsgs&id=' . $msg['_raw']->ID;
  263. $msgLink .= "&idTable={$idTable}&idRow={$idRow}";
  264. if ('read' == $actionTask || 'view' == $actionTask) {
  265. $msgLink .= '&_task=' . $actionTask;
  266. } else {
  267. $msgLink = null;
  268. }
  269. if ($msgLink) {
  270. $jsOnClick = "window.location.href='{$msgLink}'";
  271. $onClick = 'onclick="' . $jsOnClick . '"';
  272. }
  273. ?>
  274. <tr <?php echo $onClick; ?>
  275. class="tblMsgsListItem <?php echo ($msg['_read'])? 'active' : ''; ?>">
  276. <td><?php echo $msg['_raw']->ID; ?></td>
  277. <td>
  278. <div style="overflow:hidden; white-space:nowrap; text-overflow:ellipsis;"><?php echo htmlspecialchars($msg['message']); ?></div>
  279. <div class="text-muted" style="font-style:italic;">
  280. od <?php echo $msg['_raw']->A_RECORD_CREATE_AUTHOR; ?> do <?php
  281. if ('everyone' == $msg['_raw']->userTargetType) {
  282. echo "wszystkich";
  283. } else if ('user' == $msg['_raw']->userTargetType) {
  284. echo "{$msg['_raw']->userTargetName}";
  285. } else if ('group' == $msg['_raw']->userTargetType) {
  286. echo "grupy {$msg['_raw']->userTargetName}";
  287. }
  288. ?>
  289. </div>
  290. </td>
  291. <td style="white-space:nowrap;">
  292. <?php echo $msg['_raw']->A_RECORD_CREATE_DATE; ?>
  293. <?php if ($msg['_readDate']) : ?>
  294. <div class="text-muted" style="font-style:italic" title="Przeczytano <?php echo $msg['_readDate']; ?>"><?php echo $msg['_readDate']; ?></div>
  295. <?php else : ?>
  296. <div class="text-muted" style="font-style:italic" title="Wiadomość nie została jeszcze odczytana">nieodczytana</div>
  297. <?php endif; ?>
  298. </td>
  299. </tr>
  300. <?php endforeach; ?>
  301. <?php endif; ?>
  302. </tbody>
  303. <tfoot>
  304. <?php if ($msgsTotal > $listLimit) : ?>
  305. <tr class="active">
  306. <td colspan="3" style="text-align:center">
  307. <button class="btn btn-link"
  308. data-last_msg_id="<?php echo $lastMsgId; ?>"
  309. data-list_type="<?php echo $listType; ?>"
  310. onclick="return tblMsgsLoadMoreRows(this);">pobierz starsze wiadomości ...</button>
  311. </td>
  312. </tr>
  313. <?php endif; ?>
  314. </tfoot>
  315. </table>
  316. <?php
  317. }
  318. public function _getMsgs($filterType, $tableName, $idRow, $lastMsgId = null) {
  319. $lastMsgId = (int)$lastMsgId;
  320. $msgsRoute = Router::getRoute('Msgs');
  321. //$msgsList = $msgsRoute->getMessagesForTableRecord($tableName, $idRow);
  322. $msgsList = array();
  323. if (empty($tableName)) throw new Exception("No table name!");
  324. $sqlWhereAddFilter = "";
  325. $usrLogin = User::getLogin();
  326. $userGroupIds = User::getGroupsIds();
  327. $sqlFilerMsgsForUser = "
  328. m.`userTargetType` in('everyone')
  329. or (m.`userTargetType`='user' and m.`userTargetName`='{$usrLogin}')
  330. or (m.`userTargetType`='group' and m.`userTargetName` in(" . implode(",", $userGroupIds) . "))
  331. ";
  332. switch ($filterType) {
  333. case 'inbox':
  334. $sqlWhereAddFilter = "
  335. and ({$sqlFilerMsgsForUser})
  336. and m.`A_STATUS` not in('DELETED')
  337. ";
  338. break;
  339. case 'sent':
  340. $sqlWhereAddFilter = "
  341. and m.`A_RECORD_CREATE_AUTHOR`='{$usrLogin}'
  342. and m.`A_STATUS` not in('DELETED')
  343. ";
  344. break;
  345. case 'removed':
  346. $sqlWhereAddFilter = "
  347. and (m.`A_RECORD_CREATE_AUTHOR`='{$usrLogin}'
  348. or ({$sqlFilerMsgsForUser})
  349. )
  350. and m.`A_STATUS` in('DELETED')
  351. ";
  352. break;
  353. default: throw new Exception("Unknown filter type");
  354. }
  355. $db = DB::getDB();
  356. $tableName = $db->_($tableName);
  357. if ($lastMsgId > 0) {
  358. $sqlWhereAddFilter .= "\n and m.`ID`<{$lastMsgId}";
  359. }
  360. $sqlLimit = $this->_listLimit + 1;
  361. $sql = "select m.*
  362. from `CRM_UI_MSGS` m
  363. where m.`uiTargetType`='default_db_table_record'
  364. and m.`uiTargetName`='{$tableName}.{$idRow}'
  365. {$sqlWhereAddFilter}
  366. order by m.`ID` DESC
  367. limit {$sqlLimit}
  368. ";
  369. //DBG::_('DBG_MSGS', '>1', "sql", $sql, __CLASS__, __FUNCTION__, __LINE__);
  370. $db = DB::getDB();
  371. $res = $db->query($sql);
  372. while ($r = $db->fetch($res)) {
  373. $msg['message'] = $r->msg;
  374. $msg['type'] = $r->msgType;
  375. $msg['_raw'] = $r;
  376. $msg['_read'] = ('WAITING' != $r->A_STATUS);
  377. $msg['_readDate'] = $r->actionExecutedTime;
  378. $msgsList[$r->ID] = $msg;
  379. }
  380. return $msgsList;
  381. }
  382. public function _validate($args) {
  383. $toType = V::get('to_type', '', $args);
  384. $to = V::get('to', '', $args);
  385. $msg = V::get('msg', '', $args);
  386. if (!in_array($toType, array('everyone', 'user', 'group'))) {
  387. throw new Exception("Niedozwolony typ odbiorcy");
  388. }
  389. if (empty($to) && 'everyone' != $toType) {
  390. throw new Exception("Proszę podać odbiorcę wiadomości");
  391. }
  392. if (empty($msg)) {
  393. throw new Exception("Proszę podać treść wiadomości");
  394. }
  395. }
  396. public function _create($args, $tableName, $idRow) {
  397. $toType = V::get('to_type', '', $args);
  398. $to = V::get('to', '', $args);
  399. $msg = V::get('msg', '', $args);
  400. $usrLogin = User::getLogin();
  401. $db = DB::getDB();
  402. if (!$db) throw new Exception("Brak dazy danych!");
  403. if ($db->has_errors()) throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  404. $item = array();
  405. $item['`uiTargetType`'] = "'default_db_table_record'";
  406. $item['`uiTargetName`'] = "'{$tableName}.{$idRow}'";
  407. $item['`userTargetType`'] = "'{$toType}'";
  408. $item['`userTargetName`'] = "'{$to}'";
  409. $item['`msg`'] = "'" . $db->_($msg) . "'";
  410. $item['`A_RECORD_CREATE_DATE`'] = "NOW()";
  411. $item['`A_RECORD_CREATE_AUTHOR`'] = "'{$usrLogin}'";
  412. $item['`A_STATUS`'] = "'WAITING'";
  413. $item['`app_className`'] = "'TableMsgs'";
  414. $sql = "insert into `CRM_UI_MSGS` (" . implode(",", array_keys($item)) . ")
  415. values (" . implode(",", array_values($item)) . ")
  416. ";
  417. $res = $db->query($sql);
  418. if (!$res || $db->has_errors()) throw new Exception("Wystąpiły błędy podczas próby zapisu wiadomości: " . implode("\n<br>", $db->get_errors()));
  419. $createdId = $db->insert_id();
  420. if ($createdId <= 0) throw new Exception("Nie udało się zapisać wiadomości.");
  421. return $createdId;
  422. }
  423. public function _printMsgForm($args) {
  424. $toType = V::get('to_type', '', $args);
  425. $to = V::get('to', '', $args);
  426. $msg = V::get('msg', '', $args);
  427. $listTo = array();
  428. $listTo['everyone'] = 'Wszyscy';
  429. $listTo['user'] = 'Użytkownik';
  430. $listTo['group'] = 'Grupa';
  431. $toType = (array_key_exists($toType, $listTo))? $toType : 'everyone';
  432. $typeSpecialGroupId = TypespecialVariable::getInstance(-1, '__ZASOB');
  433. $typeSpecialUserLogin = TypespecialVariable::getInstance(-1, '__USER_LOGIN');
  434. $selectedLogin = ('user' == $toType)? $to : '';
  435. $selectedGroupId = ('group' == $toType)? $to : '';
  436. ?>
  437. <form class="form-horizontal" action="" method="post">
  438. <div class="form-group">
  439. <label class="col-sm-2 control-label" for="to">Do:</label>
  440. <div class="col-sm-3">
  441. <select name="to_type" class="form-control" onChange="return selectTblMsgsToType(this);">
  442. <?php foreach ($listTo as $type => $typeLabel) : ?>
  443. <option <?php echo ($type == $toType)? 'selected' : ''; ?>
  444. value="<?php echo $type; ?>"><?php echo $typeLabel; ?></option>
  445. <?php endforeach; ?>
  446. </select>
  447. </div>
  448. <div class="col-sm-7">
  449. <div id="tblMsgsTo-everyone" style="<?php echo ('everyone' == $toType)? '' : 'display:none'; ?>">
  450. <input name="to-everyone" type="text" class="form-control" disabled>
  451. </div>
  452. <div id="tblMsgsTo-group" style="<?php echo ('group' == $toType)? '' : 'display:none'; ?>">
  453. <?php if ($typeSpecialGroupId) : ?>
  454. <?php
  455. $fldName = 'to-group';
  456. $fldParams = array();
  457. $fldParams['allowCreate'] = false;
  458. $fldParams['ajaxDataUrlBase'] = "index.php?_route=TableMsgs&_task=typeSpecialGroupId";
  459. $fldParams['placeholder'] = 'Grupa...';
  460. //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
  461. echo $typeSpecialUserLogin->showFormItem($tblID = -1, $fldName, $selectedGroupId, $fldParams);
  462. ?>
  463. <?php else : ?>
  464. <input name="to-group" type="text" class="form-control" placeholder="Grupa">
  465. <?php endif; ?>
  466. </div>
  467. <div id="tblMsgsTo-user" style="<?php echo ('user' == $toType)? '' : 'display:none'; ?>">
  468. <?php if ($typeSpecialUserLogin) : ?>
  469. <?php
  470. $fldName = 'to-user';
  471. $fldParams = array();
  472. $fldParams['allowCreate'] = false;
  473. $fldParams['ajaxDataUrlBase'] = "index.php?_route=TableMsgs&_task=typeSpecialUserLogin";
  474. $fldParams['placeholder'] = 'Użytkownik...';
  475. //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
  476. echo $typeSpecialUserLogin->showFormItem($tblID = -1, $fldName, $selectedLogin, $fldParams);
  477. ?>
  478. <?php else : ?>
  479. <input name="to-user" type="text" class="form-control" placeholder="Użytkownik">
  480. <?php endif; ?>
  481. </div>
  482. </div>
  483. </div>
  484. <div class="form-group">
  485. <label for="to" class="col-sm-2 control-label">Wiadomość:</label>
  486. <div class="col-sm-10">
  487. <textarea name="msg" class="form-control"><?php echo htmlspecialchars($msg); ?></textarea>
  488. </div>
  489. </div>
  490. <div class="form-group">
  491. <div class="col-sm-10 col-sm-offset-2">
  492. <input class="btn btn-primary" type="submit" value="Wyślij">
  493. </div>
  494. </div>
  495. </form>
  496. <script>
  497. function selectTblMsgsToType(n) {
  498. var toTypes = <?php echo json_encode(array_keys($listTo)); ?>,
  499. selectedType = n.value
  500. ;
  501. if (-1 !== toTypes.indexOf(n.value)) {
  502. toTypes.forEach(function(type) {
  503. if (type == selectedType) {
  504. document.getElementById('tblMsgsTo-' + type).style.display = 'block';
  505. } else {
  506. document.getElementById('tblMsgsTo-' + type).style.display = 'none';
  507. }
  508. });
  509. }
  510. }
  511. </script>
  512. <?php
  513. }
  514. public function typeSpecialUserLoginAction() {
  515. header("Content-type: application/json");
  516. $typeSpecialUserId = TypespecialVariable::getInstance(-1, '__USER_LOGIN');
  517. if (!$typeSpecialUserId) {
  518. $jsonData = new stdClass();
  519. $jsonData->message = "TypeSpecial '__USER_LOGIN' not exists";
  520. echo json_encode($jsonData);
  521. exit;
  522. }
  523. $query = V::get('q', '', $_REQUEST);
  524. $rawRows = null;
  525. $jsonData = array();
  526. $queryParams = array();
  527. $rows = $typeSpecialUserId->getValuesWithExports($query, $queryParams);
  528. foreach ($rows as $kID => $vItem) {
  529. $itemJson = new stdClass();
  530. $itemJson->id = $vItem->id;
  531. $itemJson->name = $vItem->param_out;
  532. if (!empty($vItem->exports)) {
  533. $itemJson->exports = $vItem->exports;
  534. }
  535. $jsonData[] = $itemJson;
  536. }
  537. echo json_encode($jsonData);
  538. }
  539. public function typeSpecialGroupIdAction() {
  540. header("Content-type: application/json");
  541. Lib::loadClass('TypespecialVariable');
  542. $typeSpecialZasob = TypespecialVariable::getInstance(-1, '__ZASOB');
  543. if (!$typeSpecialZasob) {
  544. $jsonData = new stdClass();
  545. $jsonData->message = "TypeSpecial '__ZASOB' not exists";
  546. echo json_encode($jsonData);
  547. exit;
  548. }
  549. $query = V::get('q', '', $_REQUEST);
  550. $rawRows = null;
  551. $jsonData = array();
  552. $queryParams = array();
  553. $queryParams['zasob_type_in'] = array('STANOWISKO', 'PODMIOT', 'DZIAL');
  554. $rows = $typeSpecialZasob->getValuesWithExports($query, $queryParams);
  555. DBG::_('DBG_TS', '>1', "rows({$query})", $rows, __CLASS__, __FUNCTION__, __LINE__);
  556. foreach ($rows as $kID => $vItem) {
  557. $itemJson = new stdClass();
  558. $itemJson->id = $vItem->id;
  559. $itemJson->name = $vItem->param_out;
  560. if (!empty($vItem->exports)) {
  561. $itemJson->exports = $vItem->exports;
  562. }
  563. $jsonData[] = $itemJson;
  564. }
  565. echo json_encode($jsonData);
  566. }
  567. public function readAction() {
  568. $idMsg = V::get('id', 0, $_GET, 'int');
  569. $idTable = V::get('idTable', 0, $_REQUEST, 'int');
  570. $idRow = V::get('idRow', 0, $_REQUEST, 'int');
  571. if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
  572. if ($idTable <= 0) throw new HttpException("Błęny numer tabeli", 400);
  573. if ($idRow <= 0) throw new HttpException("Błęny numer tabeli", 400);
  574. SE_Layout::gora();
  575. SE_Layout::menu();
  576. try {
  577. $msg = $this->_getMsg($idMsg, $idTable, $idRow);
  578. $this->_markAsRead($msg);
  579. $this->tableRowMsg($msg);
  580. } catch (Exception $e) {
  581. SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
  582. }
  583. SE_Layout::dol();
  584. }
  585. public function viewAction() {
  586. $idMsg = V::get('id', 0, $_GET, 'int');
  587. $idTable = V::get('idTable', 0, $_REQUEST, 'int');
  588. $idRow = V::get('idRow', 0, $_REQUEST, 'int');
  589. if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
  590. if ($idTable <= 0) throw new HttpException("Błęny numer tabeli", 400);
  591. if ($idRow <= 0) throw new HttpException("Błęny numer tabeli", 400);
  592. SE_Layout::gora();
  593. SE_Layout::menu();
  594. try {
  595. $msg = $this->_getMsg($idMsg, $idTable, $idRow);
  596. $this->tableRowMsg($msg);
  597. } catch (Exception $e) {
  598. SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
  599. }
  600. SE_Layout::dol();
  601. }
  602. public function _getMsg($idMsg, $idTable, $idRow) {
  603. $msgsRoute = Router::getRoute('Msgs');
  604. $msg['_raw'] = $msgsRoute->getMessage($idMsg);
  605. if (!$msg['_raw']) throw new HttpException("Wiadomość nie istnieje!", 404);
  606. $msg['idTable'] = $idTable;
  607. $msg['idRow'] = $idRow;
  608. $msg['message'] = $msg['_raw']->msg;
  609. $msg['type'] = $msg['_raw']->msgType;
  610. $msg['_read'] = ('WAITING' != $msg['_raw']->A_STATUS);
  611. // $msg['_raw']->uiTargetType => default_db_table_record
  612. // $msg['_raw']->uiTargetName => TEST_PERMS.31
  613. if ('default_db_table_record' !== $msg['_raw']->uiTargetType) {
  614. throw new Exception("Parse message target type error!");
  615. }
  616. $parts = explode('.', $msg['_raw']->uiTargetName);
  617. if (2 !== count($parts)) throw new Exception("Parse message target type error!");
  618. $msg['tblName'] = $parts[0];
  619. if (!is_numeric($msg['idRow'])) throw new Exception("Parse message target type - id row type error!");
  620. if ($msg['idRow'] != $parts[1]) throw new Exception("Parse message target type - id row value error!");
  621. return $msg;
  622. }
  623. public function _markAsRead($msg) {
  624. if ($msg['_read']) return;
  625. $usrLogin = User::getLogin();
  626. $db = DB::getDB();
  627. if (!$db) throw new Exception("Brak dazy danych!");
  628. if ($db->has_errors()) throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  629. $sql = "update `CRM_UI_MSGS`
  630. set `A_STATUS`='NORMAL'
  631. , `A_RECORD_UPDATE_AUTHOR`='{$usrLogin}'
  632. , `A_RECORD_UPDATE_DATE`=NOW()
  633. , `actionExecutedTime`=NOW()
  634. where `ID`='{$msg['_raw']->ID}'
  635. ";
  636. $res = $db->query($sql);
  637. if (!$res || $db->has_errors()) throw new Exception("Wystąpiły błędy podczas próby zapisu wiadomości: " . implode("\n<br>", $db->get_errors()));
  638. }
  639. public function tableRowMsg($msg) {
  640. $idTable = $msg['idTable'];
  641. $idRow = $msg['idRow'];
  642. $usrAcl = User::getAcl();
  643. $tblAcl = $usrAcl->getTableAcl($idTable);
  644. $linkBase = "index.php?_route=TableMsgs";
  645. $linkBase .= "&idTable={$msg['idTable']}";
  646. $linkBase .= "&idRow={$msg['idRow']}";
  647. $rmMsgLink = "{$linkBase}&_task=removeMsg&id={$msg['_raw']->ID}";
  648. $backLink = "{$linkBase}&_task=tableRow";
  649. ?>
  650. <div class="container">
  651. <h3><i class="glyphicon glyphicon-envelope"></i> <a href="<?php echo $backLink; ?>">Wiadomości powiązane z rekordem nr <?php echo $idRow; ?></a>
  652. &raquo; Wiadomość nr <code><?php echo $msg['_raw']->ID; ?></code>
  653. <br><small>z tabeli <a href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=13051">Test permy</a></small>
  654. </h3>
  655. <div class="panel panel-<?php echo $msg['type']; ?>">
  656. <div class="panel-heading">
  657. <h3 class="panel-title">Wiadomość wysłana przez <?php echo $msg['_raw']->A_RECORD_CREATE_AUTHOR; ?>
  658. <span class="pull-right"><?php echo $msg['_raw']->A_RECORD_CREATE_DATE; ?></span></h3>
  659. </div>
  660. <div class="panel-body">
  661. <?php echo htmlspecialchars($msg['message']); ?>
  662. </div>
  663. <div class="panel-footer" style="overflow:hidden">
  664. <?php if (!empty($msg['_raw']->A_RECORD_UPDATE_DATE) && !empty($msg['_raw']->A_RECORD_UPDATE_AUTHOR)) : ?>
  665. <em style="margin-left:20px" class="text-muted">odczytana <?php echo $msg['_raw']->A_RECORD_UPDATE_DATE; ?> przez <?php echo $msg['_raw']->A_RECORD_UPDATE_AUTHOR; ?></em>
  666. <?php endif; ?>
  667. <?php if (!empty($msg['_raw']->A_RECORD_DELETE_DATE) && !empty($msg['_raw']->A_RECORD_DELETE_AUTHOR)) : ?>
  668. <em style="margin-left:20px" class="text-muted">usunięta <?php echo $msg['_raw']->A_RECORD_DELETE_DATE; ?> przez <?php echo $msg['_raw']->A_RECORD_DELETE_AUTHOR; ?></em>
  669. <?php endif; ?>
  670. <?php if ('DELETED' != $msg['_raw']->A_STATUS) : ?>
  671. <a href="<?php echo $rmMsgLink; ?>" class="btn btn-xs btn-default pull-right" title="usuń wiadomość" onclick="return confirm('Czy jesteś pewien że chcesz usunąć wiadomość?');"><i class="glyphicon glyphicon-remove"></i> Usuń</a>
  672. <?php endif; ?>
  673. </div>
  674. </div>
  675. </div>
  676. <?php
  677. // TODO: odpisz
  678. }
  679. public function removeMsgAction() {
  680. $idMsg = V::get('id', 0, $_GET, 'int');
  681. $idTable = V::get('idTable', 0, $_REQUEST, 'int');
  682. $idRow = V::get('idRow', 0, $_REQUEST, 'int');
  683. if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
  684. if ($idTable <= 0) throw new HttpException("Błęny numer tabeli", 400);
  685. if ($idRow <= 0) throw new HttpException("Błęny numer tabeli", 400);
  686. SE_Layout::gora();
  687. SE_Layout::menu();
  688. try {
  689. $msg = $this->_getMsg($idMsg, $idTable, $idRow);
  690. $this->_removeRowMsg($msg);
  691. } catch (Exception $e) {
  692. SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
  693. SE_Layout::dol();
  694. exit;
  695. }
  696. ?>
  697. <div class="container">
  698. <div class="alert alert-success">
  699. Wiadomość została usunięta <a class="btn btn-xs btn-default" href="index.php?_route=TableMsgs&_task=tableRow&idTable=<?php echo $idTable; ?>&idRow=<?php echo $idRow; ?>">wróć</a>
  700. </div>
  701. </div>
  702. <?php
  703. SE_Layout::dol();
  704. }
  705. public function _removeRowMsg($msg) {
  706. // IDEA: do kosza - add trigger to insert into `CRM_UI_MSGS__TRASH` after DELETE on `CRM_UI_MSGS`
  707. if (empty($msg['_raw']) || empty($msg['_raw']->ID)) throw new Exception("Brak wiadomości!");
  708. $usrLogin = User::getLogin();
  709. $db = DB::getDB();
  710. if (!$db) throw new Exception("Brak dazy danych!");
  711. if ($db->has_errors()) throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  712. $sqlTODO = "delete `CRM_UI_MSGS` where `ID`='{$msg['_raw']->ID}' ";
  713. $sql = "update `CRM_UI_MSGS`
  714. set `A_STATUS`='DELETED'
  715. , `A_RECORD_DELETE_AUTHOR`='{$usrLogin}'
  716. , `A_RECORD_DELETE_DATE`=NOW()
  717. where `ID`='{$msg['_raw']->ID}'
  718. ";
  719. $res = $db->query($sql);
  720. if (!$res || $db->has_errors()) throw new Exception("Wystąpiły błędy podczas próby zapisu wiadomości: " . implode("\n<br>", $db->get_errors()));
  721. }
  722. }