AclStruct.php 45 KB

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