AclStruct.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. Lib::loadClass('Router');
  4. Lib::loadClass('Response');
  5. Lib::loadClass('UI');
  6. Lib::loadClass('SchemaFactory');
  7. class Route_Storage_AclStruct extends RouteBase {
  8. public function handleAuth() {
  9. if (!User::logged()) {
  10. User::authByRequest();
  11. }
  12. }
  13. public function defaultAction() {
  14. UI::gora();
  15. UI::menu();
  16. // Router::getRoute('Storage')->navView(); // TODO: header like in Storage_AclUsage
  17. UI::startTag('div', [ 'class' => 'container-fluid' ]);
  18. try {
  19. $namespace = V::get('namespace', '', $_GET);
  20. if (empty($namespace)) throw new Exception("Missing param namespace");
  21. // [idZasob] => 25872
  22. // [idDatabase] => 36
  23. // [namespace] => default_db/CRM_PROCES/CRM_PROCES
  24. // [_rootTableName] => CRM_PROCES
  25. // [_type] => AntAcl
  26. // [hasStruct] => 1
  27. // [isStructInstalled] => 1
  28. // [isObjectActive] => 1
  29. // [description] =>
  30. // [name] => CRM_PROCES
  31. // [nsPrefix] => default_db__x3A__CRM_PROCES
  32. // [typeName] => default_db__x3A__CRM_PROCES:CRM_PROCES
  33. // [reinstallLink] => https://biuro.biall-net.pl/dev-pl/se-master/index.php?_route=Storage_AclReinstall&namespace=default_db/CRM_PROCES/CRM_PROCES
  34. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  35. switch ($item['_type']) {
  36. case 'TableAcl': $this->tableStructView($item, $item['name'], $item['idDatabase']); break;
  37. case 'AntAcl': $this->objectStructView($item); break;
  38. case 'StorageAcl': $this->objectStructView($item); break;
  39. default: throw new Exception("Not implemented type"); break;
  40. }
  41. } catch (Exception $e) {
  42. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  43. DBG::log($e);
  44. }
  45. UI::endTag('div'); // .container-fluid
  46. UI::dol();
  47. }
  48. public function tableStructAction() {
  49. UI::gora();
  50. UI::menu();
  51. // Router::getRoute('Storage')->navView(); // TODO: header like in Storage_AclUsage
  52. try {
  53. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  54. if (empty($idStorage)) throw new Exception("Missing id storage");
  55. $storageList = Router::getRoute('Storage')->getStorageList();
  56. if (empty($storageList)) throw new Exception("No storage defined");
  57. if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
  58. $tblName = V::get('table', '', $_REQUEST, 'word');
  59. if (empty($tblName)) throw new Exception("No table name");
  60. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  61. $this->tableStructView($item, $tblName, $idStorage);
  62. } catch (Exception $e) {
  63. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  64. }
  65. UI::dol();
  66. }
  67. public function objectStructureAction() { // objectStructAction
  68. UI::gora();
  69. UI::menu();
  70. // Router::getRoute('Storage')->navView(); // TODO: header like in Storage_AclUsage
  71. UI::startTag('div', [ 'class' => 'container-fluid' ]);
  72. try {
  73. $namespace = V::get('namespace', '', $_GET);
  74. if (empty($namespace)) throw new Exception("Missing param namespace");
  75. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  76. $this->objectStructView($item);
  77. } catch (Exception $e) {
  78. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  79. DBG::log($e);
  80. }
  81. UI::endTag('div'); // .container-fluid
  82. UI::dol();
  83. }
  84. public function tableStructView($item, $tblName, $idStorage) {
  85. $storagePdo = DB::getStorage($idStorage);
  86. $tblStruct = $storagePdo->getTableStruct($tblName);
  87. $idTable = Router::getRoute('Storage')->fetchTableId($idStorage, $tblName);
  88. if ($idTable <= 0) {
  89. UI::alert('warning', "Zasob tabela '{$tblName}' nie istnieje");// TODO: add p5UI btn
  90. DBG::table("tblStruct", $tblStruct, __CLASS__, __FUNCTION__, __LINE__);
  91. throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  92. }
  93. $cellZasobList = array();
  94. foreach (DB::getPDO()->fetchAllByKey("
  95. select z.ID, z.`DESC`, z.`TYPE` as ZASOB_TYPE, z.A_STATUS, z.SORT_PRIO
  96. from CRM_LISTA_ZASOBOW z
  97. where z.PARENT_ID = '{$idTable}'
  98. ", $key = 'DESC') as $ind => $row) {
  99. $cellZasobList[strtolower($ind)] = $row;
  100. }
  101. $emptyItem = array();
  102. $emptyItem['sort'] = null;
  103. $emptyItem['name'] = '';
  104. $emptyItem['id_zasob'] = '';
  105. $emptyItem['zasob_type'] = '';
  106. $emptyItem['uwagi'] = '';
  107. $emptyItem['type'] = '';
  108. $emptyItem['is_nullable'] = '';
  109. $emptyItem['default_value'] = '';
  110. $emptyItem['default_is_null'] = '';
  111. $emptyItem['max_length'] = '';
  112. $emptyItem['num_precision'] = '';
  113. $emptyItem['num_scale'] = '';
  114. $emptyItem['char_encoding'] = '';
  115. $emptyItem['char_collation'] = '';
  116. $emptyItem['extra'] = '';
  117. $emptyItem['raw_storage_type'] = '';
  118. $tableList = array();
  119. foreach ($tblStruct as $row) {
  120. $cellName = $row['name'];
  121. $tblItem = V::cloneArray($emptyItem);
  122. $tblItem['name'] = $cellName;
  123. foreach ($row as $fldName => $fldVal) {
  124. if (array_key_exists($fldName, $tblItem)) $tblItem[$fldName] = $fldVal;
  125. }
  126. $tblItem['uwagi'] = '';
  127. $lowerCellName = strtolower($cellName);
  128. $tblZasob = V::get($lowerCellName, '', $cellZasobList);
  129. if ($tblZasob) {
  130. $cellZasobList[$lowerCellName]['_checked'] = true;
  131. $tblItem['id_zasob'] = $tblZasob['ID'];
  132. $tblItem['zasob_type'] = $tblZasob['ZASOB_TYPE'];
  133. $tblItem['sort'] = $tblZasob['SORT_PRIO'];
  134. } else {
  135. $tblItem['uwagi'] .= '!Zasob';//'TODO: ADD ZASOB';
  136. $ajaxAddZasobLink = Router::getRoute('Storage')->getLink('addCellToZasoby', [ 'idStorage' => $idStorage, 'tblName' => $tblName, 'cellName' => $cellName]);
  137. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addCellToZasoby', { href: '{$ajaxAddZasobLink}' })";
  138. $tblItem['id_zasob'] = '<a onclick="'.$onClick.'" class="btn btn-xs btn-primary" href="#">TODO: ADD ZASOB</a>';
  139. }
  140. $tableList[] = $tblItem;
  141. }
  142. foreach ($cellZasobList as $cellName => $row) {
  143. if ('URL_ACTION' == $row['ZASOB_TYPE']) continue;
  144. if (!$row['_checked']) {
  145. $tblItem = V::cloneArray($emptyItem);
  146. $tblItem['name'] = $cellName;
  147. $tblItem['id_zasob'] = $row['ID'];
  148. $tblItem['zasob_type'] = $row['ZASOB_TYPE'];
  149. $tblItem['uwagi'] = '!DB';//'TODO: nie istnieje w bazie danych';
  150. $tableList[] = $tblItem;
  151. }
  152. }
  153. { // sortBy
  154. $sortByArgName = 'sortBy';
  155. $sortByCol = V::get($sortByArgName, 'name', $_GET);
  156. $sortByDir = V::get("{$sortByArgName}Dir", 'asc', $_GET);
  157. if ('name' === $sortByCol) {
  158. usort($tableList, function($rowA, $rowB) {
  159. $a = $rowA['name']; $b = $rowB['name'];
  160. // if ('ID' == $a) return -1;
  161. // if ('ID' == $b) return 1;
  162. if ($a == $b) return 0;
  163. $a1 = substr($a, 0, 1); $b1 = substr($b, 0, 1);
  164. if (('_' == $a1 || '_' == $b1) && $a1 != $b1) {
  165. return ($a1 < $b1) ? 1 : -1;
  166. }
  167. return ($a < $b) ? -1 : 1;
  168. });
  169. }
  170. else if ('sort' === $sortByCol) {
  171. usort($tableList, function ($a, $b) use ($sortByDir) {
  172. if (null === $a['sort'] && null === $b['sort']) return 0;
  173. if (null === $a['sort'] && null != $b['sort']) return 1;
  174. if (null !== $a['sort'] && null === $b['sort']) return -1;
  175. if ($a['sort'] > $b['sort']) return 'asc' === $sortByDir ? 1 : -1;
  176. if ($a['sort'] < $b['sort']) return 'asc' === $sortByDir ? -1 : 1;
  177. return 0;
  178. });
  179. }
  180. echo UI::h('style', [ 'type' => "text/css" ], "
  181. .ta-ordering { cursor:pointer }
  182. .ta-ordering-desc:after { content:\"\\e252\"; font-family:\"Glyphicons Halflings\"; line-height:1; margin:0 0 0 3px; display:inline-block; color:#bbb }
  183. .ta-ordering-asc:after { content:\"\\e253\"; font-family:\"Glyphicons Halflings\"; line-height:1; margin:0 0 0 3px; display:inline-block; color:#bbb }
  184. .ta-sortable-item { }
  185. .ta-sortable-item-handle { cursor:pointer }
  186. ");
  187. echo UI::h('script', [ 'src' => "static/URI.js" ]);
  188. echo UI::h('script', [], "
  189. function p5UI_table_sortBy_get(n, argName, colName, dir) {
  190. var newUri = URI(window.location.href).setQuery(argName, colName).setQuery(argName+'Dir', dir).build().toString();
  191. window.location.href = newUri
  192. }
  193. ");
  194. }
  195. UI::table([
  196. '__html_id' => 'struct_table',
  197. 'caption' => UI::h('span', [], [
  198. "Struktura tabeli {$tblName} [{$idTable}] ",
  199. UI::h('a', [
  200. 'href' => "index.php?_route=ViewTableAjax&namespace=default_db/{$tblName}",
  201. 'class' => "btn btn-md btn-link"
  202. ], "Przeglądaj tabelę"),
  203. UI::h('a', [
  204. 'href' => "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$idTable}&filtr_ids=%2B&filtr_ob=%2B",
  205. 'class' => "btn btn-md btn-link",
  206. 'title' => "Struktura aktualnie przeglądanej tabeli"
  207. ], "Zasoby"),
  208. UI::h('a', [
  209. 'href' => "index.php?FUNCTION_INIT=PROCES_MENU&HEADER_NOT_INIT=YES&_task=PROCES_FOR_TABLE&tblId={$idTable}",
  210. 'class' => "btn btn-md btn-link",
  211. 'title' => "Procesy dla aktualnie przeglądanej tabeli"
  212. ], "Procesy"),
  213. UI::h('a', [
  214. 'href' => Router::getRoute('Storage_AclUsage')->getLink('', [ 'namespace' => "default_db/{$tblName}" ]),
  215. 'class' => "btn btn-md btn-link",
  216. 'title' => "Uprawnienia - analiza użycia komórek w procesach"
  217. ], "Uprawnienia (analiza użycia)"),
  218. UI::h('a', [
  219. // $idStorage = V::get('idStorage', '', $_GET);
  220. // $tblName = V::get('table', '', $_GET, 'word');
  221. 'href' => Router::getRoute('Storage')->getLink('tableXsd', [ 'idStorage' => $idStorage, 'table' => "{$tblName}" ]),
  222. 'class' => "btn btn-md btn-link",
  223. ], "xsd"),
  224. ]),
  225. 'cols_label' => [
  226. 'sort' => UI::h('nobr', [
  227. 'class' => "ta-ordering" . ('sort' === $sortByCol ? " ta-ordering-" . ( 'asc' === $sortByDir ? 'asc' : 'desc' ) : '' ),
  228. 'onClick' => "return p5UI_table_sortBy_get(this, '{$sortByArgName}', 'sort', '" . ('sort' === $sortByCol ? ( 'asc' === $sortByDir ? 'desc' : 'asc' ) : 'asc' ) . "')",
  229. 'title' => "Sortuj wg pola SORT_PRIO z zasobów",
  230. ], "sort"),
  231. 'name' => UI::h('nobr', [
  232. 'class' => "ta-ordering" . ('name' === $sortByCol ? " ta-ordering-" . ( 'asc' === $sortByDir ? 'asc' : 'desc' ) : '' ),
  233. 'onClick' => "return p5UI_table_sortBy_get(this, '{$sortByArgName}', 'name', '" . ('name' === $sortByCol ? ( 'asc' === $sortByDir ? 'desc' : 'asc' ) : 'asc' ) . "')",
  234. 'title' => "Sortuj wg nazwy",
  235. ], "namespace"),
  236. ],
  237. 'cols' => array_keys($emptyItem),
  238. 'rows' => array_map(function ($item) use ($sortByCol) {
  239. if ('sort' === $sortByCol && null !== $item['sort'] && !empty($item['id_zasob'])) {
  240. $item['@class'] = "ta-sortable-item";
  241. $item['@class[sort]'] = "ta-sortable-item-handle";
  242. $item['@data']['sort_prio'] = $item['sort'];
  243. $item['@data']['id_zasob'] = $item['id_zasob'];
  244. $item['sort'] = ":: {$item['sort']}";
  245. }
  246. return $item;
  247. }, $tableList),
  248. ]);
  249. echo UI::h('script', [], "
  250. jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:click', function(e, n, payload) {
  251. console.log('event p5UIBtnAjax:Storage:addCellToZasoby:click', n, payload);
  252. });
  253. jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', function(e, n, payload) {
  254. console.log('event p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', n, payload);
  255. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  256. var cellUwagiJQNode = jQuery(n).parents('td').next('td');
  257. cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
  258. jQuery(n).parents('td').text(payload.body.id);
  259. jQuery(n).remove();
  260. }
  261. jQuery.notify(payload.msg, payload.type);
  262. });
  263. ");
  264. $ajaxAddZasobLink = Router::getRoute('Storage')->getLink('addGeomEtykietaCells', [ 'idStorage' => $idStorage, 'tblName' => $tblName]);
  265. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addGeomEtykietaCells', { href: '{$ajaxAddZasobLink}' })";
  266. UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj komórki etykiet", true);
  267. echo "<i>(<code>`etykieta_x`</code>, <code>`etykieta_y`</code>, <code>`etykieta_obrot`</code>)</i>";
  268. echo UI::h('script', [], "
  269. jQuery(document).on('p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', function(e, n, payload) {
  270. console.log('event p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', n, payload);
  271. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  272. var cellUwagiJQNode = jQuery(n).parents('td').next('td');
  273. cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
  274. jQuery(n).parents('td').text(payload.body.id);
  275. jQuery(n).remove();
  276. }
  277. jQuery.notify(payload.msg, payload.type);
  278. });
  279. ");
  280. $tableActions = array_filter($cellZasobList, function ($row) {
  281. return ('URL_ACTION' == $row['ZASOB_TYPE']);
  282. });
  283. UI::table([
  284. 'caption' => "tableActions",
  285. // 'cols' => array_keys($emptyItem),
  286. 'rows' => array_map(function ($item) {
  287. $sqlIdAction = DB::getPDO()->quote($item['ID'], PDO::PARAM_INT);
  288. $args = DB::getPDO()->fetchAll("
  289. select z.`DESC`
  290. , a.ID as ALIAS_ID, a.`DESC` as ALIAS_DESC, a.OPIS as ALIAS_OPIS
  291. from CRM_LISTA_ZASOBOW z
  292. left join CRM_LISTA_ZASOBOW a on(a.ID = z.ALIAS_ID)
  293. where z.PARENT_ID = {$sqlIdAction}
  294. and z.`TYPE` = 'PARAM_IN'
  295. ");
  296. $definitionArgs = DB::getPDO()->fetchAll("
  297. select p.ID, p.`DESC`
  298. from CRM_LISTA_ZASOBOW z
  299. join CRM_LISTA_ZASOBOW d on(d.ID = z.ALIAS_ID)
  300. left join CRM_LISTA_ZASOBOW p on(p.PARENT_ID = d.ID)
  301. where z.ID = {$sqlIdAction}
  302. and p.`TYPE` = 'PARAM_IN'
  303. ");
  304. $flatDefinitionArgs = implode(";", array_map(function ($arg) {
  305. return "{$arg['ID']}={$arg['DESC']}";
  306. }, $definitionArgs));
  307. return [
  308. 'label' => DB::getPDO()->fetchValue(" select z.OPIS from CRM_LISTA_ZASOBOW z where z.ID = {$sqlIdAction} ") . " " .
  309. UI::h('i', [
  310. 'class' => "glyphicon glyphicon-pencil",
  311. 'style' => "cursor:pointer",
  312. 'onClick' => "return Storage__tableStruct__editActionLabel(this, {$sqlIdAction})"], ''),
  313. 'args' => implode("<br>&", array_map(function ($item) {
  314. return (NULL === $item['ALIAS_ID'])
  315. ? $item['DESC']
  316. : "{$item['DESC']}=" . '{$row["' . $item['ALIAS_DESC'] . '"]}';// TODO: add rmParam btn
  317. }, $args)) . " " .
  318. UI::h('i', [
  319. 'class' => "glyphicon glyphicon-plus-sign",
  320. 'style' => "cursor:pointer",
  321. 'title' => "Dodaj PARAM_IN",
  322. 'onClick' => "return Storage__tableStruct__addParamAction(this, {$sqlIdAction}, '{$flatDefinitionArgs}')"], ''),
  323. // 'args_info' => '<pre>' . var_export($args, true) . '</pre>',
  324. 'ID' => $item['ID'],
  325. 'DESC' => $item['DESC'],
  326. 'A_STATUS' => $item['A_STATUS'],
  327. 'definition args' => implode("", array_map(function ($item) {
  328. return '<div style="white-space:nowrap">' . "[{$item['ID']}] {$item['DESC']}" . '</div>';
  329. }, $definitionArgs)),
  330. ];
  331. }, $tableActions)
  332. ]);
  333. echo UI::h('button', [
  334. 'onClick'=>"Storage__tableStruct__addAction()",
  335. 'class'=>"btn btn-xs btn-default"
  336. ], "Dodaj Akcję");
  337. echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
  338. echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
  339. echo UI::h('style', [], "
  340. .swal2-radio.p5-swal-radio-as-list { text-align:left }
  341. .swal2-radio.p5-swal-radio-as-list > label { display:block; margin-left:20px }
  342. ");
  343. UI::inlineJS(__FILE__ . '.tableActions.js', [
  344. 'ID_STORAGE' => $idStorage,
  345. 'TABLE_NAME' => $tblName,
  346. 'FETCH_URL' => Router::getRoute('Storage')->getLink('fetchActionListAjax'),
  347. 'ADD_ACTION_URL' => Router::getRoute('Storage')->getLink('addActionAjax')
  348. ]);
  349. echo '<hr>';
  350. $ajaxAddBaseProcesLink = Router::getRoute('Storage')->getLink('addTableBaseProces', [ 'idStorage' => $idStorage, 'tblName' => $tblName ]);
  351. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addTableBaseProces', { href: '{$ajaxAddBaseProcesLink}' })";
  352. UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj podstawowy proces dla tabeli '{$tblName}' - read only", true);
  353. echo UI::h('script', [], "
  354. jQuery(document).on('p5UIBtnAjax:Storage:addTableBaseProces:ajaxLoaded', function(e, n, payload) {
  355. jQuery.notify(payload.msg, payload.type);
  356. });
  357. ");
  358. if ('sort' === $sortByCol) {
  359. echo UI::h('script', [], "
  360. jQuery(document).ready(function (){
  361. var tblNode$ = jQuery('#struct_table > tbody')
  362. var getOrder = function () {
  363. var orderIds = []
  364. jQuery('#struct_table > tbody').children('.ta-sortable-item').each(function (idx, trNode) {
  365. orderIds.push(jQuery(trNode).data('id_zasob'))
  366. })
  367. return orderIds
  368. }
  369. var sortOrder = getOrder()
  370. console.log('sortOrder - init', sortOrder)
  371. tblNode$.sortable({
  372. axis: 'y',
  373. handle: '.ta-sortable-item-handle',
  374. items: '.ta-sortable-item',
  375. update: function (event, ui) {
  376. sortOrder = getOrder()
  377. tblNode$.sortable('disable')
  378. tblNode$.find('.ta-sortable-item-handle').css({color:'silver'})
  379. console.log('TODO: disable sortable while ajax')
  380. // window.setTimeout(function () {
  381. // tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  382. // console.log('TODO: ajax fetch result')
  383. // tblNode$.sortable('enable')
  384. // tblNode$.sortable('cancel')
  385. // }, 1000)
  386. window.fetch(
  387. URI(window.location.href)
  388. .setSearch('_task', 'updateAntAclSortAjax')
  389. .setSearch('idZasobOrder', sortOrder)
  390. .build().toString(),
  391. {
  392. method: 'POST',
  393. headers: {
  394. 'Content-Type': 'application/x-www-form-urlencoded' // query string
  395. },
  396. credentials: 'same-origin',
  397. body: JSON.stringify({
  398. namespace: URI.parseQuery(window.location.search).namespace,
  399. sortBy: '{$sortByCol}',
  400. sortByDir: '{$sortByDir}',
  401. sortOrder: sortOrder,
  402. })
  403. }
  404. ).then(function(response) {
  405. return response.json()
  406. }).then(function(payload) {
  407. console.log('updateAntAclSortAjax response', payload);
  408. tblNode$.sortable('enable')
  409. if ('success' !== payload.type) {
  410. tblNode$.sortable('cancel')
  411. }
  412. tblNode$.sortable('enable')
  413. tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  414. p5UI__notifyAjaxCallback({
  415. type: payload.type || 'error',
  416. msg: payload.msg || 'Request error'
  417. });
  418. if ('success' === payload.type) {
  419. window.location.reload(true)
  420. }
  421. }).catch(function(e) {
  422. tblNode$.sortable('enable')
  423. tblNode$.sortable('cancel')
  424. tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  425. p5UI__notifyAjaxCallback({
  426. type: 'error',
  427. msg: 'Request error ' + e
  428. });
  429. })
  430. }
  431. });
  432. });
  433. ");
  434. }
  435. }
  436. public function objectStructView($item) {
  437. $namespace = $item['namespace'];
  438. { // sortBy
  439. $sortByArgName = 'sortBy';
  440. $sortByCol = V::get($sortByArgName, 'namespace', $_GET);
  441. $sortByDir = V::get("{$sortByArgName}Dir", 'asc', $_GET);
  442. { // add SORT_PRIO
  443. $item['field'] = array_map(function ($field) {
  444. $field['SORT_PRIO'] = ($field['idZasob'] > 0)
  445. ? DB::getPDO()->fetchValue("
  446. select z.SORT_PRIO
  447. from CRM_LISTA_ZASOBOW z
  448. where z.ID = :id
  449. ", [ ':id' => $field['idZasob'] ])
  450. : null
  451. ;
  452. return $field;
  453. }, $item['field']);
  454. }
  455. if ('namespace' === $sortByCol) {
  456. usort($item['field'], function ($a, $b) use ($sortByDir) {
  457. if ($a['fieldNamespace'] > $b['fieldNamespace']) return 'asc' === $sortByDir ? 1 : -1;
  458. if ($a['fieldNamespace'] < $b['fieldNamespace']) return 'asc' === $sortByDir ? -1 : 1;
  459. return 0;
  460. });
  461. }
  462. else if ('sort' === $sortByCol) {
  463. usort($item['field'], function ($a, $b) use ($sortByDir) {
  464. if (null === $a['SORT_PRIO'] && null === $b['SORT_PRIO']) return 0;
  465. if (null === $a['SORT_PRIO'] && null != $b['SORT_PRIO']) return 1;
  466. if (null !== $a['SORT_PRIO'] && null === $b['SORT_PRIO']) return -1;
  467. if ($a['SORT_PRIO'] > $b['SORT_PRIO']) return 'asc' === $sortByDir ? 1 : -1;
  468. if ($a['SORT_PRIO'] < $b['SORT_PRIO']) return 'asc' === $sortByDir ? -1 : 1;
  469. return 0;
  470. });
  471. }
  472. echo UI::h('style', [ 'type' => "text/css" ], "
  473. .ta-ordering { cursor:pointer }
  474. .ta-ordering-desc:after { content:\"\\e252\"; font-family:\"Glyphicons Halflings\"; line-height:1; margin:0 0 0 3px; display:inline-block; color:#bbb }
  475. .ta-ordering-asc:after { content:\"\\e253\"; font-family:\"Glyphicons Halflings\"; line-height:1; margin:0 0 0 3px; display:inline-block; color:#bbb }
  476. .ta-sortable-item { }
  477. .ta-sortable-item-handle { cursor:pointer }
  478. ");
  479. echo UI::h('script', [ 'src' => "static/URI.js" ]);
  480. echo UI::h('script', [], "
  481. function p5UI_table_sortBy_get(n, argName, colName, dir) {
  482. var newUri = URI(window.location.href).setQuery(argName, colName).setQuery(argName+'Dir', dir).build().toString();
  483. window.location.href = newUri
  484. }
  485. ");
  486. }
  487. if ('setFieldRefConfig' === V::get('_postTask', '', $_POST)) {
  488. $field = V::get('field', '', $_POST);
  489. $source = V::get('source', '', $_POST);
  490. switch ($source) {
  491. case 'view':
  492. $refSelect = ACL::generateRefSelectSqlByFlatRelationCache($namespace, $field);
  493. ACL::setRefSource($namespace, $field, 'view', $refSelect);
  494. break;
  495. case 'table': ACL::setRefSource($namespace, $field, 'table'); break;
  496. }
  497. }
  498. if ('preview' === V::get('_postTask', '', $_POST)) {
  499. try {
  500. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  501. $localFields = array_filter($item['field'], function ($field) {
  502. return $field['isLocal'];
  503. });
  504. $refFields = array_filter($item['field'], function ($field) {
  505. return 'ref:' === substr($field['xsdType'], 0, 4);
  506. });
  507. $activeRefFields = array_filter($refFields, function ($field) {
  508. $refNamespace = str_replace(['__x3A__', ':'], '/', substr($field['xsdType'], strlen('ref:')));
  509. return (1 == DB::getPDO()->fetchValue("
  510. select t.isObjectActive
  511. from `CRM_#CACHE_ACL_OBJECT` t
  512. where t.`namespace` = '{$refNamespace}'
  513. "));
  514. });
  515. $previewItems = ACL::getAclByNamespace($namespace)->buildQuery([])->getItems([
  516. 'limit' => 5
  517. ]);
  518. DBG::nicePrint($previewItems, 'items (default query) - preview (limit 5)');
  519. $query = [ 'cols' => array_merge(
  520. array_map(
  521. function ($field) {
  522. return $field['fieldNamespace'];
  523. }, $localFields
  524. ),
  525. array_map(
  526. function ($field) {
  527. return "{$field['fieldNamespace']}/*";
  528. }, $activeRefFields
  529. )
  530. ) ];
  531. DBG::nicePrint($query, 'items with ref/* - query');
  532. $previewItems = ACL::getAclByNamespace($namespace)->buildQuery($query)->getItems([
  533. 'limit' => 5
  534. ]);
  535. DBG::nicePrint($previewItems, 'items with ref/* - preview (limit 5)');
  536. $query = [ 'cols' => array_merge(
  537. array_map(
  538. function ($field) {
  539. return $field['fieldNamespace'];
  540. }, $localFields
  541. ),
  542. array_map(
  543. function ($field) {
  544. return "{$field['fieldNamespace']}";
  545. }, $activeRefFields
  546. )
  547. ) ];
  548. DBG::nicePrint($query, 'items with ref as xlink - query');
  549. $previewItems = ACL::getAclByNamespace($namespace)->buildQuery($query)->getItems([
  550. 'limit' => 5
  551. ]);
  552. DBG::nicePrint($previewItems, 'items with ref as xlink - preview (limit 5)');
  553. } catch (Exception $e) {
  554. DBG::log($e);
  555. UI::alert('danger', $e->getMessage());
  556. }
  557. }
  558. echo UI::h('details', ['style'=>"margin-bottom:24px; padding:0 10px; background-color:#eee", 'open' => "open"], [
  559. UI::h('summary', ['style'=>"font-size:1.4em; line-height:2em; cursor:pointer; outline:none"], [
  560. "Struktura obiektu '{$namespace}' ",
  561. // UI::h('small', ['style'=>"font-size:0.8em; font-style:italic; color:#aaa"], " więcej...")
  562. ]),
  563. UI::h('div', ['style'=>"padding:4px 24px; border-top:1px solid #fff"], [
  564. UI::h('span', ['style'=>"margin-right:12px"], [
  565. ( ($item['idZasob'] > 0)
  566. ? UI::h('span', [ 'title' => "Nr zasobu '{$item['idZasob']}'" ], "Nr zasobu [{$item['idZasob']}]")
  567. : UI::h('span', [ 'title' => "Brak nr zasobu - dodaj do zasobów" ], [
  568. UI::hButtonAjax("+ do zasobów", 'addAclObjectToZasobyAjax', [
  569. 'class' => "btn btn-xs btn-primary",
  570. 'href' => Router::getRoute('Storage')->getLink('addAclObjectToZasobyAjax'),
  571. 'data' => [
  572. 'idStorage' => $item['idDatabase'],
  573. 'namespace' => $item['namespace'],
  574. ]
  575. ])
  576. ])
  577. ),
  578. ]),
  579. UI::h('span', ['style'=>"margin:0 12px"], [
  580. ( ($item['isObjectActive'] > 0)
  581. ? UI::h('span', [ 'class' => "label label-success", 'title' => "Namespace active" ], "Active")
  582. : UI::h('span', [ 'title' => "Namespace not active" ], [
  583. ($item['idZasob'] > 0)
  584. ? UI::hButtonAjax("Aktywuj", 'activateObjectAjax', [
  585. 'class' => "btn btn-xs btn-primary",
  586. 'href' => Router::getRoute('Storage')->getLink('activateObjectAjax'),
  587. 'data' => [
  588. 'namespace' => $item['namespace'],
  589. ]
  590. ])
  591. : '',
  592. ])
  593. ),
  594. ]),
  595. UI::h('a', [
  596. 'href' => "index.php?_route=ViewTableAjax&namespace={$item['namespace']}",
  597. 'class' => "btn btn-sm btn-link"
  598. ], "Przeglądaj tabelę"),
  599. ( ($item['idZasob'] > 0)
  600. ? UI::h('a', [
  601. 'href' => "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$item['idZasob']}&filtr_ids=%2B&filtr_ob=%2B",
  602. 'class' => "btn btn-sm btn-link",
  603. 'title' => "Struktura tabeli w drzewie zasobów"
  604. ], "Zasoby")
  605. : ''
  606. ),
  607. ( ($item['idZasob'] > 0)
  608. ? UI::h('a', [
  609. 'href' => "index.php?FUNCTION_INIT=PROCES_MENU&HEADER_NOT_INIT=YES&_task=PROCES_FOR_TABLE&tblId={$item['idZasob']}",
  610. 'class' => "btn btn-sm btn-link",
  611. 'title' => "Procesy dla aktualnie przeglądanej tabeli"
  612. ], "Procesy")
  613. : ''
  614. ),
  615. UI::h('a', [
  616. 'href' => Router::getRoute('Storage_AclReinstall')->getLink('', ['namespace' => $item['namespace']]),
  617. 'class' => 'btn btn-sm btn-link', 'style' => "color:#f00",
  618. 'title' => "Zainstaluje ponownie obiekt"
  619. ], "reinstall object"),
  620. UI::h('a', [
  621. 'href' => Router::getRoute('Storage_AclUsage')->getLink('', [ 'namespace' => $item['namespace'] ]),
  622. 'class' => "btn btn-sm btn-link",
  623. 'title' => "Uprawnienia - analiza użycia komórek w procesach"
  624. ], "Uprawnienia (analiza użycia)"),
  625. UI::hButtonPost("(podgląd z relacjami)", [
  626. 'data' => [
  627. '_postTask' => 'preview'
  628. ],
  629. 'class' => 'btn btn-sm btn-link', 'style' => "font-style:italic",
  630. 'title' => "Podgląd kilku ostatnich obiektów wraz z relacjami"
  631. ]),
  632. ])
  633. ]);
  634. $thisGetLink = [ $this, 'getLink' ];
  635. { // not installed ref
  636. $refFields = array_filter($item['field'], function ($field) {
  637. return ('ref:' === substr($field['xsdType'], 0, 4) && $field['isActive']);
  638. });
  639. UI::table([
  640. 'caption' => UI::h('span', [], "Obiekty powiązane (TODO backRef)"),
  641. 'rows' => array_map(function ($field) use ($thisGetLink) {
  642. $refNamespace = str_replace(['__x3A__', ':'], '/', substr($field['xsdType'], strlen('ref:')));
  643. $isInstalled = (1 == DB::getPDO()->fetchValue("
  644. select t.isObjectActive
  645. from `CRM_#CACHE_ACL_OBJECT` t
  646. where t.`namespace` = '{$refNamespace}'
  647. "));
  648. $refSource = null;
  649. if ($isInstalled) {
  650. try {
  651. $refTable = ACL::getRefTable($field['objectNamespace'], $field['fieldNamespace']);
  652. DBG::log($refTable, 'array', "getRefTable('{$field['objectNamespace']}', '{$field['fieldNamespace']}')");
  653. $refSource = ACL::getRefSource($field['objectNamespace'], $field['fieldNamespace']);
  654. DBG::log($refSource, 'array', "ACL::getRefSource('{$field['objectNamespace']}', '{$field['fieldNamespace']}')");
  655. } catch (Exception $e) {
  656. DBG::log($e);
  657. }
  658. }
  659. return [
  660. 'fieldName' => $field['fieldNamespace'],
  661. // 'xsdType' => $field['xsdType'], // always === "ref:{$field['fieldNamespace']}"
  662. 'ref object' => UI::h('a', [
  663. 'class' => "btn btn-xs btn-link",
  664. 'href' => $thisGetLink('', [ 'namespace' => $refNamespace ])
  665. ], "objectStruct ({$refNamespace})"),
  666. 'ref source' => UI::h('div', [],
  667. (null === $refSource)
  668. ? [ "ref object not installed" ] // TODO: link to install? is table struct
  669. : [
  670. // UI::hButtonAjax("Tabela ref", "setFieldRefConfig", [
  671. // 'class' => "btn btn-xs btn-default" . ( 'table' === $refSource ? ' disabled' : '' ),
  672. // 'href' => $thisGetLink('setFieldRefConfig'),
  673. // 'data' => [ 'namespace' => $refNamespace, 'field' => $field['fieldNamespace'], 'do' => 'table' ]
  674. // ]),
  675. // UI::hButtonAjax("Widok (cache)", "setFieldRefConfig", [
  676. // 'title' => "Według flat_relation_cache",
  677. // 'class' => "btn btn-xs btn-default" . ( 'view' === $refSource ? ' disabled' : '' ),
  678. // 'href' => $thisGetLink('setFieldRefConfig'),
  679. // 'data' => [ 'namespace' => $refNamespace, 'field' => $field['fieldNamespace'], 'do' => 'view' ]
  680. // ]),
  681. UI::hButtonPost("Tabela ref", [
  682. 'title' => "Według wygenerowanej tabeli REF",
  683. 'class' => "btn btn-xs btn-default" . ( 'table' === $refSource ? ' disabled' : '' ),
  684. // 'href' => $thisGetLink('setFieldRefConfig'),
  685. 'data' => [ 'namespace' => $refNamespace, 'field' => $field['fieldNamespace'], '_postTask' => 'setFieldRefConfig', 'source' => 'table' ]
  686. ]),
  687. UI::hButtonPost("Widok (cache)", [
  688. 'title' => "Według flat_relation_cache",
  689. 'class' => "btn btn-xs btn-default" . ( 'view' === $refSource ? ' disabled' : '' ),
  690. // 'href' => $thisGetLink('setFieldRefConfig'),
  691. 'data' => [ 'namespace' => $refNamespace, 'field' => $field['fieldNamespace'], '_postTask' => 'setFieldRefConfig', 'source' => 'view' ]
  692. ]),
  693. ]
  694. ),
  695. '@class' => ($isInstalled) ? "success" : "danger",
  696. ]; // TODO: link to install object
  697. }, $refFields)
  698. ]);
  699. }
  700. $thisGetLink = [ $this, 'getLink' ];
  701. UI::table([
  702. '__html_id' => 'struct_table',
  703. 'caption' => UI::h('span', [], [
  704. UI::h('span', [ 'style' => "margin-right:6px;color:#000" ], "Struktura obiektu '{$item['namespace']}'"),
  705. ]),
  706. // 'sortBy' => [
  707. // 'method' => 'get',
  708. // 'argName' => '_sortBy',
  709. // 'allow' => ['sort', 'namespace'],
  710. // 'default' => ['namespace', 'asc'],
  711. // ],
  712. 'cols_label' => [
  713. 'sort' => UI::h('nobr', [
  714. 'class' => "ta-ordering" . ('sort' === $sortByCol ? " ta-ordering-" . ( 'asc' === $sortByDir ? 'asc' : 'desc' ) : '' ),
  715. 'onClick' => "return p5UI_table_sortBy_get(this, '{$sortByArgName}', 'sort', '" . ('sort' === $sortByCol ? ( 'asc' === $sortByDir ? 'desc' : 'asc' ) : 'asc' ) . "')",
  716. 'title' => "Sortuj wg pola SORT_PRIO z zasobów",
  717. ], "sort"),
  718. 'namespace' => UI::h('nobr', [
  719. 'class' => "ta-ordering" . ('namespace' === $sortByCol ? " ta-ordering-" . ( 'asc' === $sortByDir ? 'asc' : 'desc' ) : '' ),
  720. 'onClick' => "return p5UI_table_sortBy_get(this, '{$sortByArgName}', 'namespace', '" . ('namespace' === $sortByCol ? ( 'asc' === $sortByDir ? 'desc' : 'asc' ) : 'asc' ) . "')",
  721. 'title' => "Sortuj wg nazwy pola",
  722. ], "namespace"),
  723. ],
  724. 'rows' => array_map(function ($field) use ($item, $thisGetLink, $sortByCol) {
  725. $tblItem = [];
  726. if ('sort' === $sortByCol && null !== $field['SORT_PRIO'] && !empty($field['idZasob'])) {
  727. $tblItem['@class'] = "ta-sortable-item";
  728. $tblItem['@class[sort]'] = "ta-sortable-item-handle";
  729. $tblItem['@data']['sort_prio'] = $field['SORT_PRIO'];
  730. $tblItem['@data']['id_zasob'] = $field['idZasob'];
  731. $field['SORT_PRIO'] = ":: {$field['SORT_PRIO']}";
  732. }
  733. $tblItem['sort'] = V::get('SORT_PRIO', null, $field);
  734. foreach ($field as $k => $v) {
  735. if ('SORT_PRIO' === $k) continue;
  736. $tblItem[$k] = $v;
  737. }
  738. $tblItem['namespace'] = UI::h('span', [], [
  739. UI::h('span', ['style' => "color:#aaa"], substr($field['namespace'], 0, strlen($field['objectNamespace']) + 1)),
  740. UI::h('span', ['style' => "color:#000"], substr($field['namespace'], strlen($field['objectNamespace']) + 1)),
  741. ]);
  742. $tblItem['idZasob'] = ($field['idZasob'] > 0)
  743. ? $field['idZasob']
  744. : (
  745. ($item['idZasob'] > 0)
  746. ? UI::hButtonAjax("+ do zasobów", 'addFieldToZasobyAjax', [
  747. 'class' => "btn btn-xs btn-primary",
  748. 'href' => $thisGetLink('addFieldToZasobyAjax'),
  749. 'data' => [
  750. 'namespace' => $item['namespace'],
  751. 'fieldNamespace' => $field['namespace'],
  752. ]
  753. ])
  754. : UI::h('span', ['title'=>"Brak Nr zasobu dla obiektu", 'class'=>"btn btn-xs btn-danger"], "Brak nr zasobu obiektu")
  755. )
  756. ;
  757. unset($tblItem['objectNamespace']);
  758. unset($tblItem['fieldNamespace']);
  759. return $tblItem;
  760. }, array_filter($item['field'], function ($field) { return $field['isActive']; }))
  761. ]);
  762. $removedFields = array_filter($item['field'], function ($field) { return !$field['isActive']; });
  763. if (!empty($removedFields)) {
  764. // echo UI::h('details', [ 'style' => "padding:6px; background-color:#333; color:#fff", 'open' => "open" ], [
  765. // UI::h('summary', [ 'style' => "padding:0 3px; outline:none; cursor:pointer" ], "WFS Response converted to JSON"),
  766. // UI::h('pre', [ 'id' => 'wfsResponse', 'style' => "margin:0; font-size:x-small; border-radius:0" ], 'loading...'),
  767. echo UI::h('details', [ 'style' => "margin-bottom:12px; padding:6px; background-color:#dedede; color:#000" ], [
  768. UI::h('summary', [ 'style' => "padding:0 3px; outline:none; cursor:pointer" ], "Pola w koszu (".count($removedFields).")"),
  769. UI::h('table', [ 'style' => "margin:6px 0 0 0; background-color:#fff; font-size:x-small", 'class' => "table table-bordered table-hover table-condensed" ], [
  770. UI::h('thead', [], [
  771. UI::h('tr', [], [
  772. UI::h('th', [], "#"),
  773. UI::h('th', [], "namespace"),
  774. UI::h('th', [], "xsdType"),
  775. UI::h('th', [], "xsdRestrictions"),
  776. UI::h('th', [], "appInfo"),
  777. UI::h('th', [], "minOccurs"),
  778. UI::h('th', [], "maxOccurs"),
  779. UI::h('th', [], "isActive"),
  780. ]),
  781. ]),
  782. UI::h('tbody', [], array_map(function ($field) use ($item, $thisGetLink) {
  783. return UI::h('tr', [], [
  784. UI::h('td', [], [
  785. UI::hButtonAjax("usuń", 'removeFieldFromTrashAjax', [
  786. 'class' => "btn btn-xs btn-danger",
  787. 'href' => $thisGetLink('removeFieldFromTrashAjax'),
  788. 'data' => [
  789. 'namespace' => $item['namespace'],
  790. 'fieldNamespace' => $field['namespace'],
  791. ]
  792. ])
  793. ]),
  794. UI::h('td', [], $field['fieldNamespace']),
  795. UI::h('td', [], $field['xsdType']),
  796. UI::h('td', [], $field['xsdRestrictions']),
  797. UI::h('td', [], $field['appInfo']),
  798. UI::h('td', [], $field['minOccurs']),
  799. UI::h('td', [], $field['maxOccurs']),
  800. UI::h('td', [], $field['isActive']),
  801. ]);
  802. }, $removedFields)),
  803. ]),
  804. ]);
  805. }
  806. UI::hButtonAjaxOnResponse('removeFieldFromTrashAjax', /* payload, n */ "
  807. if (!payload.type) return false
  808. jQuery.notify(payload.msg, payload.type)
  809. if ('success' == payload.type) {
  810. var trJqNode = jQuery(n).closest('tr')
  811. var tbodyJqNode = trJqNode.parent()
  812. var detailsJqNode = trJqNode.closest('details')
  813. trJqNode.remove()
  814. if (!tbodyJqNode.children().length) {
  815. detailsJqNode.remove()
  816. }
  817. }
  818. ");
  819. UI::hButtonAjaxOnResponse('addFieldToZasobyAjax', /* payload, n */ "
  820. if (!payload.type) return false
  821. if (payload.body && payload.body.id && payload.body.id > 0) { // if ('success' == payload.type) {
  822. n.parentNode.replaceChild(document.createTextNode(payload.body.id), n)
  823. }
  824. jQuery.notify(payload.msg, payload.type)
  825. ");
  826. UI::hButtonAjaxOnResponse('addAclObjectToZasobyAjax', /* payload, n */ "
  827. if (!payload.type) return false
  828. if ('success' === payload.type || 'info' === payload.type) {
  829. if (payload.body && payload.body.id && payload.body.id > 0) {
  830. n.parentNode.replaceChild(document.createTextNode(payload.body.id), n)
  831. } else {
  832. console.log('TODO: addAclObjectToZasobyAjax unknown response', payload);
  833. }
  834. window.location.reload()
  835. }
  836. ");
  837. UI::hButtonAjaxOnResponse('activateObjectAjax', /* payload, n */ "
  838. jQuery.notify(payload.msg, payload.type)
  839. if (!payload.type) return false
  840. if ('success' === payload.type || 'info' === payload.type) {
  841. if (payload.body && payload.body.isObjectActive && payload.body.isObjectActive > 0) {
  842. n.parentNode.replaceChild(document.createTextNode('Active'), n)
  843. } else {
  844. console.log('TODO: activateObjectAjax unknown response', payload);
  845. }
  846. }
  847. ");
  848. if ('sort' === $sortByCol) {
  849. echo UI::h('script', [], "
  850. jQuery(document).ready(function (){
  851. var tblNode$ = jQuery('#struct_table > tbody')
  852. var getOrder = function () {
  853. var orderIds = []
  854. jQuery('#struct_table > tbody').children('.ta-sortable-item').each(function (idx, trNode) {
  855. orderIds.push(jQuery(trNode).data('id_zasob'))
  856. })
  857. return orderIds
  858. }
  859. var sortOrder = getOrder()
  860. console.log('sortOrder - init', sortOrder)
  861. tblNode$.sortable({
  862. axis: 'y',
  863. handle: '.ta-sortable-item-handle',
  864. items: '.ta-sortable-item',
  865. update: function (event, ui) {
  866. sortOrder = getOrder()
  867. tblNode$.sortable('disable')
  868. tblNode$.find('.ta-sortable-item-handle').css({color:'silver'})
  869. console.log('TODO: disable sortable while ajax')
  870. // window.setTimeout(function () {
  871. // tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  872. // console.log('TODO: ajax fetch result')
  873. // tblNode$.sortable('enable')
  874. // tblNode$.sortable('cancel')
  875. // }, 1000)
  876. window.fetch(
  877. URI(window.location.href)
  878. .setSearch('_task', 'updateAntAclSortAjax')
  879. .setSearch('idZasobOrder', sortOrder)
  880. .build().toString(),
  881. {
  882. method: 'POST',
  883. headers: {
  884. 'Content-Type': 'application/x-www-form-urlencoded' // query string
  885. },
  886. credentials: 'same-origin',
  887. body: JSON.stringify({
  888. namespace: URI.parseQuery(window.location.search).namespace,
  889. sortBy: '{$sortByCol}',
  890. sortByDir: '{$sortByDir}',
  891. sortOrder: sortOrder,
  892. })
  893. }
  894. ).then(function(response) {
  895. return response.json()
  896. }).then(function(payload) {
  897. console.log('updateAntAclSortAjax response', payload);
  898. tblNode$.sortable('enable')
  899. if ('success' !== payload.type) {
  900. tblNode$.sortable('cancel')
  901. }
  902. tblNode$.sortable('enable')
  903. tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  904. p5UI__notifyAjaxCallback({
  905. type: payload.type || 'error',
  906. msg: payload.msg || 'Request error'
  907. });
  908. if ('success' === payload.type) {
  909. window.location.reload(true)
  910. }
  911. }).catch(function(e) {
  912. tblNode$.sortable('enable')
  913. tblNode$.sortable('cancel')
  914. tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  915. p5UI__notifyAjaxCallback({
  916. type: 'error',
  917. msg: 'Request error ' + e
  918. });
  919. })
  920. }
  921. });
  922. });
  923. ");
  924. }
  925. if ($item['isObjectActive']) {
  926. echo UI::hButtonAjax("Dodaj podstawowy proces dla obiektu '{$item['namespace']}' - read only (TODO)", 'addObjectBaseProcesAjax', [
  927. 'class' => "btn btn-xs btn-default",
  928. 'href' => Router::getRoute('Storage')->getLink('addObjectBaseProcesAjax'),
  929. 'data' => [ 'namespace' => $item['namespace'] ]
  930. ]);
  931. UI::hButtonAjaxOnResponse('addObjectBaseProcesAjax', /* payload, n */ "
  932. jQuery.notify(payload.msg, payload.type)
  933. ");
  934. }
  935. DBG::nicePrint($item, '$item');
  936. }
  937. public function updateAntAclSortAjaxAction() {
  938. return Response::sendTryCatchJson(array($this, 'updateAntAclSortAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  939. }
  940. public function updateAntAclSortAjax($args) {
  941. DBG::log($args, 'array', "args");
  942. $namespace = V::get('namespace', '', $args);
  943. if (empty($namespace)) throw new Exception("Missing param namespace");
  944. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  945. DBG::log($item, 'array', "\$item");
  946. $sortByArgName = 'sortBy';
  947. $sortByCol = V::get($sortByArgName, 'namespace', $args);
  948. $sortByDir = V::get("{$sortByArgName}Dir", 'asc', $args);
  949. if ('sort' !== $sortByCol) throw new Exception("Only sort by SORT_PRIO allowed to update");
  950. if (!in_array($sortByDir, ['asc', 'desc'])) throw new Exception("Wrong order by dir arg");
  951. if ('asc' !== $sortByDir) throw new Exception("Only sort asc is allowed"); // DBG
  952. $sortPrioIdsFromZasoby = DB::getPDO()->fetchAll("
  953. select z.ID, z.SORT_PRIO
  954. from CRM_LISTA_ZASOBOW z
  955. where z.PARENT_ID = :p_id
  956. order by z.SORT_PRIO asc, z.ID asc -- default order in Zasoby tree
  957. ", [
  958. ':p_id' => $item['idZasob']
  959. ]);
  960. DBG::log($sortPrioIdsFromZasoby, 'array', "\$sortPrioIdsFromZasoby");
  961. $idZasobCurrentOrder = array_map(function ($orderRow) {
  962. return (int)$orderRow['ID'];
  963. }, $sortPrioIdsFromZasoby);
  964. DBG::log($idZasobCurrentOrder, 'array', "\$idZasobCurrentOrder");
  965. DBG::log(array_diff_assoc($args['sortOrder'], $idZasobCurrentOrder), 'array', "array_diff_assoc(\$args['sortOrder'], \$idZasobCurrentOrder)");
  966. DBG::log(array_diff_assoc($idZasobCurrentOrder, $args['sortOrder']), 'array', "array_diff_assoc(\$idZasobCurrentOrder, \$args['sortOrder'])");
  967. $orderDiff = array_diff_assoc($args['sortOrder'], $idZasobCurrentOrder);
  968. foreach ($orderDiff as $sortPrio => $idZasob) {
  969. DB::getPDO()->update('CRM_LISTA_ZASOBOW', 'ID', $idZasob, [
  970. 'SORT_PRIO' => $sortPrio,
  971. ]);
  972. }
  973. return [
  974. 'type' => 'success',
  975. 'msg' => "OK",
  976. 'DBG__args' => $args
  977. ];
  978. }
  979. public function removeFieldFromTrashAjaxAction() {
  980. DBG::log($_REQUEST, 'array', '$_REQUEST');
  981. Response::sendTryCatchJson(array($this, 'removeFieldFromTrashAjax'), $_REQUEST);
  982. }
  983. public function removeFieldFromTrashAjax($args) {
  984. $namespace = V::get('namespace', '', $args);
  985. if (empty($namespace)) throw new HttpException("Missing namespace");
  986. $fieldNamespace = V::get('fieldNamespace', '', $args);
  987. if (empty($fieldNamespace)) throw new HttpException("Missing fieldNamespace");
  988. $fieldItem = SchemaFactory::loadDefaultObject('SystemObjectField')->getItem($fieldNamespace);
  989. if (!$fieldItem) throw new HttpException("Field not found '{$fieldNamespace}'", 404);
  990. DBG::log($fieldItem, 'array', "\$fieldItem");
  991. switch ($fieldItem['xsdType']) {
  992. case 'p5:enum': throw new Exception("TODO: remove enum values first"); break; // CRM_#CACHE_ACL_OBJECT_FIELD_enum
  993. default: {
  994. if ('ref:' === substr($fieldItem['xsdType'], 0, 4)) { // OK, remove
  995. } else throw new Exception("TODO: remove xsdType: {$fieldItem['xsdType']}");
  996. }
  997. }
  998. DB::getPDO()->execSql("
  999. DELETE from `CRM_#CACHE_ACL_OBJECT_FIELD`
  1000. where namespace = :namespace
  1001. and objectNamespace = :objectNamespace
  1002. and _rootTableName = :rootTableName
  1003. and isActive = 0
  1004. limit 1
  1005. ", [
  1006. 'namespace' => $fieldItem['namespace'],
  1007. 'objectNamespace' => $fieldItem['objectNamespace'],
  1008. 'rootTableName' => $fieldItem['_rootTableName'],
  1009. ]);
  1010. return [
  1011. 'type' => "success",
  1012. 'msg' => "Usunięto pole {$fieldItem['fieldNamespace']}",
  1013. ];
  1014. }
  1015. public function addFieldToZasobyAjaxAction() {
  1016. DBG::log($_REQUEST, 'array', '$_REQUEST');
  1017. Response::sendTryCatchJson(array($this, 'addFieldToZasobyAjax'), $_REQUEST);
  1018. }
  1019. public function addFieldToZasobyAjax($args) {
  1020. $namespace = V::get('namespace', '', $args);
  1021. if (empty($namespace)) throw new HttpException("Missing namespace");
  1022. $fieldNamespace = V::get('fieldNamespace', '', $args);
  1023. if (empty($fieldNamespace)) throw new HttpException("Missing fieldNamespace");
  1024. $fieldItem = SchemaFactory::loadDefaultObject('SystemObjectField')->getItem($fieldNamespace);
  1025. if (!$fieldItem) throw new HttpException("Field not found '{$fieldNamespace}'", 404);
  1026. DBG::log($fieldItem, 'array', "\$fieldItem");
  1027. if ($fieldItem['idZasob'] > 0) throw (new AlertSuccessException("Field already added to Zasoby '{$fieldItem['idZasob']}'"))->setBody([ 'id' => $fieldItem['idZasob'] ]);
  1028. $objectItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace);
  1029. if (!$objectItem) throw new HttpException("Object not found '{$namespace}'", 404);
  1030. DBG::log($objectItem, 'array', "\$objectItem");
  1031. if (!$objectItem['idZasob']) throw new Exception("Missing Object idZasob");
  1032. $zasobItem = DB::getPDO()->fetchFirst("
  1033. select zField.ID, zField.`DESC`, zField.`TYPE`, zField.PARENT_ID
  1034. from CRM_LISTA_ZASOBOW as zField
  1035. join CRM_LISTA_ZASOBOW as zTable on(zTable.ID = zField.PARENT_ID)
  1036. where zTable.`ID` = '{$objectItem['idZasob']}'
  1037. and zTable.`TYPE` = 'TABELA'
  1038. and zField.`DESC` = '{$fieldItem['fieldNamespace']}'
  1039. and zField.`TYPE` = 'KOMORKA'
  1040. ");
  1041. if ($zasobItem) {
  1042. SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
  1043. 'namespace' => $fieldItem['namespace'],
  1044. 'idZasob' => $zasobItem['ID']
  1045. ]);
  1046. throw (new AlertSuccessException("Zasob już istnieje"))->setBody([ 'id' => $zasobItem['ID'] ]);
  1047. }
  1048. $newFieldItem = [
  1049. 'PARENT_ID' => $objectItem['idZasob'],
  1050. 'TYPE' => 'KOMORKA',
  1051. 'DESC' => $fieldItem['fieldNamespace'],
  1052. 'DESC_PL' => $fieldItem['fieldNamespace'],
  1053. ];
  1054. DBG::log($newFieldItem, 'array', "add new field item");
  1055. try {
  1056. $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
  1057. } catch (Exception $e) {
  1058. throw new Exception("Brak dostępu do tabeli Zasoby");
  1059. }
  1060. $createdId = $acl->addItem($newFieldItem);
  1061. if (!$createdId) throw new Exception("Nie udało się utworzyć nowego rekordu!");
  1062. SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
  1063. 'namespace' => $fieldItem['namespace'],
  1064. 'idZasob' => $createdId
  1065. ]);
  1066. throw (new AlertSuccessException("Utworzono pomyślnie rekord nr {$createdId}"))->setBody([ 'id' => $createdId ]);
  1067. }
  1068. }