AclStruct.php 50 KB

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