AclStruct.php 45 KB

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