AclStruct.php 41 KB

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