AclStruct.php 52 KB

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