AclStruct.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  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. echo UI::h('details', ['style'=>"margin-bottom:24px; padding:0 10px; background-color:#eee", 'open' => "open"], [
  196. UI::h('summary', ['style'=>"font-size:1.4em; line-height:2em; cursor:pointer; outline:none"], [
  197. "Struktura obiektu '{$item['namespace']}' ",
  198. ]),
  199. UI::h('div', ['style'=>"padding:4px 24px; border-top:1px solid #fff"], [
  200. UI::h('span', ['style'=>"margin-right:12px"], [
  201. ( ($item['idZasob'] > 0)
  202. ? UI::h('span', [ 'title' => "Nr zasobu '{$item['idZasob']}'" ], "Nr zasobu [{$item['idZasob']}]")
  203. : UI::h('span', [ 'title' => "Brak nr zasobu - dodaj do zasobów" ], [
  204. UI::hButtonAjax("+ do zasobów", 'addAclObjectToZasobyAjax', [
  205. 'class' => "btn btn-xs btn-primary",
  206. 'href' => Router::getRoute('Storage')->getLink('addAclObjectToZasobyAjax'),
  207. 'data' => [
  208. 'idStorage' => $item['idDatabase'],
  209. 'namespace' => $item['namespace'],
  210. ]
  211. ])
  212. ])
  213. ),
  214. ]),
  215. // UI::h('span', ['style'=>"margin:0 12px"], [
  216. // ( ($item['isObjectActive'] > 0)
  217. // ? UI::h('span', [ 'class' => "label label-success", 'title' => "Namespace active" ], "Active")
  218. // : UI::h('span', [ 'title' => "Namespace not active" ], [
  219. // ($item['idZasob'] > 0)
  220. // ? UI::hButtonAjax("Aktywuj", 'activateObjectAjax', [
  221. // 'class' => "btn btn-xs btn-primary",
  222. // 'href' => Router::getRoute('Storage')->getLink('activateObjectAjax'),
  223. // 'data' => [
  224. // 'namespace' => $item['namespace'],
  225. // ]
  226. // ])
  227. // : '',
  228. // ])
  229. // ),
  230. // ]),
  231. UI::h('a', [
  232. 'href' => "index.php?_route=ViewTableAjax&namespace={$item['namespace']}",
  233. 'class' => "btn btn-sm btn-link"
  234. ], "Przeglądaj tabelę"),
  235. ( ($item['idZasob'] > 0)
  236. ? UI::h('a', [
  237. 'href' => "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$item['idZasob']}&filtr_ids=%2B&filtr_ob=%2B",
  238. 'class' => "btn btn-sm btn-link",
  239. 'title' => "Struktura tabeli w drzewie zasobów"
  240. ], "Zasoby")
  241. : ''
  242. ),
  243. ( ($item['idZasob'] > 0)
  244. ? UI::h('a', [
  245. 'href' => "index.php?FUNCTION_INIT=PROCES_MENU&HEADER_NOT_INIT=YES&_task=PROCES_FOR_TABLE&tblId={$item['idZasob']}",
  246. 'class' => "btn btn-sm btn-link",
  247. 'title' => "Procesy dla aktualnie przeglądanej tabeli"
  248. ], "Procesy")
  249. : ''
  250. ),
  251. // UI::h('a', [
  252. // 'href' => Router::getRoute('Storage_AclReinstall')->getLink('', [ 'namespace' => $item['namespace'] ]),
  253. // 'class' => 'btn btn-sm btn-link', 'style' => "color:#f00",
  254. // 'title' => "Zainstaluje ponownie obiekt"
  255. // ], "reinstall object"),
  256. UI::h('a', [
  257. 'href' => Router::getRoute('Storage_AclUsage')->getLink('', [ 'namespace' => $item['namespace'] ]),
  258. 'class' => "btn btn-sm btn-link",
  259. 'title' => "Uprawnienia - analiza użycia komórek w procesach"
  260. ], "Uprawnienia (analiza użycia)"),
  261. UI::h('a', [
  262. 'href' => Router::getRoute('WfsJsRequestPanel')->getLink('', [ 'namespace' => $item['namespace'] ]),
  263. 'class' => "btn btn-sm btn-link",
  264. 'title' => "JavaScript WFS Panel"
  265. ], "JavaScript WFS Panel"),
  266. UI::h('a', [
  267. 'href' => Router::getRoute('Storage_TestXsd')->getLink('tableXsd', [ 'idStorage' => $idStorage, 'table' => "{$tblName}" ]),
  268. 'class' => "btn btn-md btn-link",
  269. ], "xsd"),
  270. ])
  271. ]);
  272. UI::table([
  273. '__html_id' => 'struct_table',
  274. 'caption' => "Struktura tabeli {$tblName} [{$idTable}]",
  275. 'cols_label' => [
  276. 'sort' => UI::h('nobr', [
  277. 'class' => "ta-ordering" . ('sort' === $sortByCol ? " ta-ordering-" . ( 'asc' === $sortByDir ? 'asc' : 'desc' ) : '' ),
  278. 'onClick' => "return p5UI_table_sortBy_get(this, '{$sortByArgName}', 'sort', '" . ('sort' === $sortByCol ? ( 'asc' === $sortByDir ? 'desc' : 'asc' ) : 'asc' ) . "')",
  279. 'title' => "Sortuj wg pola SORT_PRIO z zasobów",
  280. ], "sort"),
  281. 'name' => UI::h('nobr', [
  282. 'class' => "ta-ordering" . ('name' === $sortByCol ? " ta-ordering-" . ( 'asc' === $sortByDir ? 'asc' : 'desc' ) : '' ),
  283. 'onClick' => "return p5UI_table_sortBy_get(this, '{$sortByArgName}', 'name', '" . ('name' === $sortByCol ? ( 'asc' === $sortByDir ? 'desc' : 'asc' ) : 'asc' ) . "')",
  284. 'title' => "Sortuj wg nazwy",
  285. ], "namespace"),
  286. ],
  287. 'cols' => array_keys($emptyItem),
  288. 'rows' => array_map(function ($item) use ($sortByCol) {
  289. if ('sort' === $sortByCol && null !== $item['sort'] && !empty($item['id_zasob'])) {
  290. $item['@class'] = "ta-sortable-item";
  291. $item['@class[sort]'] = "ta-sortable-item-handle";
  292. $item['@data']['sort_prio'] = $item['sort'];
  293. $item['@data']['id_zasob'] = $item['id_zasob'];
  294. $item['sort'] = ":: {$item['sort']}";
  295. }
  296. return $item;
  297. }, $tableList),
  298. ]);
  299. echo UI::h('script', [], "
  300. jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:click', function(e, n, payload) {
  301. console.log('event p5UIBtnAjax:Storage:addCellToZasoby:click', n, payload);
  302. });
  303. jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', function(e, n, payload) {
  304. console.log('event p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', n, payload);
  305. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  306. var cellUwagiJQNode = jQuery(n).parents('td').next('td');
  307. cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
  308. jQuery(n).parents('td').text(payload.body.id);
  309. jQuery(n).remove();
  310. }
  311. jQuery.notify(payload.msg, payload.type);
  312. });
  313. ");
  314. $ajaxAddZasobLink = Router::getRoute('Storage')->getLink('addGeomEtykietaCells', [ 'idStorage' => $idStorage, 'tblName' => $tblName]);
  315. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addGeomEtykietaCells', { href: '{$ajaxAddZasobLink}' })";
  316. UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj komórki etykiet", true);
  317. echo "<i>(<code>`etykieta_x`</code>, <code>`etykieta_y`</code>, <code>`etykieta_obrot`</code>)</i>";
  318. echo UI::h('script', [], "
  319. jQuery(document).on('p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', function(e, n, payload) {
  320. console.log('event p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', n, payload);
  321. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  322. var cellUwagiJQNode = jQuery(n).parents('td').next('td');
  323. cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
  324. jQuery(n).parents('td').text(payload.body.id);
  325. jQuery(n).remove();
  326. }
  327. jQuery.notify(payload.msg, payload.type);
  328. });
  329. ");
  330. $tableActions = array_filter($cellZasobList, function ($row) {
  331. return ('URL_ACTION' == $row['ZASOB_TYPE']);
  332. });
  333. UI::table([
  334. 'caption' => "tableActions",
  335. // 'cols' => array_keys($emptyItem),
  336. 'rows' => array_map(function ($item) {
  337. $sqlIdAction = DB::getPDO()->quote($item['ID'], PDO::PARAM_INT);
  338. $args = DB::getPDO()->fetchAll("
  339. select z.`DESC`
  340. , a.ID as ALIAS_ID, a.`DESC` as ALIAS_DESC, a.OPIS as ALIAS_OPIS
  341. from CRM_LISTA_ZASOBOW z
  342. left join CRM_LISTA_ZASOBOW a on(a.ID = z.ALIAS_ID)
  343. where z.PARENT_ID = {$sqlIdAction}
  344. and z.`TYPE` = 'PARAM_IN'
  345. ");
  346. $definitionArgs = DB::getPDO()->fetchAll("
  347. select p.ID, p.`DESC`
  348. from CRM_LISTA_ZASOBOW z
  349. join CRM_LISTA_ZASOBOW d on(d.ID = z.ALIAS_ID)
  350. left join CRM_LISTA_ZASOBOW p on(p.PARENT_ID = d.ID)
  351. where z.ID = {$sqlIdAction}
  352. and p.`TYPE` = 'PARAM_IN'
  353. ");
  354. $flatDefinitionArgs = implode(";", array_map(function ($arg) {
  355. return "{$arg['ID']}={$arg['DESC']}";
  356. }, $definitionArgs));
  357. return [
  358. 'label' => DB::getPDO()->fetchValue(" select z.OPIS from CRM_LISTA_ZASOBOW z where z.ID = {$sqlIdAction} ") . " " .
  359. UI::h('i', [
  360. 'class' => "glyphicon glyphicon-pencil",
  361. 'style' => "cursor:pointer",
  362. 'onClick' => "return Storage__tableStruct__editActionLabel(this, {$sqlIdAction})"], ''),
  363. 'args' => implode("<br>&", array_map(function ($item) {
  364. return (NULL === $item['ALIAS_ID'])
  365. ? $item['DESC']
  366. : "{$item['DESC']}=" . '{$row["' . $item['ALIAS_DESC'] . '"]}';// TODO: add rmParam btn
  367. }, $args)) . " " .
  368. UI::h('i', [
  369. 'class' => "glyphicon glyphicon-plus-sign",
  370. 'style' => "cursor:pointer",
  371. 'title' => "Dodaj PARAM_IN",
  372. 'onClick' => "return Storage__tableStruct__addParamAction(this, {$sqlIdAction}, '{$flatDefinitionArgs}')"], ''),
  373. // 'args_info' => '<pre>' . var_export($args, true) . '</pre>',
  374. 'ID' => $item['ID'],
  375. 'DESC' => $item['DESC'],
  376. 'A_STATUS' => $item['A_STATUS'],
  377. 'definition args' => implode("", array_map(function ($item) {
  378. return '<div style="white-space:nowrap">' . "[{$item['ID']}] {$item['DESC']}" . '</div>';
  379. }, $definitionArgs)),
  380. ];
  381. }, $tableActions)
  382. ]);
  383. echo UI::h('button', [
  384. 'onClick'=>"Storage__tableStruct__addAction()",
  385. 'class'=>"btn btn-xs btn-default"
  386. ], "Dodaj Akcję");
  387. echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
  388. echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
  389. echo UI::h('style', [], "
  390. .swal2-radio.p5-swal-radio-as-list { text-align:left }
  391. .swal2-radio.p5-swal-radio-as-list > label { display:block; margin-left:20px }
  392. ");
  393. UI::inlineJS(__FILE__ . '.tableActions.js', [
  394. 'ID_STORAGE' => $idStorage,
  395. 'TABLE_NAME' => $tblName,
  396. 'FETCH_URL' => Router::getRoute('Storage')->getLink('fetchActionListAjax'),
  397. 'ADD_ACTION_URL' => Router::getRoute('Storage')->getLink('addActionAjax')
  398. ]);
  399. echo '<hr>';
  400. $ajaxAddBaseProcesLink = Router::getRoute('Storage')->getLink('addTableBaseProces', [ 'idStorage' => $idStorage, 'tblName' => $tblName ]);
  401. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addTableBaseProces', { href: '{$ajaxAddBaseProcesLink}' })";
  402. UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj podstawowy proces dla tabeli '{$tblName}' - read only", true);
  403. echo UI::h('script', [], "
  404. jQuery(document).on('p5UIBtnAjax:Storage:addTableBaseProces:ajaxLoaded', function(e, n, payload) {
  405. jQuery.notify(payload.msg, payload.type);
  406. });
  407. ");
  408. if ('sort' === $sortByCol) {
  409. echo UI::h('script', [], "
  410. jQuery(document).ready(function (){
  411. var tblNode$ = jQuery('#struct_table > tbody')
  412. var getOrder = function () {
  413. var orderIds = []
  414. jQuery('#struct_table > tbody').children('.ta-sortable-item').each(function (idx, trNode) {
  415. orderIds.push(jQuery(trNode).data('id_zasob'))
  416. })
  417. return orderIds
  418. }
  419. var sortOrder = getOrder()
  420. console.log('sortOrder - init', sortOrder)
  421. tblNode$.sortable({
  422. axis: 'y',
  423. handle: '.ta-sortable-item-handle',
  424. items: '.ta-sortable-item',
  425. update: function (event, ui) {
  426. sortOrder = getOrder()
  427. tblNode$.sortable('disable')
  428. tblNode$.find('.ta-sortable-item-handle').css({color:'silver'})
  429. console.log('TODO: disable sortable while ajax')
  430. // window.setTimeout(function () {
  431. // tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  432. // console.log('TODO: ajax fetch result')
  433. // tblNode$.sortable('enable')
  434. // tblNode$.sortable('cancel')
  435. // }, 1000)
  436. window.fetch(
  437. URI(window.location.href)
  438. .setSearch('_task', 'updateAntAclSortAjax')
  439. .setSearch('idZasobOrder', sortOrder)
  440. .build().toString(),
  441. {
  442. method: 'POST',
  443. headers: {
  444. 'Content-Type': 'application/x-www-form-urlencoded' // query string
  445. },
  446. credentials: 'same-origin',
  447. body: JSON.stringify({
  448. namespace: URI.parseQuery(window.location.search).namespace,
  449. sortBy: '{$sortByCol}',
  450. sortByDir: '{$sortByDir}',
  451. sortOrder: sortOrder,
  452. })
  453. }
  454. ).then(function(response) {
  455. return response.json()
  456. }).then(function(payload) {
  457. console.log('updateAntAclSortAjax response', payload);
  458. tblNode$.sortable('enable')
  459. if ('success' !== payload.type) {
  460. tblNode$.sortable('cancel')
  461. }
  462. tblNode$.sortable('enable')
  463. tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  464. p5UI__notifyAjaxCallback({
  465. type: payload.type || 'error',
  466. msg: payload.msg || 'Request error'
  467. });
  468. if ('success' === payload.type) {
  469. window.location.reload(true)
  470. }
  471. }).catch(function(e) {
  472. tblNode$.sortable('enable')
  473. tblNode$.sortable('cancel')
  474. tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  475. p5UI__notifyAjaxCallback({
  476. type: 'error',
  477. msg: 'Request error ' + e
  478. });
  479. })
  480. }
  481. });
  482. });
  483. ");
  484. }
  485. }
  486. public function objectStructView($item) {
  487. $namespace = $item['namespace'];
  488. { // sortBy
  489. $sortByArgName = 'sortBy';
  490. $sortByCol = V::get($sortByArgName, 'namespace', $_GET);
  491. $sortByDir = V::get("{$sortByArgName}Dir", 'asc', $_GET);
  492. { // add SORT_PRIO
  493. $item['field'] = array_map(function ($field) {
  494. $field['SORT_PRIO'] = ($field['idZasob'] > 0)
  495. ? DB::getPDO()->fetchValue("
  496. select z.SORT_PRIO
  497. from CRM_LISTA_ZASOBOW z
  498. where z.ID = :id
  499. ", [ ':id' => $field['idZasob'] ])
  500. : null
  501. ;
  502. return $field;
  503. }, $item['field']);
  504. }
  505. if ('namespace' === $sortByCol) {
  506. usort($item['field'], function ($a, $b) use ($sortByDir) {
  507. if ($a['fieldNamespace'] > $b['fieldNamespace']) return 'asc' === $sortByDir ? 1 : -1;
  508. if ($a['fieldNamespace'] < $b['fieldNamespace']) return 'asc' === $sortByDir ? -1 : 1;
  509. return 0;
  510. });
  511. }
  512. else if ('sort' === $sortByCol) {
  513. usort($item['field'], function ($a, $b) use ($sortByDir) {
  514. if (null === $a['SORT_PRIO'] && null === $b['SORT_PRIO']) return 0;
  515. if (null === $a['SORT_PRIO'] && null != $b['SORT_PRIO']) return 1;
  516. if (null !== $a['SORT_PRIO'] && null === $b['SORT_PRIO']) return -1;
  517. if ($a['SORT_PRIO'] > $b['SORT_PRIO']) return 'asc' === $sortByDir ? 1 : -1;
  518. if ($a['SORT_PRIO'] < $b['SORT_PRIO']) return 'asc' === $sortByDir ? -1 : 1;
  519. return 0;
  520. });
  521. }
  522. echo UI::h('style', [ 'type' => "text/css" ], "
  523. .ta-ordering { cursor:pointer }
  524. .ta-ordering-desc:after { content:\"\\e252\"; font-family:\"Glyphicons Halflings\"; line-height:1; margin:0 0 0 3px; display:inline-block; color:#bbb }
  525. .ta-ordering-asc:after { content:\"\\e253\"; font-family:\"Glyphicons Halflings\"; line-height:1; margin:0 0 0 3px; display:inline-block; color:#bbb }
  526. .ta-sortable-item { }
  527. .ta-sortable-item-handle { cursor:pointer }
  528. ");
  529. echo UI::h('script', [ 'src' => "static/URI.js" ]);
  530. echo UI::h('script', [], "
  531. function p5UI_table_sortBy_get(n, argName, colName, dir) {
  532. var newUri = URI(window.location.href).setQuery(argName, colName).setQuery(argName+'Dir', dir).build().toString();
  533. window.location.href = newUri
  534. }
  535. ");
  536. }
  537. if ('setFieldRefConfig' === V::get('_postTask', '', $_POST)) {
  538. $field = V::get('field', '', $_POST);
  539. $source = V::get('source', '', $_POST);
  540. switch ($source) {
  541. case 'view':
  542. $refSelect = ACL::generateRefSelectSqlByFlatRelationCache($namespace, $field);
  543. ACL::setRefSource($namespace, $field, 'view', $refSelect);
  544. break;
  545. case 'table': ACL::setRefSource($namespace, $field, 'table'); break;
  546. }
  547. }
  548. if ('preview' === V::get('_postTask', '', $_POST)) {
  549. try {
  550. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  551. $localFields = array_filter($item['field'], function ($field) {
  552. return $field['isLocal'];
  553. });
  554. $refFields = array_filter($item['field'], function ($field) {
  555. return 'ref:' === substr($field['xsdType'], 0, 4);
  556. });
  557. $activeRefFields = array_filter($refFields, function ($field) {
  558. $refNamespace = str_replace(['__x3A__', ':'], '/', substr($field['xsdType'], strlen('ref:')));
  559. return (1 == DB::getPDO()->fetchValue("
  560. select t.isObjectActive
  561. from `CRM_#CACHE_ACL_OBJECT` t
  562. where t.`namespace` = '{$refNamespace}'
  563. "));
  564. });
  565. $previewItems = ACL::getAclByNamespace($namespace)->buildQuery([])->getItems([
  566. 'limit' => 5
  567. ]);
  568. DBG::nicePrint($previewItems, 'items (default query) - preview (limit 5)');
  569. $query = [ 'cols' => array_merge(
  570. array_map(
  571. function ($field) {
  572. return $field['fieldNamespace'];
  573. }, $localFields
  574. ),
  575. array_map(
  576. function ($field) {
  577. return "{$field['fieldNamespace']}/*";
  578. }, $activeRefFields
  579. )
  580. ) ];
  581. DBG::nicePrint($query, 'items with ref/* - query');
  582. $previewItems = ACL::getAclByNamespace($namespace)->buildQuery($query)->getItems([
  583. 'limit' => 5
  584. ]);
  585. DBG::nicePrint($previewItems, 'items with ref/* - preview (limit 5)');
  586. $query = [ 'cols' => array_merge(
  587. array_map(
  588. function ($field) {
  589. return $field['fieldNamespace'];
  590. }, $localFields
  591. ),
  592. array_map(
  593. function ($field) {
  594. return "{$field['fieldNamespace']}";
  595. }, $activeRefFields
  596. )
  597. ) ];
  598. DBG::nicePrint($query, 'items with ref as xlink - query');
  599. $previewItems = ACL::getAclByNamespace($namespace)->buildQuery($query)->getItems([
  600. 'limit' => 5
  601. ]);
  602. DBG::nicePrint($previewItems, 'items with ref as xlink - preview (limit 5)');
  603. } catch (Exception $e) {
  604. DBG::log($e);
  605. UI::alert('danger', $e->getMessage());
  606. }
  607. }
  608. echo UI::h('div', ['style'=>"margin-bottom:24px; padding:0 10px; background-color:#eee", 'open' => "open"], [
  609. UI::h('div', [], [
  610. UI::h('a', [
  611. 'class' => "btn btn-link",
  612. 'href' => Router::getRoute('Storage')->getLink('tableList', [ 'idStorage' => 36 ]),
  613. ], "&laquo wróć do listy"),
  614. " ",
  615. UI::h('b', [ 'style' => "font-size:1.1em; line-height:2em" ], "Struktura obiektu '{$namespace}'"),
  616. // UI::h('small', ['style'=>"font-size:0.8em; font-style:italic; color:#aaa"], " więcej...")
  617. ]),
  618. UI::h('div', ['style'=>"padding:4px 24px; border-top:1px solid #fff"], [
  619. UI::h('span', ['style'=>"margin-right:12px"], [
  620. ( ($item['idZasob'] > 0)
  621. ? UI::h('span', [ 'title' => "Nr zasobu '{$item['idZasob']}'" ], "Nr zasobu [{$item['idZasob']}]")
  622. : UI::h('span', [ 'title' => "Brak nr zasobu - dodaj do zasobów" ], [
  623. UI::hButtonAjax("+ do zasobów", 'addAclObjectToZasobyAjax', [
  624. 'class' => "btn btn-xs btn-primary",
  625. 'href' => Router::getRoute('Storage')->getLink('addAclObjectToZasobyAjax'),
  626. 'data' => [
  627. 'idStorage' => $item['idDatabase'],
  628. 'namespace' => $item['namespace'],
  629. ]
  630. ])
  631. ])
  632. ),
  633. ]),
  634. UI::h('span', ['style'=>"margin:0 12px"], [
  635. ( ($item['isObjectActive'] > 0)
  636. ? UI::h('span', [ 'class' => "label label-success", 'title' => "Namespace active" ], "Active")
  637. : UI::h('span', [ 'title' => "Namespace not active" ], [
  638. ($item['idZasob'] > 0)
  639. ? UI::hButtonAjax("Aktywuj", 'activateObjectAjax', [
  640. 'class' => "btn btn-xs btn-primary",
  641. 'href' => Router::getRoute('Storage')->getLink('activateObjectAjax'),
  642. 'data' => [
  643. 'namespace' => $item['namespace'],
  644. ]
  645. ])
  646. : '',
  647. ])
  648. ),
  649. ]),
  650. UI::h('a', [
  651. 'href' => "index.php?_route=ViewTableAjax&namespace={$item['namespace']}",
  652. 'class' => "btn btn-sm btn-link"
  653. ], "Przeglądaj tabelę"),
  654. ( ($item['idZasob'] > 0)
  655. ? UI::h('a', [
  656. 'href' => "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$item['idZasob']}&filtr_ids=%2B&filtr_ob=%2B",
  657. 'class' => "btn btn-sm btn-link",
  658. 'title' => "Struktura tabeli w drzewie zasobów"
  659. ], "Zasoby")
  660. : ''
  661. ),
  662. ( ($item['idZasob'] > 0)
  663. ? UI::h('a', [
  664. 'href' => "index.php?FUNCTION_INIT=PROCES_MENU&HEADER_NOT_INIT=YES&_task=PROCES_FOR_TABLE&tblId={$item['idZasob']}",
  665. 'class' => "btn btn-sm btn-link",
  666. 'title' => "Procesy dla aktualnie przeglądanej tabeli"
  667. ], "Procesy")
  668. : ''
  669. ),
  670. UI::h('a', [
  671. 'href' => Router::getRoute('Storage_AclReinstall')->getLink('', ['namespace' => $item['namespace']]),
  672. 'class' => 'btn btn-sm btn-link', 'style' => "color:#f00",
  673. 'title' => "Zainstaluje ponownie obiekt"
  674. ], "reinstall object"),
  675. UI::h('a', [
  676. 'href' => Router::getRoute('Storage_AclUsage')->getLink('', [ 'namespace' => $item['namespace'] ]),
  677. 'class' => "btn btn-sm btn-link",
  678. 'title' => "Uprawnienia - analiza użycia komórek w procesach"
  679. ], "Uprawnienia (analiza użycia)"),
  680. UI::h('a', [
  681. 'href' => Router::getRoute('WfsJsRequestPanel')->getLink('', [ 'namespace' => $item['namespace'] ]),
  682. 'class' => "btn btn-sm btn-link",
  683. 'title' => "JavaScript WFS Panel"
  684. ], "JavaScript WFS Panel"),
  685. UI::hButtonPost("(podgląd z relacjami)", [
  686. 'data' => [
  687. '_postTask' => 'preview'
  688. ],
  689. 'class' => 'btn btn-sm btn-link', 'style' => "font-style:italic",
  690. 'title' => "Podgląd kilku ostatnich obiektów wraz z relacjami"
  691. ]),
  692. ])
  693. ]);
  694. $thisGetLink = [ $this, 'getLink' ];
  695. { // not installed ref
  696. $refFields = array_filter($item['field'], function ($field) {
  697. return ('ref:' === substr($field['xsdType'], 0, 4) && $field['isActive']);
  698. });
  699. echo UI::h('h3', [], "Obiekty powiązane");
  700. UI::table([
  701. 'rows' => array_map(function ($backRef) use ($thisGetLink) {
  702. $refNamespace = $backRef['namespace'];
  703. $isInstalled = (1 == DB::getPDO()->fetchValue("
  704. select t.isObjectActive
  705. from `CRM_#CACHE_ACL_OBJECT` t
  706. where t.`namespace` = '{$refNamespace}'
  707. "));
  708. return [
  709. 'back ref namespace' => UI::h('a', [
  710. 'class' => "btn btn-xs btn-link",
  711. 'href' => $thisGetLink('', [ 'namespace' => $refNamespace ])
  712. ], "{$refNamespace}"),
  713. // 'idInstance' => $backRef['idInstance'],
  714. // 'isInstalled' => $isInstalled,
  715. '@class' => ($isInstalled) ? "success" : "danger",
  716. ];
  717. }, ACL::getBackRefList($item['namespace'])),
  718. ]);
  719. UI::table([
  720. 'rows' => array_map(function ($field) use ($thisGetLink) {
  721. $refNamespace = str_replace(['__x3A__', ':'], '/', substr($field['xsdType'], strlen('ref:')));
  722. $isInstalled = (1 == DB::getPDO()->fetchValue("
  723. select t.isObjectActive
  724. from `CRM_#CACHE_ACL_OBJECT` t
  725. where t.`namespace` = '{$refNamespace}'
  726. "));
  727. $refSource = null;
  728. if ($isInstalled) {
  729. try {
  730. $refTable = ACL::getRefTable($field['objectNamespace'], $field['fieldNamespace']);
  731. DBG::log($refTable, 'array', "getRefTable('{$field['objectNamespace']}', '{$field['fieldNamespace']}')");
  732. $refSource = ACL::getRefSource($field['objectNamespace'], $field['fieldNamespace']);
  733. DBG::log($refSource, 'array', "ACL::getRefSource('{$field['objectNamespace']}', '{$field['fieldNamespace']}')");
  734. } catch (Exception $e) {
  735. DBG::log($e);
  736. }
  737. }
  738. return [
  739. 'child ref name' => $field['fieldNamespace'],
  740. // 'xsdType' => $field['xsdType'], // always === "ref:{$field['fieldNamespace']}"
  741. 'ref object' => UI::h('a', [
  742. 'class' => "btn btn-xs btn-link",
  743. 'href' => $thisGetLink('', [ 'namespace' => $refNamespace ])
  744. ], "{$refNamespace}"),
  745. 'ref source' => UI::h('div', [],
  746. (null === $refSource)
  747. ? [ "ref object not installed" ] // TODO: link to install? is table struct
  748. : [
  749. // UI::hButtonAjax("Tabela ref", "setFieldRefConfig", [
  750. // 'class' => "btn btn-xs btn-default" . ( 'table' === $refSource ? ' disabled' : '' ),
  751. // 'href' => $thisGetLink('setFieldRefConfig'),
  752. // 'data' => [ 'namespace' => $refNamespace, 'field' => $field['fieldNamespace'], 'do' => 'table' ]
  753. // ]),
  754. // UI::hButtonAjax("Widok (cache)", "setFieldRefConfig", [
  755. // 'title' => "Według flat_relation_cache",
  756. // 'class' => "btn btn-xs btn-default" . ( 'view' === $refSource ? ' disabled' : '' ),
  757. // 'href' => $thisGetLink('setFieldRefConfig'),
  758. // 'data' => [ 'namespace' => $refNamespace, 'field' => $field['fieldNamespace'], 'do' => 'view' ]
  759. // ]),
  760. UI::hButtonPost("Tabela ref", [
  761. 'title' => "Według wygenerowanej tabeli REF",
  762. 'class' => "btn btn-xs btn-default" . ( 'table' === $refSource ? ' disabled' : '' ),
  763. // 'href' => $thisGetLink('setFieldRefConfig'),
  764. 'data' => [ 'namespace' => $refNamespace, 'field' => $field['fieldNamespace'], '_postTask' => 'setFieldRefConfig', 'source' => 'table' ]
  765. ]),
  766. UI::hButtonPost("Widok (cache)", [
  767. 'title' => "Według flat_relation_cache",
  768. 'class' => "btn btn-xs btn-default" . ( 'view' === $refSource ? ' disabled' : '' ),
  769. // 'href' => $thisGetLink('setFieldRefConfig'),
  770. 'data' => [ 'namespace' => $refNamespace, 'field' => $field['fieldNamespace'], '_postTask' => 'setFieldRefConfig', 'source' => 'view' ]
  771. ]),
  772. ]
  773. ),
  774. '@class' => ($isInstalled) ? "success" : "danger",
  775. ]; // TODO: link to install object
  776. }, $refFields)
  777. ]);
  778. }
  779. $thisGetLink = [ $this, 'getLink' ];
  780. UI::table([
  781. '__html_id' => 'struct_table',
  782. 'caption' => UI::h('span', [], [
  783. UI::h('span', [ 'style' => "margin-right:6px;color:#000" ], "Struktura obiektu '{$item['namespace']}'"),
  784. ]),
  785. // 'sortBy' => [
  786. // 'method' => 'get',
  787. // 'argName' => '_sortBy',
  788. // 'allow' => ['sort', 'namespace'],
  789. // 'default' => ['namespace', 'asc'],
  790. // ],
  791. 'cols_label' => [
  792. 'sort' => UI::h('nobr', [
  793. 'class' => "ta-ordering" . ('sort' === $sortByCol ? " ta-ordering-" . ( 'asc' === $sortByDir ? 'asc' : 'desc' ) : '' ),
  794. 'onClick' => "return p5UI_table_sortBy_get(this, '{$sortByArgName}', 'sort', '" . ('sort' === $sortByCol ? ( 'asc' === $sortByDir ? 'desc' : 'asc' ) : 'asc' ) . "')",
  795. 'title' => "Sortuj wg pola SORT_PRIO z zasobów",
  796. ], "sort"),
  797. 'namespace' => UI::h('nobr', [
  798. 'class' => "ta-ordering" . ('namespace' === $sortByCol ? " ta-ordering-" . ( 'asc' === $sortByDir ? 'asc' : 'desc' ) : '' ),
  799. 'onClick' => "return p5UI_table_sortBy_get(this, '{$sortByArgName}', 'namespace', '" . ('namespace' === $sortByCol ? ( 'asc' === $sortByDir ? 'desc' : 'asc' ) : 'asc' ) . "')",
  800. 'title' => "Sortuj wg nazwy pola",
  801. ], "namespace"),
  802. ],
  803. 'rows' => array_map(function ($field) use ($item, $thisGetLink, $sortByCol) {
  804. $tblItem = [];
  805. if ('sort' === $sortByCol && null !== $field['SORT_PRIO'] && !empty($field['idZasob'])) {
  806. $tblItem['@class'] = "ta-sortable-item";
  807. $tblItem['@class[sort]'] = "ta-sortable-item-handle";
  808. $tblItem['@data']['sort_prio'] = $field['SORT_PRIO'];
  809. $tblItem['@data']['id_zasob'] = $field['idZasob'];
  810. $field['SORT_PRIO'] = ":: {$field['SORT_PRIO']}";
  811. }
  812. $tblItem['sort'] = V::get('SORT_PRIO', null, $field);
  813. foreach ($field as $k => $v) {
  814. if ('SORT_PRIO' === $k) continue;
  815. $tblItem[$k] = $v;
  816. }
  817. $tblItem['namespace'] = UI::h('span', [], [
  818. UI::h('span', ['style' => "color:#aaa"], substr($field['namespace'], 0, strlen($field['objectNamespace']) + 1)),
  819. UI::h('span', ['style' => "color:#000"], substr($field['namespace'], strlen($field['objectNamespace']) + 1)),
  820. ]);
  821. $tblItem['idZasob'] = ($field['idZasob'] > 0)
  822. ? $field['idZasob']
  823. : (
  824. ($item['idZasob'] > 0)
  825. ? UI::hButtonAjax("+ do zasobów", 'addFieldToZasobyAjax', [
  826. 'class' => "btn btn-xs btn-primary",
  827. 'href' => $thisGetLink('addFieldToZasobyAjax'),
  828. 'data' => [
  829. 'namespace' => $item['namespace'],
  830. 'fieldNamespace' => $field['namespace'],
  831. ]
  832. ])
  833. : UI::h('span', ['title'=>"Brak Nr zasobu dla obiektu", 'class'=>"btn btn-xs btn-danger"], "Brak nr zasobu obiektu")
  834. )
  835. ;
  836. unset($tblItem['objectNamespace']);
  837. unset($tblItem['fieldNamespace']);
  838. return $tblItem;
  839. }, array_filter($item['field'], function ($field) { return $field['isActive']; }))
  840. ]);
  841. $removedFields = array_filter($item['field'], function ($field) { return !$field['isActive']; });
  842. if (!empty($removedFields)) {
  843. echo UI::h('details', [ 'style' => "margin-bottom:12px; padding:6px; background-color:#dedede; color:#000" ], [
  844. UI::h('summary', [ 'style' => "padding:0 3px; outline:none; cursor:pointer" ], "Pola w koszu (".count($removedFields).")"),
  845. UI::h('table', [ 'style' => "margin:6px 0 0 0; background-color:#fff; font-size:x-small", 'class' => "table table-bordered table-hover table-condensed" ], [
  846. UI::h('thead', [], [
  847. UI::h('tr', [], [
  848. UI::h('th', [], "#"),
  849. UI::h('th', [], "namespace"),
  850. UI::h('th', [], "xsdType"),
  851. UI::h('th', [], "xsdRestrictions"),
  852. UI::h('th', [], "appInfo"),
  853. UI::h('th', [], "minOccurs"),
  854. UI::h('th', [], "maxOccurs"),
  855. UI::h('th', [], "isActive"),
  856. ]),
  857. ]),
  858. UI::h('tbody', [], array_map(function ($field) use ($item, $thisGetLink) {
  859. return UI::h('tr', [], [
  860. UI::h('td', [], [
  861. UI::hButtonAjax("usuń", 'removeFieldFromTrashAjax', [
  862. 'class' => "btn btn-xs btn-danger",
  863. 'href' => $thisGetLink('removeFieldFromTrashAjax'),
  864. 'data' => [
  865. 'namespace' => $item['namespace'],
  866. 'fieldNamespace' => $field['namespace'],
  867. ]
  868. ])
  869. ]),
  870. UI::h('td', [], $field['fieldNamespace']),
  871. UI::h('td', [], $field['xsdType']),
  872. UI::h('td', [], $field['xsdRestrictions']),
  873. UI::h('td', [], $field['appInfo']),
  874. UI::h('td', [], $field['minOccurs']),
  875. UI::h('td', [], $field['maxOccurs']),
  876. UI::h('td', [], $field['isActive']),
  877. ]);
  878. }, $removedFields)),
  879. ]),
  880. ]);
  881. }
  882. UI::hButtonAjaxOnResponse('removeFieldFromTrashAjax', /* payload, n */ "
  883. if (!payload.type) return false
  884. jQuery.notify(payload.msg, payload.type)
  885. if ('success' == payload.type) {
  886. var trJqNode = jQuery(n).closest('tr')
  887. var tbodyJqNode = trJqNode.parent()
  888. var detailsJqNode = trJqNode.closest('details')
  889. trJqNode.remove()
  890. if (!tbodyJqNode.children().length) {
  891. detailsJqNode.remove()
  892. }
  893. }
  894. ");
  895. UI::hButtonAjaxOnResponse('addFieldToZasobyAjax', /* payload, n */ "
  896. if (!payload.type) return false
  897. if (payload.body && payload.body.id && payload.body.id > 0) { // if ('success' == payload.type) {
  898. n.parentNode.replaceChild(document.createTextNode(payload.body.id), n)
  899. }
  900. jQuery.notify(payload.msg, payload.type)
  901. ");
  902. UI::hButtonAjaxOnResponse('addAclObjectToZasobyAjax', /* payload, n */ "
  903. if (!payload.type) return false
  904. if ('success' === payload.type || 'info' === payload.type) {
  905. if (payload.body && payload.body.id && payload.body.id > 0) {
  906. n.parentNode.replaceChild(document.createTextNode(payload.body.id), n)
  907. } else {
  908. console.log('TODO: addAclObjectToZasobyAjax unknown response', payload);
  909. }
  910. window.location.reload()
  911. }
  912. ");
  913. UI::hButtonAjaxOnResponse('activateObjectAjax', /* payload, n */ "
  914. jQuery.notify(payload.msg, payload.type)
  915. if (!payload.type) return false
  916. if ('success' === payload.type || 'info' === payload.type) {
  917. if (payload.body && payload.body.isObjectActive && payload.body.isObjectActive > 0) {
  918. n.parentNode.replaceChild(document.createTextNode('Active'), n)
  919. } else {
  920. console.log('TODO: activateObjectAjax unknown response', payload);
  921. }
  922. }
  923. ");
  924. if ('sort' === $sortByCol) {
  925. echo UI::h('script', [], "
  926. jQuery(document).ready(function (){
  927. var tblNode$ = jQuery('#struct_table > tbody')
  928. var getOrder = function () {
  929. var orderIds = []
  930. jQuery('#struct_table > tbody').children('.ta-sortable-item').each(function (idx, trNode) {
  931. orderIds.push(jQuery(trNode).data('id_zasob'))
  932. })
  933. return orderIds
  934. }
  935. var sortOrder = getOrder()
  936. console.log('sortOrder - init', sortOrder)
  937. tblNode$.sortable({
  938. axis: 'y',
  939. handle: '.ta-sortable-item-handle',
  940. items: '.ta-sortable-item',
  941. update: function (event, ui) {
  942. sortOrder = getOrder()
  943. tblNode$.sortable('disable')
  944. tblNode$.find('.ta-sortable-item-handle').css({color:'silver'})
  945. console.log('TODO: disable sortable while ajax')
  946. // window.setTimeout(function () {
  947. // tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  948. // console.log('TODO: ajax fetch result')
  949. // tblNode$.sortable('enable')
  950. // tblNode$.sortable('cancel')
  951. // }, 1000)
  952. window.fetch(
  953. URI(window.location.href)
  954. .setSearch('_task', 'updateAntAclSortAjax')
  955. .setSearch('idZasobOrder', sortOrder)
  956. .build().toString(),
  957. {
  958. method: 'POST',
  959. headers: {
  960. 'Content-Type': 'application/x-www-form-urlencoded' // query string
  961. },
  962. credentials: 'same-origin',
  963. body: JSON.stringify({
  964. namespace: URI.parseQuery(window.location.search).namespace,
  965. sortBy: '{$sortByCol}',
  966. sortByDir: '{$sortByDir}',
  967. sortOrder: sortOrder,
  968. })
  969. }
  970. ).then(function(response) {
  971. return response.json()
  972. }).then(function(payload) {
  973. console.log('updateAntAclSortAjax response', payload);
  974. tblNode$.sortable('enable')
  975. if ('success' !== payload.type) {
  976. tblNode$.sortable('cancel')
  977. }
  978. tblNode$.sortable('enable')
  979. tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  980. p5UI__notifyAjaxCallback({
  981. type: payload.type || 'error',
  982. msg: payload.msg || 'Request error'
  983. });
  984. if ('success' === payload.type) {
  985. window.location.reload(true)
  986. }
  987. }).catch(function(e) {
  988. tblNode$.sortable('enable')
  989. tblNode$.sortable('cancel')
  990. tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  991. p5UI__notifyAjaxCallback({
  992. type: 'error',
  993. msg: 'Request error ' + e
  994. });
  995. })
  996. }
  997. });
  998. });
  999. ");
  1000. }
  1001. if ($item['isObjectActive']) {
  1002. echo UI::hButtonAjax("Dodaj podstawowy proces dla obiektu '{$item['namespace']}' - read only (TODO)", 'addObjectBaseProcesAjax', [
  1003. 'class' => "btn btn-xs btn-default",
  1004. 'href' => Router::getRoute('Storage')->getLink('addObjectBaseProcesAjax'),
  1005. 'data' => [ 'namespace' => $item['namespace'] ]
  1006. ]);
  1007. UI::hButtonAjaxOnResponse('addObjectBaseProcesAjax', /* payload, n */ "
  1008. jQuery.notify(payload.msg, payload.type)
  1009. ");
  1010. }
  1011. DBG::nicePrint($item, '$item');
  1012. }
  1013. public function updateAntAclSortAjaxAction() {
  1014. return Response::sendTryCatchJson(array($this, 'updateAntAclSortAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  1015. }
  1016. public function updateAntAclSortAjax($args) {
  1017. DBG::log($args, 'array', "args");
  1018. $namespace = V::get('namespace', '', $args);
  1019. if (empty($namespace)) throw new Exception("Missing param namespace");
  1020. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  1021. DBG::log($item, 'array', "\$item");
  1022. $sortByArgName = 'sortBy';
  1023. $sortByCol = V::get($sortByArgName, 'namespace', $args);
  1024. $sortByDir = V::get("{$sortByArgName}Dir", 'asc', $args);
  1025. if ('sort' !== $sortByCol) throw new Exception("Only sort by SORT_PRIO allowed to update");
  1026. if (!in_array($sortByDir, ['asc', 'desc'])) throw new Exception("Wrong order by dir arg");
  1027. if ('asc' !== $sortByDir) throw new Exception("Only sort asc is allowed"); // DBG
  1028. $sortPrioIdsFromZasoby = DB::getPDO()->fetchAll("
  1029. select z.ID, z.SORT_PRIO
  1030. from CRM_LISTA_ZASOBOW z
  1031. where z.PARENT_ID = :p_id
  1032. order by z.SORT_PRIO asc, z.ID asc -- default order in Zasoby tree
  1033. ", [
  1034. ':p_id' => $item['idZasob']
  1035. ]);
  1036. DBG::log($sortPrioIdsFromZasoby, 'array', "\$sortPrioIdsFromZasoby");
  1037. $idZasobCurrentOrder = array_map(function ($orderRow) {
  1038. return (int)$orderRow['ID'];
  1039. }, $sortPrioIdsFromZasoby);
  1040. DBG::log($idZasobCurrentOrder, 'array', "\$idZasobCurrentOrder");
  1041. DBG::log(array_diff_assoc($args['sortOrder'], $idZasobCurrentOrder), 'array', "array_diff_assoc(\$args['sortOrder'], \$idZasobCurrentOrder)");
  1042. DBG::log(array_diff_assoc($idZasobCurrentOrder, $args['sortOrder']), 'array', "array_diff_assoc(\$idZasobCurrentOrder, \$args['sortOrder'])");
  1043. $orderDiff = array_diff_assoc($args['sortOrder'], $idZasobCurrentOrder);
  1044. foreach ($orderDiff as $sortPrio => $idZasob) {
  1045. DB::getPDO()->update('CRM_LISTA_ZASOBOW', 'ID', $idZasob, [
  1046. 'SORT_PRIO' => $sortPrio,
  1047. ]);
  1048. }
  1049. return [
  1050. 'type' => 'success',
  1051. 'msg' => "OK",
  1052. 'DBG__args' => $args
  1053. ];
  1054. }
  1055. public function removeFieldFromTrashAjaxAction() {
  1056. DBG::log($_REQUEST, 'array', '$_REQUEST');
  1057. Response::sendTryCatchJson(array($this, 'removeFieldFromTrashAjax'), $_REQUEST);
  1058. }
  1059. public function removeFieldFromTrashAjax($args) {
  1060. $namespace = V::get('namespace', '', $args);
  1061. if (empty($namespace)) throw new HttpException("Missing namespace");
  1062. $fieldNamespace = V::get('fieldNamespace', '', $args);
  1063. if (empty($fieldNamespace)) throw new HttpException("Missing fieldNamespace");
  1064. $fieldItem = SchemaFactory::loadDefaultObject('SystemObjectField')->getItem($fieldNamespace);
  1065. if (!$fieldItem) throw new HttpException("Field not found '{$fieldNamespace}'", 404);
  1066. DBG::log($fieldItem, 'array', "\$fieldItem");
  1067. switch ($fieldItem['xsdType']) {
  1068. case 'p5:enum': throw new Exception("TODO: remove enum values first"); break; // CRM_#CACHE_ACL_OBJECT_FIELD_enum
  1069. default: {
  1070. if ('ref:' === substr($fieldItem['xsdType'], 0, 4)) { // OK, remove
  1071. } else throw new Exception("TODO: remove xsdType: {$fieldItem['xsdType']}");
  1072. }
  1073. }
  1074. DB::getPDO()->execSql("
  1075. DELETE from `CRM_#CACHE_ACL_OBJECT_FIELD`
  1076. where namespace = :namespace
  1077. and objectNamespace = :objectNamespace
  1078. and _rootTableName = :rootTableName
  1079. and isActive = 0
  1080. limit 1
  1081. ", [
  1082. 'namespace' => $fieldItem['namespace'],
  1083. 'objectNamespace' => $fieldItem['objectNamespace'],
  1084. 'rootTableName' => $fieldItem['_rootTableName'],
  1085. ]);
  1086. return [
  1087. 'type' => "success",
  1088. 'msg' => "Usunięto pole {$fieldItem['fieldNamespace']}",
  1089. ];
  1090. }
  1091. public function addFieldToZasobyAjaxAction() {
  1092. DBG::log($_REQUEST, 'array', '$_REQUEST');
  1093. Response::sendTryCatchJson(array($this, 'addFieldToZasobyAjax'), $_REQUEST);
  1094. }
  1095. public function addFieldToZasobyAjax($args) {
  1096. $namespace = V::get('namespace', '', $args);
  1097. if (empty($namespace)) throw new HttpException("Missing namespace");
  1098. $fieldNamespace = V::get('fieldNamespace', '', $args);
  1099. if (empty($fieldNamespace)) throw new HttpException("Missing fieldNamespace");
  1100. $fieldItem = SchemaFactory::loadDefaultObject('SystemObjectField')->getItem($fieldNamespace);
  1101. if (!$fieldItem) throw new HttpException("Field not found '{$fieldNamespace}'", 404);
  1102. DBG::log($fieldItem, 'array', "\$fieldItem");
  1103. if ($fieldItem['idZasob'] > 0) throw (new AlertSuccessException("Field already added to Zasoby '{$fieldItem['idZasob']}'"))->setBody([ 'id' => $fieldItem['idZasob'] ]);
  1104. $objectItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace);
  1105. if (!$objectItem) throw new HttpException("Object not found '{$namespace}'", 404);
  1106. DBG::log($objectItem, 'array', "\$objectItem");
  1107. if (!$objectItem['idZasob']) throw new Exception("Missing Object idZasob");
  1108. $zasobItem = DB::getPDO()->fetchFirst("
  1109. select zField.ID, zField.`DESC`, zField.`TYPE`, zField.PARENT_ID
  1110. from CRM_LISTA_ZASOBOW as zField
  1111. join CRM_LISTA_ZASOBOW as zTable on(zTable.ID = zField.PARENT_ID)
  1112. where zTable.`ID` = '{$objectItem['idZasob']}'
  1113. and zTable.`TYPE` = 'TABELA'
  1114. and zField.`DESC` = '{$fieldItem['fieldNamespace']}'
  1115. and zField.`TYPE` = 'KOMORKA'
  1116. ");
  1117. if ($zasobItem) {
  1118. SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
  1119. 'namespace' => $fieldItem['namespace'],
  1120. 'idZasob' => $zasobItem['ID']
  1121. ]);
  1122. throw (new AlertSuccessException("Zasob już istnieje"))->setBody([ 'id' => $zasobItem['ID'] ]);
  1123. }
  1124. $newFieldItem = [
  1125. 'PARENT_ID' => $objectItem['idZasob'],
  1126. 'TYPE' => 'KOMORKA',
  1127. 'DESC' => $fieldItem['fieldNamespace'],
  1128. 'DESC_PL' => $fieldItem['fieldNamespace'],
  1129. ];
  1130. DBG::log($newFieldItem, 'array', "add new field item");
  1131. try {
  1132. $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
  1133. } catch (Exception $e) {
  1134. throw new Exception("Brak dostępu do tabeli Zasoby");
  1135. }
  1136. $createdId = $acl->addItem($newFieldItem);
  1137. if (!$createdId) throw new Exception("Nie udało się utworzyć nowego rekordu!");
  1138. SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
  1139. 'namespace' => $fieldItem['namespace'],
  1140. 'idZasob' => $createdId
  1141. ]);
  1142. throw (new AlertSuccessException("Utworzono pomyślnie rekord nr {$createdId}"))->setBody([ 'id' => $createdId ]);
  1143. }
  1144. }