AclStruct.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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. $childTypeName = V::get('field', '', $_POST);
  539. $source = V::get('source', '', $_POST);
  540. $toUpdateField = array_filter($item['field'], function ($field) use ($childTypeName) { return ($childTypeName === $field['fieldNamespace']); });
  541. $toUpdateField = (!empty($toUpdateField)) ? reset($toUpdateField) : null;
  542. if (!$toUpdateField) throw new Exception("Field not found '{$childTypeName}'");
  543. $typeField = Type_Field::build($toUpdateField);
  544. $refConfig = RefConfig::fetch($objectNamespace, $childTypeName);
  545. switch ($source) {
  546. case 'view': RefConfig::installRefView($objectNamespace, $childTypeName, $typeField, $refConfig); break;
  547. case 'table': RefConfig::installRefTable($objectNamespace, $childTypeName, $typeField, $refConfig); break;
  548. }
  549. }
  550. if ('preview' === V::get('_postTask', '', $_POST)) {
  551. try {
  552. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  553. $localFields = array_filter($item['field'], function ($field) {
  554. return $field['isLocal'];
  555. });
  556. $refFields = array_filter($item['field'], function ($field) {
  557. return 'ref:' === substr($field['xsdType'], 0, 4);
  558. });
  559. $activeRefFields = array_filter($refFields, function ($field) {
  560. $refNamespace = str_replace(['__x3A__', ':'], '/', substr($field['xsdType'], strlen('ref:')));
  561. return (1 == DB::getPDO()->fetchValue("
  562. select t.isObjectActive
  563. from `CRM_#CACHE_ACL_OBJECT` t
  564. where t.`namespace` = '{$refNamespace}'
  565. "));
  566. });
  567. $previewItems = ACL::getAclByNamespace($namespace)->buildQuery([])->getItems([
  568. 'limit' => 5
  569. ]);
  570. DBG::nicePrint($previewItems, 'items (default query) - preview (limit 5)');
  571. $query = [ 'cols' => array_merge(
  572. array_map(
  573. function ($field) {
  574. return $field['fieldNamespace'];
  575. }, $localFields
  576. ),
  577. array_map(
  578. function ($field) {
  579. return "{$field['fieldNamespace']}/*";
  580. }, $activeRefFields
  581. )
  582. ) ];
  583. DBG::nicePrint($query, 'items with ref/* - query');
  584. $previewItems = ACL::getAclByNamespace($namespace)->buildQuery($query)->getItems([
  585. 'limit' => 5
  586. ]);
  587. DBG::nicePrint($previewItems, 'items with ref/* - preview (limit 5)');
  588. $query = [ 'cols' => array_merge(
  589. array_map(
  590. function ($field) {
  591. return $field['fieldNamespace'];
  592. }, $localFields
  593. ),
  594. array_map(
  595. function ($field) {
  596. return "{$field['fieldNamespace']}";
  597. }, $activeRefFields
  598. )
  599. ) ];
  600. DBG::nicePrint($query, 'items with ref as xlink - query');
  601. $previewItems = ACL::getAclByNamespace($namespace)->buildQuery($query)->getItems([
  602. 'limit' => 5
  603. ]);
  604. DBG::nicePrint($previewItems, 'items with ref as xlink - preview (limit 5)');
  605. } catch (Exception $e) {
  606. DBG::log($e);
  607. UI::alert('danger', $e->getMessage());
  608. }
  609. }
  610. echo UI::h('div', ['style'=>"margin-bottom:24px; padding:0 10px; background-color:#eee", 'open' => "open"], [
  611. UI::h('div', [], [
  612. UI::h('a', [
  613. 'class' => "btn btn-link",
  614. 'href' => Router::getRoute('Storage')->getLink('tableList', [ 'idStorage' => $item['idDatabase'] ]),
  615. ], "&laquo wróć do listy"),
  616. " ",
  617. UI::h('b', [ 'style' => "font-size:1.1em; line-height:2em" ], "Struktura obiektu '{$namespace}'"),
  618. // UI::h('small', ['style'=>"font-size:0.8em; font-style:italic; color:#aaa"], " więcej...")
  619. ]),
  620. UI::h('div', ['style'=>"padding:4px 24px; border-top:1px solid #fff"], [
  621. UI::h('span', ['style'=>"margin-right:12px"], [
  622. ( ($item['idZasob'] > 0)
  623. ? UI::h('span', [ 'title' => "Nr zasobu '{$item['idZasob']}'" ], "Nr zasobu [{$item['idZasob']}]")
  624. : UI::h('span', [ 'title' => "Brak nr zasobu - dodaj do zasobów" ], [
  625. UI::hButtonAjax("+ do zasobów", 'addAclObjectToZasobyAjax', [
  626. 'class' => "btn btn-xs btn-primary",
  627. 'href' => Router::getRoute('Storage')->getLink('addAclObjectToZasobyAjax'),
  628. 'data' => [
  629. 'idStorage' => $item['idDatabase'],
  630. 'namespace' => $item['namespace'],
  631. ]
  632. ])
  633. ])
  634. ),
  635. ]),
  636. UI::h('span', ['style'=>"margin:0 12px"], [
  637. ( ($item['isObjectActive'] > 0)
  638. ? UI::h('span', [ 'class' => "label label-success", 'title' => "Namespace active" ], "Active")
  639. : UI::h('span', [ 'title' => "Namespace not active" ], [
  640. ($item['idZasob'] > 0)
  641. ? UI::hButtonAjax("Aktywuj", 'activateObjectAjax', [
  642. 'class' => "btn btn-xs btn-primary",
  643. 'href' => Router::getRoute('Storage')->getLink('activateObjectAjax'),
  644. 'data' => [
  645. 'namespace' => $item['namespace'],
  646. ]
  647. ])
  648. : '',
  649. ])
  650. ),
  651. ]),
  652. UI::h('a', [
  653. 'href' => "index.php?_route=ViewTableAjax&namespace={$item['namespace']}",
  654. 'class' => "btn btn-sm btn-link"
  655. ], "Przeglądaj tabelę"),
  656. ( ($item['idZasob'] > 0)
  657. ? UI::h('a', [
  658. 'href' => "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$item['idZasob']}&filtr_ids=%2B&filtr_ob=%2B",
  659. 'class' => "btn btn-sm btn-link",
  660. 'title' => "Struktura tabeli w drzewie zasobów"
  661. ], "Zasoby")
  662. : ''
  663. ),
  664. ( ($item['idZasob'] > 0)
  665. ? UI::h('a', [
  666. 'href' => "index.php?FUNCTION_INIT=PROCES_MENU&HEADER_NOT_INIT=YES&_task=PROCES_FOR_TABLE&tblId={$item['idZasob']}",
  667. 'class' => "btn btn-sm btn-link",
  668. 'title' => "Procesy dla aktualnie przeglądanej tabeli"
  669. ], "Procesy")
  670. : ''
  671. ),
  672. UI::h('a', [
  673. 'href' => Router::getRoute('Storage_AclReinstall')->getLink('', ['namespace' => $item['namespace']]),
  674. 'class' => 'btn btn-sm btn-link', 'style' => "color:#f00",
  675. 'title' => "Zainstaluje ponownie obiekt"
  676. ], "reinstall object"),
  677. UI::h('a', [
  678. 'href' => Router::getRoute('Storage_AclUsage')->getLink('', [ 'namespace' => $item['namespace'] ]),
  679. 'class' => "btn btn-sm btn-link",
  680. 'title' => "Uprawnienia - analiza użycia komórek w procesach"
  681. ], "Uprawnienia (analiza użycia)"),
  682. UI::h('a', [
  683. 'href' => Router::getRoute('WfsJsRequestPanel')->getLink('', [ 'namespace' => $item['namespace'] ]),
  684. 'class' => "btn btn-sm btn-link",
  685. 'title' => "JavaScript WFS Panel"
  686. ], "JavaScript WFS Panel"),
  687. UI::hButtonPost("(podgląd z relacjami)", [
  688. 'data' => [
  689. '_postTask' => 'preview'
  690. ],
  691. 'class' => 'btn btn-sm btn-link', 'style' => "font-style:italic",
  692. 'title' => "Podgląd kilku ostatnich obiektów wraz z relacjami"
  693. ]),
  694. ])
  695. ]);
  696. $thisGetLink = [ $this, 'getLink' ];
  697. { // not installed ref
  698. $refFields = array_filter($item['field'], function ($field) {
  699. return ('ref:' === substr($field['xsdType'], 0, 4) && $field['isActive']);
  700. });
  701. echo UI::h('h3', [], "Obiekty powiązane");
  702. UI::table([
  703. 'rows' => array_map(function ($backRef) use ($thisGetLink) {
  704. $refNamespace = $backRef['namespace'];
  705. $isInstalled = (1 == DB::getPDO()->fetchValue("
  706. select t.isObjectActive
  707. from `CRM_#CACHE_ACL_OBJECT` t
  708. where t.`namespace` = '{$refNamespace}'
  709. "));
  710. return [
  711. 'back ref namespace' => UI::h('a', [
  712. 'class' => "btn btn-xs btn-link",
  713. 'href' => $thisGetLink('', [ 'namespace' => $refNamespace ])
  714. ], "{$refNamespace}"),
  715. // 'idInstance' => $backRef['idInstance'],
  716. // 'isInstalled' => $isInstalled,
  717. '@class' => ($isInstalled) ? "success" : "danger",
  718. ];
  719. }, ACL::getBackRefList($item['namespace'])),
  720. ]);
  721. UI::table([
  722. 'rows' => array_map(function ($field) use ($thisGetLink) {
  723. $refNs = str_replace(['__x3A__', ':'], '/', substr($field['xsdType'], strlen('ref:')));
  724. $refNamespace = ACL::getBaseNamespace($refNs);
  725. $isInstalled = (1 == DB::getPDO()->fetchValue("
  726. select t.isObjectActive
  727. from `CRM_#CACHE_ACL_OBJECT` t
  728. where t.`namespace` = '{$refNamespace}'
  729. "));
  730. $refSource = null;
  731. if ($isInstalled) {
  732. try {
  733. $refTable = ACL::getRefTable($field['objectNamespace'], $field['fieldNamespace']);
  734. DBG::log($refTable, 'array', "getRefTable('{$field['objectNamespace']}', '{$field['fieldNamespace']}')");
  735. $refSource = ACL::getRefSource($field['objectNamespace'], $field['fieldNamespace']);
  736. DBG::log($refSource, 'array', "ACL::getRefSource('{$field['objectNamespace']}', '{$field['fieldNamespace']}')");
  737. } catch (Exception $e) {
  738. DBG::log($e);
  739. }
  740. }
  741. $labelRefSource = [
  742. 'table' => "Tabela",
  743. 'view' => "Widok",
  744. 'backRef' => "BackRef",
  745. ];
  746. return [
  747. 'child ref name' => $field['fieldNamespace'],
  748. // 'xsdType' => $field['xsdType'], // always === "ref:{$field['fieldNamespace']}"
  749. 'ref object' => UI::h('a', [
  750. 'class' => "btn btn-xs btn-link",
  751. 'href' => $thisGetLink('', [ 'namespace' => $refNamespace ])
  752. ], "{$refNs}"),
  753. 'ref source' => UI::h('div', [],
  754. (null === $refSource)
  755. ? [ "ref object not installed" ] // TODO: link to install? is table struct
  756. : [
  757. // UI::hButtonAjax("Tabela ref", "setFieldRefConfig", [
  758. // 'class' => "btn btn-xs btn-default" . ( 'table' === $refSource ? ' disabled' : '' ),
  759. // 'href' => $thisGetLink('setFieldRefConfig'),
  760. // 'data' => [ 'namespace' => $refNamespace, 'field' => $field['fieldNamespace'], 'do' => 'table' ]
  761. // ]),
  762. // UI::hButtonAjax("Widok (cache)", "setFieldRefConfig", [
  763. // 'title' => "Według flat_relation_cache",
  764. // 'class' => "btn btn-xs btn-default" . ( 'view' === $refSource ? ' disabled' : '' ),
  765. // 'href' => $thisGetLink('setFieldRefConfig'),
  766. // 'data' => [ 'namespace' => $refNamespace, 'field' => $field['fieldNamespace'], 'do' => 'view' ]
  767. // ]),
  768. $labelRefSource[$refSource] . ' ',
  769. ('view' === $refSource)
  770. ? UI::hButtonPost("Zmień na tabelę", [
  771. 'title' => "Według wygenerowanej tabeli REF",
  772. 'class' => "btn btn-xs btn-default" . ( 'table' === $refSource ? ' disabled' : '' ),
  773. // 'href' => $thisGetLink('setFieldRefConfig'),
  774. 'data' => [ 'namespace' => $refNamespace, 'field' => $field['fieldNamespace'], '_postTask' => 'setFieldRefConfig', 'source' => 'table' ]
  775. ])
  776. : '',
  777. ('table' === $refSource)
  778. ? UI::hButtonPost("Zmień na widok", [
  779. 'title' => "Według flat_relation_cache",
  780. 'class' => "btn btn-xs btn-default" . ( 'view' === $refSource ? ' disabled' : '' ),
  781. // 'href' => $thisGetLink('setFieldRefConfig'),
  782. 'data' => [ 'namespace' => $refNamespace, 'field' => $field['fieldNamespace'], '_postTask' => 'setFieldRefConfig', 'source' => 'view' ]
  783. ])
  784. : '',
  785. ]
  786. ),
  787. '@class' => ($isInstalled) ? "success" : "danger",
  788. ]; // TODO: link to install object
  789. }, $refFields)
  790. ]);
  791. }
  792. $thisGetLink = [ $this, 'getLink' ];
  793. UI::table([
  794. '__html_id' => 'struct_table',
  795. 'caption' => UI::h('span', [], [
  796. UI::h('span', [ 'style' => "margin-right:6px;color:#000" ], "Struktura obiektu '{$item['namespace']}'"),
  797. UI::h('code', [ 'style' => "margin-right:6px;color:#000" ], "(PrimaryKey: " . ($item['primaryKey'] ? $item['primaryKey'] : "Brak" ) . ")"),
  798. ]),
  799. // 'sortBy' => [
  800. // 'method' => 'get',
  801. // 'argName' => '_sortBy',
  802. // 'allow' => ['sort', 'namespace'],
  803. // 'default' => ['namespace', 'asc'],
  804. // ],
  805. 'cols_label' => [
  806. 'sort' => UI::h('nobr', [
  807. 'class' => "ta-ordering" . ('sort' === $sortByCol ? " ta-ordering-" . ( 'asc' === $sortByDir ? 'asc' : 'desc' ) : '' ),
  808. 'onClick' => "return p5UI_table_sortBy_get(this, '{$sortByArgName}', 'sort', '" . ('sort' === $sortByCol ? ( 'asc' === $sortByDir ? 'desc' : 'asc' ) : 'asc' ) . "')",
  809. 'title' => "Sortuj wg pola SORT_PRIO z zasobów",
  810. ], "sort"),
  811. 'namespace' => UI::h('nobr', [
  812. 'class' => "ta-ordering" . ('namespace' === $sortByCol ? " ta-ordering-" . ( 'asc' === $sortByDir ? 'asc' : 'desc' ) : '' ),
  813. 'onClick' => "return p5UI_table_sortBy_get(this, '{$sortByArgName}', 'namespace', '" . ('namespace' === $sortByCol ? ( 'asc' === $sortByDir ? 'desc' : 'asc' ) : 'asc' ) . "')",
  814. 'title' => "Sortuj wg nazwy pola",
  815. ], "namespace"),
  816. ],
  817. 'rows' => array_map(function ($field) use ($item, $thisGetLink, $sortByCol) {
  818. $tblItem = [];
  819. if ('sort' === $sortByCol && null !== $field['SORT_PRIO'] && !empty($field['idZasob'])) {
  820. $tblItem['@class'] = "ta-sortable-item";
  821. $tblItem['@class[sort]'] = "ta-sortable-item-handle";
  822. $tblItem['@data']['sort_prio'] = $field['SORT_PRIO'];
  823. $tblItem['@data']['id_zasob'] = $field['idZasob'];
  824. $field['SORT_PRIO'] = ":: {$field['SORT_PRIO']}";
  825. }
  826. $tblItem['sort'] = V::get('SORT_PRIO', null, $field);
  827. foreach ($field as $k => $v) {
  828. if ('SORT_PRIO' === $k) continue;
  829. $tblItem[$k] = $v;
  830. }
  831. $tblItem['namespace'] = UI::h('span', [], [
  832. UI::h('span', ['style' => "color:#aaa"], substr($field['namespace'], 0, strlen($field['objectNamespace']) + 1)),
  833. UI::h('span', ['style' => "color:#000"], substr($field['namespace'], strlen($field['objectNamespace']) + 1)),
  834. ]);
  835. $tblItem['idZasob'] = ($field['idZasob'] > 0)
  836. ? $field['idZasob']
  837. : (
  838. ($item['idZasob'] > 0)
  839. ? UI::hButtonAjax("+ do zasobów", 'addFieldToZasobyAjax', [
  840. 'class' => "btn btn-xs btn-primary",
  841. 'href' => $thisGetLink('addFieldToZasobyAjax'),
  842. 'data' => [
  843. 'namespace' => $item['namespace'],
  844. 'fieldNamespace' => $field['namespace'],
  845. ]
  846. ])
  847. : UI::h('span', ['title'=>"Brak Nr zasobu dla obiektu", 'class'=>"btn btn-xs btn-danger"], "Brak nr zasobu obiektu")
  848. )
  849. ;
  850. unset($tblItem['objectNamespace']);
  851. unset($tblItem['fieldNamespace']);
  852. return $tblItem;
  853. }, array_filter($item['field'], function ($field) { return $field['isActive']; }))
  854. ]);
  855. $removedFields = array_filter($item['field'], function ($field) { return !$field['isActive']; });
  856. if (!empty($removedFields)) {
  857. echo UI::h('details', [ 'style' => "margin-bottom:12px; padding:6px; background-color:#dedede; color:#000" ], [
  858. UI::h('summary', [ 'style' => "padding:0 3px; outline:none; cursor:pointer" ], "Pola w koszu (".count($removedFields).")"),
  859. UI::h('table', [ 'style' => "margin:6px 0 0 0; background-color:#fff; font-size:x-small", 'class' => "table table-bordered table-hover table-condensed" ], [
  860. UI::h('thead', [], [
  861. UI::h('tr', [], [
  862. UI::h('th', [], "#"),
  863. UI::h('th', [], "namespace"),
  864. UI::h('th', [], "idZasob"),
  865. UI::h('th', [], "xsdType"),
  866. UI::h('th', [], "xsdRestrictions"),
  867. UI::h('th', [], "appInfo"),
  868. UI::h('th', [], "minOccurs"),
  869. UI::h('th', [], "maxOccurs"),
  870. UI::h('th', [], "isActive"),
  871. ]),
  872. ]),
  873. UI::h('tbody', [], array_map(function ($field) use ($item, $thisGetLink) {
  874. return UI::h('tr', [], [
  875. UI::h('td', [], [
  876. UI::hButtonAjax("usuń", 'removeFieldFromTrashAjax', [
  877. 'class' => "btn btn-xs btn-danger",
  878. 'href' => $thisGetLink('removeFieldFromTrashAjax'),
  879. 'data' => [
  880. 'namespace' => $item['namespace'],
  881. 'fieldNamespace' => $field['namespace'],
  882. ]
  883. ])
  884. ]),
  885. UI::h('td', [], $field['fieldNamespace']),
  886. UI::h('td', [], [
  887. ($field['idZasob'] > 0)
  888. ? UI::h('span', [ 'class' => 'text-danger', 'title' => "Zasób zostanie usunięty" ], "{$field['idZasob']}")
  889. : UI::h('span', [ 'class' => 'text-muted' ], "brak")
  890. ]),
  891. UI::h('td', [], $field['xsdType']),
  892. UI::h('td', [], $field['xsdRestrictions']),
  893. UI::h('td', [], $field['appInfo']),
  894. UI::h('td', [], $field['minOccurs']),
  895. UI::h('td', [], $field['maxOccurs']),
  896. UI::h('td', [], $field['isActive']),
  897. ]);
  898. }, $removedFields)),
  899. ]),
  900. ]);
  901. }
  902. UI::hButtonAjaxOnResponse('removeFieldFromTrashAjax', /* payload, n */ "
  903. if (!payload.type) return false
  904. jQuery.notify(payload.msg, payload.type)
  905. if ('success' == payload.type) {
  906. var trJqNode = jQuery(n).closest('tr')
  907. var tbodyJqNode = trJqNode.parent()
  908. var detailsJqNode = trJqNode.closest('details')
  909. trJqNode.remove()
  910. if (!tbodyJqNode.children().length) {
  911. detailsJqNode.remove()
  912. }
  913. }
  914. ");
  915. UI::hButtonAjaxOnResponse('addFieldToZasobyAjax', /* payload, n */ "
  916. if (!payload.type) return false
  917. if (payload.body && payload.body.id && payload.body.id > 0) { // if ('success' == payload.type) {
  918. n.parentNode.replaceChild(document.createTextNode(payload.body.id), n)
  919. }
  920. jQuery.notify(payload.msg, payload.type)
  921. ");
  922. UI::hButtonAjaxOnResponse('addAclObjectToZasobyAjax', /* payload, n */ "
  923. if (!payload.type) return false
  924. if ('success' === payload.type || 'info' === payload.type) {
  925. if (payload.body && payload.body.id && payload.body.id > 0) {
  926. n.parentNode.replaceChild(document.createTextNode(payload.body.id), n)
  927. } else {
  928. console.log('TODO: addAclObjectToZasobyAjax unknown response', payload);
  929. }
  930. window.location.reload()
  931. }
  932. ");
  933. UI::hButtonAjaxOnResponse('activateObjectAjax', /* payload, n */ "
  934. jQuery.notify(payload.msg, payload.type)
  935. if (!payload.type) return false
  936. if ('success' === payload.type || 'info' === payload.type) {
  937. if (payload.body && payload.body.isObjectActive && payload.body.isObjectActive > 0) {
  938. n.parentNode.replaceChild(document.createTextNode('Active'), n)
  939. } else {
  940. console.log('TODO: activateObjectAjax unknown response', payload);
  941. }
  942. }
  943. ");
  944. if ('sort' === $sortByCol) {
  945. echo UI::h('script', [], "
  946. jQuery(document).ready(function (){
  947. var tblNode$ = jQuery('#struct_table > tbody')
  948. var getOrder = function () {
  949. var orderIds = []
  950. jQuery('#struct_table > tbody').children('.ta-sortable-item').each(function (idx, trNode) {
  951. orderIds.push(jQuery(trNode).data('id_zasob'))
  952. })
  953. return orderIds
  954. }
  955. var sortOrder = getOrder()
  956. console.log('sortOrder - init', sortOrder)
  957. tblNode$.sortable({
  958. axis: 'y',
  959. handle: '.ta-sortable-item-handle',
  960. items: '.ta-sortable-item',
  961. update: function (event, ui) {
  962. sortOrder = getOrder()
  963. tblNode$.sortable('disable')
  964. tblNode$.find('.ta-sortable-item-handle').css({color:'silver'})
  965. console.log('TODO: disable sortable while ajax')
  966. // window.setTimeout(function () {
  967. // tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  968. // console.log('TODO: ajax fetch result')
  969. // tblNode$.sortable('enable')
  970. // tblNode$.sortable('cancel')
  971. // }, 1000)
  972. window.fetch(
  973. URI(window.location.href)
  974. .setSearch('_task', 'updateAntAclSortAjax')
  975. .setSearch('idZasobOrder', sortOrder)
  976. .build().toString(),
  977. {
  978. method: 'POST',
  979. headers: {
  980. 'Content-Type': 'application/x-www-form-urlencoded' // query string
  981. },
  982. credentials: 'same-origin',
  983. body: JSON.stringify({
  984. namespace: URI.parseQuery(window.location.search).namespace,
  985. sortBy: '{$sortByCol}',
  986. sortByDir: '{$sortByDir}',
  987. sortOrder: sortOrder,
  988. })
  989. }
  990. ).then(function(response) {
  991. return response.json()
  992. }).then(function(payload) {
  993. console.log('updateAntAclSortAjax response', payload);
  994. tblNode$.sortable('enable')
  995. if ('success' !== payload.type) {
  996. tblNode$.sortable('cancel')
  997. }
  998. tblNode$.sortable('enable')
  999. tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  1000. p5UI__notifyAjaxCallback({
  1001. type: payload.type || 'error',
  1002. msg: payload.msg || 'Request error'
  1003. });
  1004. if ('success' === payload.type) {
  1005. window.location.reload(true)
  1006. }
  1007. }).catch(function(e) {
  1008. tblNode$.sortable('enable')
  1009. tblNode$.sortable('cancel')
  1010. tblNode$.find('.ta-sortable-item-handle').css({color:'black'})
  1011. p5UI__notifyAjaxCallback({
  1012. type: 'error',
  1013. msg: 'Request error ' + e
  1014. });
  1015. })
  1016. }
  1017. });
  1018. });
  1019. ");
  1020. }
  1021. if ($item['isObjectActive']) {
  1022. echo UI::hButtonAjax("Dodaj podstawowy proces dla obiektu '{$item['namespace']}' - read only (TODO)", 'addObjectBaseProcesAjax', [
  1023. 'class' => "btn btn-xs btn-default",
  1024. 'href' => Router::getRoute('Storage')->getLink('addObjectBaseProcesAjax'),
  1025. 'data' => [ 'namespace' => $item['namespace'] ]
  1026. ]);
  1027. UI::hButtonAjaxOnResponse('addObjectBaseProcesAjax', /* payload, n */ "
  1028. jQuery.notify(payload.msg, payload.type)
  1029. ");
  1030. }
  1031. DBG::nicePrint($item, '$item');
  1032. }
  1033. public function updateAntAclSortAjaxAction() {
  1034. return Response::sendTryCatchJson(array($this, 'updateAntAclSortAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  1035. }
  1036. public function updateAntAclSortAjax($args) {
  1037. DBG::log($args, 'array', "args");
  1038. $namespace = V::get('namespace', '', $args);
  1039. if (empty($namespace)) throw new Exception("Missing param namespace");
  1040. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  1041. DBG::log($item, 'array', "\$item");
  1042. $sortByArgName = 'sortBy';
  1043. $sortByCol = V::get($sortByArgName, 'namespace', $args);
  1044. $sortByDir = V::get("{$sortByArgName}Dir", 'asc', $args);
  1045. if ('sort' !== $sortByCol) throw new Exception("Only sort by SORT_PRIO allowed to update");
  1046. if (!in_array($sortByDir, ['asc', 'desc'])) throw new Exception("Wrong order by dir arg");
  1047. if ('asc' !== $sortByDir) throw new Exception("Only sort asc is allowed"); // DBG
  1048. $sortPrioIdsFromZasoby = DB::getPDO()->fetchAll("
  1049. select z.ID, z.SORT_PRIO
  1050. from CRM_LISTA_ZASOBOW z
  1051. where z.PARENT_ID = :p_id
  1052. order by z.SORT_PRIO asc, z.ID asc -- default order in Zasoby tree
  1053. ", [
  1054. ':p_id' => $item['idZasob']
  1055. ]);
  1056. DBG::log($sortPrioIdsFromZasoby, 'array', "\$sortPrioIdsFromZasoby");
  1057. $idZasobCurrentOrder = array_map(function ($orderRow) {
  1058. return (int)$orderRow['ID'];
  1059. }, $sortPrioIdsFromZasoby);
  1060. DBG::log($idZasobCurrentOrder, 'array', "\$idZasobCurrentOrder");
  1061. DBG::log(array_diff_assoc($args['sortOrder'], $idZasobCurrentOrder), 'array', "array_diff_assoc(\$args['sortOrder'], \$idZasobCurrentOrder)");
  1062. DBG::log(array_diff_assoc($idZasobCurrentOrder, $args['sortOrder']), 'array', "array_diff_assoc(\$idZasobCurrentOrder, \$args['sortOrder'])");
  1063. $orderDiff = array_diff_assoc($args['sortOrder'], $idZasobCurrentOrder);
  1064. foreach ($orderDiff as $sortPrio => $idZasob) {
  1065. DB::getPDO()->update('CRM_LISTA_ZASOBOW', 'ID', $idZasob, [
  1066. 'SORT_PRIO' => $sortPrio,
  1067. ]);
  1068. }
  1069. return [
  1070. 'type' => 'success',
  1071. 'msg' => "OK",
  1072. 'DBG__args' => $args
  1073. ];
  1074. }
  1075. public function removeFieldFromTrashAjaxAction() {
  1076. DBG::log($_REQUEST, 'array', '$_REQUEST');
  1077. Response::sendTryCatchJson(array($this, 'removeFieldFromTrashAjax'), $_REQUEST);
  1078. }
  1079. public function removeFieldFromTrashAjax($args) {
  1080. $namespace = V::get('namespace', '', $args);
  1081. if (empty($namespace)) throw new HttpException("Missing namespace");
  1082. $fieldNamespace = V::get('fieldNamespace', '', $args);
  1083. if (empty($fieldNamespace)) throw new HttpException("Missing fieldNamespace");
  1084. $fieldItem = SchemaFactory::loadDefaultObject('SystemObjectField')->getItem($fieldNamespace);
  1085. if (!$fieldItem) throw new HttpException("Field not found '{$fieldNamespace}'", 404);
  1086. DBG::log($fieldItem, 'array', "\$fieldItem");
  1087. if ('p5:enum' === $fieldItem['xsdType']) {
  1088. // DBG::log(DB::getPDO()->fetchAll("
  1089. // select e.*
  1090. // from `CRM_#CACHE_ACL_OBJECT_FIELD_enum` e
  1091. // where e.objectNamespace = :objectNamespace
  1092. // and e.fieldNamespace = :fieldNamespace
  1093. // ", [
  1094. // ':objectNamespace' => $fieldItem['objectNamespace'],
  1095. // ':fieldNamespace' => $fieldItem['fieldNamespace'],
  1096. // ]), 'array', "enum values");
  1097. DB::getPDO()->execSql("
  1098. DELETE from `CRM_#CACHE_ACL_OBJECT_FIELD_enum`
  1099. where objectNamespace = :objectNamespace
  1100. and fieldNamespace = :fieldNamespace
  1101. and isActive = 0
  1102. ", [
  1103. ':objectNamespace' => $fieldItem['objectNamespace'],
  1104. ':fieldNamespace' => $fieldItem['fieldNamespace'],
  1105. ]);
  1106. }
  1107. DB::getPDO()->execSql("
  1108. DELETE from `CRM_#CACHE_ACL_OBJECT_FIELD`
  1109. where namespace = :namespace
  1110. and objectNamespace = :objectNamespace
  1111. and _rootTableName = :rootTableName
  1112. and isActive = 0
  1113. limit 1
  1114. ", [
  1115. 'namespace' => $fieldItem['namespace'],
  1116. 'objectNamespace' => $fieldItem['objectNamespace'],
  1117. 'rootTableName' => $fieldItem['_rootTableName'],
  1118. ]);
  1119. if ($fieldItem['idZasob'] > 0) {
  1120. $zasob = DB::getPDO()->fetchFirst(" select z.ID, z.A_STATUS, z.DESC from CRM_LISTA_ZASOBOW z where z.ID = :id ", [ ':id' => $fieldItem['idZasob'] ]);
  1121. if ($zasob) {
  1122. if ('DELETED' !== $zasob['A_STATUS']) {
  1123. $affected = DB::getPDO()->update('CRM_LISTA_ZASOBOW', 'ID', $zasob['ID'], [
  1124. 'A_STATUS' => 'DELETED',
  1125. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1126. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1127. ]);
  1128. if ($affected) {
  1129. DB::getPDO()->insert('CRM_LISTA_ZASOBOW_HIST', [
  1130. 'ID_USERS2' => $zasob['ID'],
  1131. 'A_STATUS' => 'DELETED',
  1132. 'A_RECORD_CREATE_DATE' => 'NOW()',
  1133. 'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
  1134. ]);
  1135. }
  1136. }
  1137. }
  1138. $wskazniki = DB::getPDO()->fetchAll("
  1139. select w.ID, w.A_STATUS
  1140. from CRM_WSKAZNIK w
  1141. where w.ID_ZASOB = :id
  1142. ", [ ':id' => $fieldItem['idZasob'] ]);
  1143. if (!empty($wskazniki)) {
  1144. foreach ($wskazniki as $wsk) {
  1145. if ('DELETED' !== $wsk['A_STATUS']) {
  1146. $affected = DB::getPDO()->update('CRM_WSKAZNIK', 'ID', $wsk['ID'], [
  1147. 'A_STATUS' => 'DELETED',
  1148. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1149. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1150. ]);
  1151. if ($affected) {
  1152. DB::getPDO()->insert('CRM_WSKAZNIK_HIST', [
  1153. 'ID_USERS2' => $wsk['ID'],
  1154. 'A_STATUS' => 'DELETED',
  1155. 'A_RECORD_CREATE_DATE' => 'NOW()',
  1156. 'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
  1157. ]);
  1158. }
  1159. }
  1160. }
  1161. }
  1162. }
  1163. return [
  1164. 'type' => "success",
  1165. 'msg' => "Usunięto pole {$fieldItem['fieldNamespace']}",
  1166. ];
  1167. }
  1168. public function addFieldToZasobyAjaxAction() {
  1169. DBG::log($_REQUEST, 'array', '$_REQUEST');
  1170. Response::sendTryCatchJson(array($this, 'addFieldToZasobyAjax'), $_REQUEST);
  1171. }
  1172. public function addFieldToZasobyAjax($args) {
  1173. $namespace = V::get('namespace', '', $args);
  1174. if (empty($namespace)) throw new HttpException("Missing namespace");
  1175. $fieldNamespace = V::get('fieldNamespace', '', $args);
  1176. if (empty($fieldNamespace)) throw new HttpException("Missing fieldNamespace");
  1177. $fieldItem = SchemaFactory::loadDefaultObject('SystemObjectField')->getItem($fieldNamespace);
  1178. if (!$fieldItem) throw new HttpException("Field not found '{$fieldNamespace}'", 404);
  1179. DBG::log($fieldItem, 'array', "\$fieldItem");
  1180. if ($fieldItem['idZasob'] > 0) throw (new AlertSuccessException("Field already added to Zasoby '{$fieldItem['idZasob']}'"))->setBody([ 'id' => $fieldItem['idZasob'] ]);
  1181. $objectItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace);
  1182. if (!$objectItem) throw new HttpException("Object not found '{$namespace}'", 404);
  1183. DBG::log($objectItem, 'array', "\$objectItem");
  1184. if (!$objectItem['idZasob']) throw new Exception("Missing Object idZasob");
  1185. $zasobItem = DB::getPDO()->fetchFirst("
  1186. select zField.ID, zField.`DESC`, zField.`TYPE`, zField.PARENT_ID
  1187. from CRM_LISTA_ZASOBOW as zField
  1188. join CRM_LISTA_ZASOBOW as zTable on(zTable.ID = zField.PARENT_ID)
  1189. where zTable.`ID` = '{$objectItem['idZasob']}'
  1190. and zTable.`TYPE` = 'TABELA'
  1191. and zField.`DESC` = '{$fieldItem['fieldNamespace']}'
  1192. and zField.`TYPE` = 'KOMORKA'
  1193. ");
  1194. if ($zasobItem) {
  1195. SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
  1196. 'namespace' => $fieldItem['namespace'],
  1197. 'idZasob' => $zasobItem['ID']
  1198. ]);
  1199. throw (new AlertSuccessException("Zasob już istnieje"))->setBody([ 'id' => $zasobItem['ID'] ]);
  1200. }
  1201. $newFieldItem = [
  1202. 'PARENT_ID' => $objectItem['idZasob'],
  1203. 'TYPE' => 'KOMORKA',
  1204. 'DESC' => $fieldItem['fieldNamespace'],
  1205. 'DESC_PL' => $fieldItem['fieldNamespace'],
  1206. ];
  1207. DBG::log($newFieldItem, 'array', "add new field item");
  1208. try {
  1209. $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
  1210. } catch (Exception $e) {
  1211. throw new Exception("Brak dostępu do tabeli Zasoby");
  1212. }
  1213. $createdId = $acl->addItem($newFieldItem);
  1214. if (!$createdId) throw new Exception("Nie udało się utworzyć nowego rekordu!");
  1215. SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
  1216. 'namespace' => $fieldItem['namespace'],
  1217. 'idZasob' => $createdId
  1218. ]);
  1219. throw (new AlertSuccessException("Utworzono pomyślnie rekord nr {$createdId}"))->setBody([ 'id' => $createdId ]);
  1220. }
  1221. }