BiAuditGenerate.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. Lib::loadClass('FoldersConfig');
  4. Lib::loadClass('FileUploader');
  5. Lib::loadClass('ProcesHelper');
  6. Lib::loadClass('SchemaFactory');
  7. Lib::loadClass('Core_AclHelper');
  8. Lib::loadClass('Core_AclSimpleSchemaBase');
  9. class Route_UrlAction_BiAuditGenerate extends RouteBase {
  10. private $powiazanie = null;
  11. private $REFERER;
  12. public function handleAuth() {
  13. if (!User::logged()) {
  14. User::authByRequest();
  15. }
  16. }
  17. private function getDirectory($table, $id) {
  18. $folderConf = FoldersConfig::getAll($table.'_COLUMN');
  19. $record = new stdClass;
  20. $record->ID = $id;
  21. $uploader = new FileUploader($table.'_COLUMN', $record);
  22. $errMsg = "";
  23. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$$errMsg}", 404);
  24. $uploader->findFolder();
  25. return $uploader->getDestLocalPath(true);
  26. }
  27. private function getMainDirectory() {
  28. $folderConf = FoldersConfig::getAll('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_COLUMN');
  29. if (!isset($folderConf['mount_point'])) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
  30. return $folderConf['mount_point'];
  31. }
  32. private function initializePowiazaniaForm() {
  33. ?>
  34. <div class="container" style="margin-top:20px">
  35. <form class="form-horizontal" method="post">
  36. <legend>
  37. Generowanie powiązań :: <?=$this->powiazanie['L_APPOITMENT_INFO']?>
  38. <span class="pull-right"># <?=$this->powiazanie['ID']?></span>
  39. </legend>
  40. <div class="form-group">
  41. <div class="col-sm-12">
  42. <h4>Wybierz pracowników, dla których mają zostać wyszukane powiązania</h4>
  43. <table class="table table-bordered table-hover table-striped" height=5>
  44. <thead>
  45. <tr style="text-align:center; background-color:lightgray">
  46. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  47. <td width=1>ID</td>
  48. <td>Imiona</td>
  49. <td>Nazwisko</td>
  50. <td>Pesel</td>
  51. <td>NIP</td>
  52. <td>Regon</td>
  53. </tr>
  54. </thead>
  55. <tbody>
  56. <?php
  57. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
  58. $queryFeatures = $acl->buildQuery(['limit' => 0]);
  59. $pracownicy = $queryFeatures->getItems();
  60. foreach ($pracownicy as $pracownik) {
  61. ?>
  62. <tr>
  63. <td><input type="checkbox" name="prID[]" value="<?=$pracownik['ID']?>" onClick="toggle(this)"/></td>
  64. <td align="right"><?=$pracownik['ID']?></td>
  65. <td><?=$pracownik['imiona']?></td>
  66. <td><?=$pracownik['nazwisko']?></td>
  67. <td><?=$pracownik['pesel']?></td>
  68. <td><?=$pracownik['nip']?></td>
  69. <td><?=$pracownik['regon']?></td>
  70. </tr>
  71. <?php
  72. }
  73. ?>
  74. <tr>
  75. <td><input type="checkbox" name="reloadCache"/></td>
  76. <td colspan=6>Odśwież cache (wymagane w przypadku, gdy dokonano dowolnych zmian w tabelach pracowników/kontrahentów)</td>
  77. </tr>
  78. </tbody>
  79. </table>
  80. </div>
  81. </div>
  82. <div class="form-group">
  83. <div class="col-sm-12">
  84. <div class="containter" style="text-align:center">
  85. <button type="submit" class="btn btn-primary" name="action" value="initialize">Generuj</button>
  86. <a href="<?=$this->REFERER?>" class="btn btn-default">Anuluj</a>
  87. </div>
  88. </div>
  89. </div>
  90. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  91. </form>
  92. </div>
  93. <script language="JavaScript">
  94. <!--
  95. function toggleAll(source) {
  96. checkboxes = document.getElementsByName('prID[]');
  97. for(var i=0, n=checkboxes.length;i<n;i++) checkboxes[i].checked = source.checked;
  98. }
  99. function toggle(source) {
  100. checkboxes = document.getElementsByName('prID[]');
  101. all = true;
  102. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked == false) all = false;
  103. source.form['checkAll'].checked = all;
  104. }
  105. -->
  106. </script>
  107. <?php
  108. }
  109. private function initializePowiazaniaSave() {
  110. $prID = V::get('prID', array(), $_POST);
  111. if (!$prID) throw new Exception("Nie wybrano żadnego pracownika!");
  112. $reloadCache = V::get('reloadCache', 'off', $_POST);
  113. $sqlArr = [
  114. 'ID' => $this->powiazanie['ID'],
  115. 'FILE_STATUS' => 'TO_GENERATE',
  116. ];
  117. if ($reloadCache == 'on') $sqlArr['BI_analiza_reloadCache'] = 'Y';
  118. $this->truncatePowiazaniaFromDB($this->powiazanie['ID']);
  119. $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  120. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
  121. foreach ($prID as $v) DB::getPDO()->insert($refPowiazaniaToPracownicy, ['PRIMARY_KEY' => $this->powiazanie['ID'], 'REMOTE_PRIMARY_KEY' => $v]);
  122. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
  123. $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
  124. $kontrahenci = $queryFeatures->getItems();
  125. $refPowiazaniaToKontrahenci = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  126. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI');
  127. foreach ($kontrahenci as $kontrahent) DB::getPDO()->insert($refPowiazaniaToKontrahenci, ['PRIMARY_KEY' => $this->powiazanie['ID'], 'REMOTE_PRIMARY_KEY' => $kontrahent['ID']]);
  128. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_KW_requested_person/BI_audit_KW_requested_person');
  129. $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
  130. $requestedPersons = $queryFeatures->getItems();
  131. $refPowiazaniaToKwRequestedPreson = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  132. 'default_db__x3A__BI_audit_KW_requested_person:BI_audit_KW_requested_person');
  133. foreach ($requestedPersons as $requestedPerson) DB::getPDO()->insert($refPowiazaniaToKwRequestedPreson, ['PRIMARY_KEY' => $this->powiazanie['ID'], 'REMOTE_PRIMARY_KEY' => $requestedPerson['ID']]);
  134. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Y'";
  135. $result = DB::getPDO()->fetchValue($query);
  136. if ($result) $sqlArr['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache (wymagane dla innego rekordu)';
  137. elseif ($reloadCache == 'on') $sqlArr['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache';
  138. else $sqlArr['FILE_STATUS_info'] = "Oczekuje na wygenerowanie powiązań";
  139. $affected = DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  140. if ($affected) {
  141. SE_Layout::alert('success','Oznaczono rekord do wygenerowania');
  142. ?>
  143. <div class="container" style="text-align:center">
  144. <a href="<?=$this->REFERER?>" class="btn btn-primary">Powrót</a>
  145. </div>
  146. <?php
  147. } else {
  148. throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  149. }
  150. }
  151. private function initializePowiazania() {
  152. switch (V::get('action', '', $_POST)) {
  153. case "initialize":
  154. $this->initializePowiazaniaSave();
  155. break;
  156. default:
  157. $this->initializePowiazaniaForm();
  158. }
  159. }
  160. private function showPowiazania() {
  161. // $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  162. // $xmlFile = "{$powiazanieDirLocation}/relations.xml";
  163. // echo "<pre>" . htmlentities(file_get_contents($xmlFile)) . "</pre>";
  164. echo "Statystyki znalezionych powiązań [TODO]";
  165. }
  166. private function powiazania($ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA) {
  167. try {
  168. $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA}'");
  169. if (!$powiazania) throw new Exception("Błąd danych");
  170. $this->powiazanie = $powiazania[0];
  171. switch ($this->powiazanie['FILE_STATUS']) {
  172. case "NONE":
  173. $this->initializePowiazania();
  174. break;
  175. case "GENERATED":
  176. $this->showPowiazania();
  177. break;
  178. default:
  179. throw new Exception("Błędny status rekordu");
  180. }
  181. } catch (Exception $e) {
  182. SE_Layout::alert('danger',$e->getMessage());
  183. $_SESSION['REFERER'] = $this->REFERER;
  184. ?>
  185. <div class="container" style="text-align:center">
  186. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
  187. </div>
  188. <?php
  189. }
  190. }
  191. public function defaultAction() {
  192. SE_Layout::gora();
  193. SE_Layout::menu();
  194. if (isset($_SESSION['REFERER'])) {
  195. $this->REFERER = $_SESSION['REFERER'];
  196. unset($_SESSION['REFERER']);
  197. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  198. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  199. if (V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int') > 0) $this->powiazania(V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int'));
  200. else SE_Layout::alert('danger','Błąd parametru');
  201. SE_Layout::dol();
  202. }
  203. private function getRefsTables($namespace) {
  204. try {
  205. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  206. if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
  207. $fields = $item['field'];
  208. $refsTables = [];
  209. foreach ($fields as $field) {
  210. list($type, $child) = explode(":", $field['xsdType'], 2);
  211. if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) $refsTables[] = ACL::getRefTable($namespace, $child);
  212. }
  213. return $refsTables;
  214. } catch (Exception $e) {
  215. echo "{$namespace} - {$e->getMessage}";
  216. return [];
  217. }
  218. }
  219. private function truncatePowiazaniaFromDB($ID) {
  220. $refsTables = $this->getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  221. if (!$refsTables) return null;
  222. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  223. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  224. $refsTables = array_diff($refsTables, [$refPowiazaniaToPowiazaniaRow]);
  225. $query = "delete from `" . implode("`, `", $refsTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  226. foreach ($refsTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  227. $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  228. DB::getPDO()->query($query);
  229. }
  230. private function deleteResultsFromDB($ID) {
  231. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  232. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  233. $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
  234. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  235. $refsTables = $this->getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  236. $sqlDeleteFrom = "delete from
  237. `{$refPowiazaniaToPowiazaniaRow}`,
  238. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
  239. `{$refPowiazaniaRowToPowiazaniaRowObject}`,
  240. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
  241. $sqlUsing = "
  242. using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  243. join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
  244. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
  245. join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
  246. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
  247. $sqlWhere = "
  248. where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  249. foreach ($refsTables as $refTable) {
  250. $sqlDeleteFrom .= ",\n`{$refTable}`";
  251. $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  252. }
  253. $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
  254. DB::getPDO()->query($query);
  255. }
  256. public function doGenerate() {
  257. function generatePhpScript($function) {
  258. return '<?php
  259. ini_set("memory_limit", "4G");
  260. define("DS", DIRECTORY_SEPARATOR);
  261. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  262. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  263. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  264. ini_set("display_startup_errors", "0");
  265. ini_set("log_errors", "1");
  266. ini_set("error_log", "/var/log/apache2/error_log");
  267. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  268. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  269. Lib::loadClass("Router");
  270. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  271. ';
  272. }
  273. try {
  274. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  275. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  276. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  277. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  278. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  279. ### Ustawienie zmiennych
  280. $powiazaniaDirLocation = $this->getMainDirectory();
  281. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  282. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  283. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  284. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  285. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  286. ### Utworzenie niezbędnych katalogów i plików
  287. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0755, true);
  288. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  289. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  290. $doGenerate = true;
  291. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Y' and FILE_STATUS = 'TO_GENERATE'";
  292. $result = DB::getPDO()->fetchAll($query);
  293. if ($result) {
  294. $doGenerate = false;
  295. $sqlArr = [];
  296. if (file_exists($reloadCachePhpFile)) {
  297. if (file_exists($reloadCacheResultFile)) {
  298. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  299. if ($reloadCacheResult == "ok") {
  300. $sqlArr = [
  301. 'FILE_STATUS_info' => 'Odświeżono cache, oczekiwanie na wygenerowanie powiązań',
  302. 'BI_analiza_reloadCache' => 'N',
  303. ];
  304. $doGenerate = true;
  305. } else {
  306. $sqlArr = [
  307. 'FILE_STATUS' => 'ERROR',
  308. 'FILE_STATUS_info' => "Wystąpił błąd podczas odświeżania cache ({$reloadCacheResult})",
  309. ];
  310. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  311. $result = DB::getPDO()->fetchAll($query);
  312. }
  313. unlink($reloadCachePhpFile);
  314. unlink($reloadCachePidFile);
  315. unlink($reloadCacheResultFile);
  316. } elseif (file_exists($reloadCachePidFile)) {
  317. $pid = file_get_contents($reloadCachePidFile);
  318. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  319. $processShouldBeRunning = "php {$reloadCachePhpFile}";
  320. if ($processRunning != $processShouldBeRunning) {
  321. if (!file_exists($reloadCacheResultFile)) {
  322. $sqlArr = [
  323. 'FILE_STATUS' => 'ERROR',
  324. 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas odświeżania cache - nie znaleziono procesu potomnego",
  325. ];
  326. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  327. $result = DB::getPDO()->fetchAll($query);
  328. unlink($reloadCachePhpFile);
  329. unlink($reloadCachePidFile);
  330. unlink($reloadCacheResultFile);
  331. }
  332. }
  333. }
  334. } else {
  335. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  336. $result2 = DB::getPDO()->fetchValue($query);
  337. if ($result2) {
  338. $sqlArr = [
  339. 'FILE_STATUS_info' => 'Wstrzymano odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  340. ];
  341. } else {
  342. $sqlArr = [
  343. 'FILE_STATUS_info' => 'W trakcie odświeżania cache',
  344. ];
  345. file_put_contents($reloadCachePhpFile, generatePhpScript('doReloadCache()'));
  346. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  347. }
  348. }
  349. if ($sqlArr) {
  350. foreach ($result as $row) {
  351. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  352. }
  353. }
  354. }
  355. ### Generowanie powiązań
  356. if ($doGenerate) {
  357. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
  358. $result = DB::getPDO()->fetchAll($query);
  359. foreach ($result as $row) {
  360. $sqlArr = [
  361. 'ID' => $row['ID'],
  362. 'FILE_STATUS' => 'IN_PROGRESS',
  363. 'FILE_STATUS_info' => 'W trakcie generowania powiązań',
  364. ];
  365. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  366. $this->deleteResultsFromDB($row['ID']);
  367. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  368. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  369. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  370. file_put_contents($generatePowiazaniaPhpFile, generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  371. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  372. }
  373. }
  374. ### Weryfikacja świeżo wygenerowanych powiązań
  375. $query = "select ID, BI_analiza_depth from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  376. $result = DB::getPDO()->fetchAll($query);
  377. foreach ($result as $row) {
  378. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  379. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  380. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  381. $error = false;
  382. $success = false;
  383. $sqlArr = [];
  384. if (file_exists($generatePowiazaniaResultFile)) {
  385. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.xml";
  386. if (file_exists($xmlFile)) {
  387. if (filesize($xmlFile)) {
  388. $generatePowiazaniaResult = file_get_contents($generatePowiazaniaResultFile);
  389. if ($generatePowiazaniaResult == "ok") {
  390. $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  391. if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0777, false);
  392. if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
  393. else $success = true;
  394. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult})";
  395. } else $error = "Wystąpił nieznany błąd - plk xml został wygenerowany niepoprawnie";
  396. } else $error = "Wystąpił nienzany błąd - nie znaleziono pliku xml";
  397. } elseif (file_exists($generatePowiazaniaPidFile)) {
  398. $pid = file_get_contents($generatePowiazaniaPidFile);
  399. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  400. $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
  401. if ($processRunning != $processShouldBeRunning) {
  402. if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
  403. }
  404. }
  405. if ($error) {
  406. $sqlArr = [
  407. 'FILE_STATUS' => 'ERROR',
  408. 'FILE_STATUS_info' => $error,
  409. ];
  410. deleteResultsFromDB($row['ID']);
  411. if (file_exists($xmlFile)) unlink($xmlFile);
  412. } elseif ($success) {
  413. $sqlArr = [
  414. 'FILE_STATUS' => 'GENERATED',
  415. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  416. ];
  417. $destXmlFile = "{$powiazanieDirLocation}/relations.xml";
  418. rename($xmlFile, $destXmlFile);
  419. }
  420. if ($sqlArr) {
  421. $sqlArr['ID'] = $row['ID'];
  422. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  423. if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
  424. if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
  425. if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
  426. }
  427. }
  428. } catch (Exception $e) {
  429. echo $e->getMessage()."\n";
  430. }
  431. }
  432. private function reloadCache_reTeryt() {
  433. Lib::loadClass('Teryt');
  434. function reTeryt($table) {
  435. $tableConf = [
  436. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  437. 'kodPocztowy' => 'Kod_pocztowy',
  438. 'miejscowosc' => 'Miejscowosc',
  439. 'ulica' => 'Ulica',
  440. ],
  441. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  442. 'kodPocztowy' => 'kodPocztowy',
  443. 'miejscowosc' => 'miejscowosc',
  444. 'ulica' => 'ulica',
  445. ],
  446. ];
  447. $columns = ['kodPocztowy', 'miejscowosc', 'ulica'];
  448. $query = "select * from `{$table}` where TERYT_SYM is null";
  449. try {
  450. $adresy = DB::getPDO()->fetchall($query);
  451. foreach ($adresy as $adres) {
  452. $search = [];
  453. foreach ($columns as $column) $search[$column] = $adres[$tableConf[$table][$column]];
  454. try {
  455. $teryt = Teryt::search($search);
  456. if ($teryt) {
  457. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  458. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  459. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  460. }
  461. } catch (Exception $e) {
  462. }
  463. }
  464. } catch (Exception $e) {
  465. }
  466. }
  467. reTeryt('BI_audit_ENERGA_RUM_KONTRAHENCI');
  468. reTeryt('BI_audit_ENERGA_PRACOWNICY_adresy');
  469. }
  470. private function reloadCache_updateAll() {
  471. $tables = [
  472. 'BI_audit_ENERGA_PRACOWNICY' => [
  473. 'fields' => [
  474. 'nip' => 'nip',
  475. 'regon' => 'regon',
  476. 'pesel' => 'pesel',
  477. ],
  478. //'where' => '',
  479. ],
  480. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  481. 'fields' => [
  482. 'TERYT_SYM' => 'TERYT_SYM',
  483. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  484. 'nrDomu' => 'nrBudynku',
  485. 'nrLokalu' => 'nrLokalu',
  486. ],
  487. //'where' => '',
  488. ],
  489. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  490. 'fields' => [
  491. 'nip' => 'NIP',
  492. 'regon' => 'REGON',
  493. 'pesel' => 'PESEL',
  494. 'TERYT_SYM' => 'TERYT_SYM',
  495. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  496. 'nrDomu' => 'Numer_budynku',
  497. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  498. ],
  499. 'where' => "ownCompany != 'Y'",
  500. ],
  501. 'BI_audit_KW_requested_person' => [
  502. 'fields' => [
  503. 'pesel' => 'Seller_person_pesel',
  504. 'krs' => 'Seller_person_KRS',
  505. 'nip' => 'Seller_person_NIP',
  506. 'regon' => 'Seller_person_REGON',
  507. ],
  508. //'where' => '',
  509. ],
  510. ];
  511. $queries[] = "delete from BI_audit_ALL where BASE = 0";
  512. $queries[] = "delete from BI_audit_ALL_ref where BASE = 0";
  513. $queries[] = "delete from BI_audit_ALL_ref_RELATIONS where BASE = 0";
  514. foreach ($tables as $name => $table) {
  515. if (isset($table['where']) && $table['where']) $where = "where {$table['where']}";
  516. else $where = '';
  517. $queries[] = "insert into BI_audit_ALL (REMOTE_TABLE, REMOTE_ID, " . implode(", ", array_keys($table['fields'])) . ") select '{$name}', ID, " . implode(", ", $table['fields']) . " from {$name} {$where}";
  518. }
  519. $queries[] = "update BI_audit_ALL set nrDomu = substring(nrDomu, 1, position('/' in nrDomu) - 1), nrLokalu = substring(nrDomu, position('/' in nrDomu ) + 1) where nrDomu rlike '^[[:digit:]]+.*/[[:digit:]]+.*$' and nrLokalu is null and BASE = 0";
  520. $queries[] = "set @var = (select round(coalesce(max(ID), '0.5')) from BI_audit_ALL_ref_RELATIONS)";
  521. $queries[] = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) select @var:=@var*2, a.RELATION from (select a.REMOTE_TABLE as RELATION from BI_audit_ALL a where a.REMOTE_TABLE not in ('BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person') group by a.REMOTE_TABLE) as a left join BI_audit_ALL_ref_RELATIONS r on a.RELATION = r.RELATION where r.RELATION is null";
  522. $refPracownicyToPracownicyAdresy = ACL::getRefTable('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY', "default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy");
  523. $queries[] = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID) select all1.ID, all2.ID, rel.ID from BI_audit_ALL as all1 join `{$refPracownicyToPracownicyAdresy}` as ref on all1.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY_adresy' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION";
  524. foreach ($queries as $query) DB::getPDO()->query($query);
  525. $BiAuditRelations = new BiAuditRelations();
  526. $query = "select ID from BI_audit_ALL where BASE = 0";
  527. $result = DB::query($query);
  528. while ($row = DB::fetch($result)) $BiAuditRelations->findRelations($row->ID);
  529. }
  530. public function doReloadCache() {
  531. $powiazaniaDirLocation = $this->getMainDirectory();
  532. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  533. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  534. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  535. file_put_contents($reloadCachePidFile, getmypid());
  536. try {
  537. $this->reloadCache_reTeryt();
  538. $this->reloadCache_updateAll();
  539. file_put_contents($reloadCacheResultFile, "ok");
  540. } catch (Exception $e) {
  541. file_put_contents($reloadCacheResultFile, $e->getMessage());
  542. }
  543. }
  544. public function doGeneratePowiazania($ID) {
  545. $powiazaniaDirLocation = $this->getMainDirectory();
  546. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  547. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  548. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  549. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  550. file_put_contents($pidFile, getmypid());
  551. $tablesConf = [
  552. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  553. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  554. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  555. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  556. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  557. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  558. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  559. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  560. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  561. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  562. ];
  563. try {
  564. $BiAuditPowiazania = new BiAuditPowiazania($ID);
  565. if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  566. file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  567. $BiAuditPowiazania->saveToDb();
  568. /* $powiazania = $BiAuditPowiazania->asArray('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  569. if (!$powiazania) return false;
  570. DB::getPDO()->query($query);
  571. foreach ($powiazania['BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row'] as $row) {
  572. $powiazaniaRowSqlArr = [];
  573. $string_concat_path = [];
  574. foreach ($row['object'] as $i => $object) {
  575. $powiazaniaRowObjectSqlArr = [];
  576. $table = array_keys($object)[0];
  577. if (!isset($tablesConf[$table])) throw new Exception("Błąd danych konfiguracyjnych");
  578. $concat = "table='{$table}'";
  579. if (isset($object['relation_from'])) $concat .= ";relation_from='{$object['relation_from']}'";
  580. foreach ($tablesConf[$table] as $field) {
  581. if ($object[$table][$field]) $concat .= ";{$field}='{$object[$table][$field]}'";
  582. }
  583. if ($i == 0) $powiazaniaRowSqlArr['string_concat_from'] = $concat;
  584. elseif ($i == count($row['object']) - 1) $powiazaniaRowSqlArr['string_concat_to'] = $concat;
  585. else $string_concat_path[] = $concat;
  586. }
  587. $powiazaniaRowSqlArr['string_concat_path'] = implode(' / ', $string_concat_path);
  588. $id_row = DB::getPDO()->insert("BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row", $powiazaniaRowSqlArr);
  589. if (!$id_row) throw new Exception("Błąd bazy danych");
  590. DB::getPDO()->insert('CRM__#REF_TABLE__25', ["PRIMARY_KEY" => $ID, "REMOTE_PRIMARY_KEY" => $id_row]);
  591. }
  592. */
  593. file_put_contents($resultFile, "ok");
  594. } catch (Exception $e) {
  595. file_put_contents($resultFile, $e->getMessage());
  596. }
  597. }
  598. public function reinstallAction() {
  599. $this->reinstall();
  600. die('OK');
  601. }
  602. public function reinstall() {
  603. $sqlList = array();
  604. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  605. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  606. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  607. SQL;
  608. $db = DB::getDB();
  609. if ($db->has_errors()) {
  610. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  611. }
  612. foreach ($sqlList as $sqlName => $sql) {
  613. $res = $db->query($sql);
  614. if ($db->has_errors()) {
  615. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  616. }
  617. }
  618. }
  619. }
  620. class BiAuditRelations {
  621. private $RELATIONS_ID = [];
  622. private $relations = [
  623. 'nip' => ['nip'],
  624. 'regon' => ['regon'],
  625. 'krs' => ['krs'],
  626. 'pesel' => ['pesel'],
  627. 'adres' => ['TERYT_SYM', 'TERYT_SYM_UL', 'nrDomu', 'nrLokalu'],
  628. ];
  629. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  630. private $sourceTable = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  631. public function __construct() {
  632. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  633. $result = DB::getPDO()->fetchAll($query);
  634. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  635. }
  636. private function getRelationID($name) {
  637. if (!isset($this->RELATIONS_ID[$name])) {
  638. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  639. $newID = DB::getPDO()->fetchValue($query);
  640. $this->RELATIONS_ID[$name] = $newID;
  641. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  642. DB::getPDO()->query($query);
  643. }
  644. return $this->RELATIONS_ID[$name];
  645. }
  646. public function findRelations($ID) {
  647. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  648. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  649. $row = $result[0];
  650. $joins = [];
  651. $items = '';
  652. foreach ($this->relations as $name => $columns) {
  653. $ok = 0;
  654. $join = [];
  655. foreach ($columns as $column) {
  656. $join[] = "t1.{$column} = t2.{$column}";
  657. if ($row[$column]) $ok++;
  658. }
  659. if ($ok / count($columns) > 0.5) {
  660. $joins[] = "(" . implode(" and ", $join) . ")";
  661. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  662. }
  663. }
  664. if (!$joins) return false;
  665. $query = "select t2.ID as ID, t1.REMOTE_TABLE as REMOTE_TABLE_1, t2.REMOTE_TABLE as REMOTE_TABLE_2 {$items} " .
  666. "from BI_audit_ALL t1 join BI_audit_ALL t2 on " . implode(" or ", $joins) . " where t1.ID = {$ID} and (t2.BASE = 1 or t2.ID > {$ID})";
  667. $result = DB::getPDO()->fetchAll($query);
  668. foreach ($result as $row) {
  669. $relationID = 0;
  670. foreach ($this->relations as $name => $v) {
  671. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  672. }
  673. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  674. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  675. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  676. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  677. if (!($start2 || $end1)) {
  678. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2})";
  679. DB::getPDO()->query($query);
  680. }
  681. if (!($start1 || $end2)) {
  682. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1})";
  683. DB::getPDO()->query($query);
  684. }
  685. }
  686. }
  687. }
  688. class BiAuditPowiazania {
  689. private $DEPTH;
  690. private $ID;
  691. private $endNodes;
  692. private $path = [];
  693. private $results = [];
  694. private $items_results = [];
  695. private $relations = [];
  696. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  697. public function __construct($ID = 0) {
  698. if (!$ID) throw new Exception("Wrong ID parameter");
  699. $query = "select BI_analiza_depth from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$ID}' and FILE_STATUS = 'IN_PROGRESS' and BI_analiza_reloadCache != 'Y'";
  700. $result = DB::getPDO()->fetchAll($query);
  701. if (!$result) throw new Exception("Błąd danych");
  702. $this->DEPTH = (int) $result[0]['BI_analiza_depth'];
  703. $this->ID = $ID;
  704. $subQueries = [];
  705. foreach ($this->destTables as $destTable) {
  706. $refTable = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "default_db__x3A__{$destTable}:{$destTable}");
  707. $subQueries[] = "select `all`.ID from BI_audit_ALL `all` join `{$refTable}` ref on `all`.REMOTE_TABLE = '{$destTable}' and `all`.REMOTE_ID = ref.REMOTE_PRIMARY_KEY and ref.PRIMARY_KEY = '{$ID}'";
  708. }
  709. $query = implode(" union ", $subQueries);
  710. $result = DB::getPDO()->fetchAll($query);
  711. if (!$result) throw new Exception("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  712. $this->endNodes = array_map('reset', $result);
  713. $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  714. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
  715. $query = "select `all`.ID as ID from BI_audit_ALL `all` join `{$refPowiazaniaToPracownicy}` ref
  716. on `all`.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and `all`.REMOTE_ID = ref.REMOTE_PRIMARY_KEY and ref.PRIMARY_KEY = '{$ID}'";
  717. $result = DB::getPDO()->fetchAll($query);
  718. foreach ($result as $row) $this->findPowiazania($row['ID']);
  719. }
  720. public function findPowiazania($ID, $relation = "", $end = 0) {
  721. if (isset($this->path[$ID])) return false;
  722. $this->path[$ID] = $relation;
  723. if (!$relation) $relation = 0;
  724. if ($end) {
  725. if (in_array($ID, $this->endNodes)) $this->results[] = $this->path;
  726. array_pop($this->path);
  727. return true;
  728. }
  729. if (count($this->path) > $this->DEPTH) {
  730. array_pop($this->path);
  731. return false;
  732. }
  733. $nodes = [];
  734. if ($relation) $where = "and ({$relation} & ref.RELATION_ID) != {$relation}";
  735. else $where = "";
  736. $query = "select ref.ID2, RELATION_ID, END from BI_audit_ALL_ref ref where ref.ID1 = '{$ID}' {$where}";
  737. $result = DB::query($query);
  738. while ($row = DB::fetch($result)) $nodes[$row->ID2] = ['relation' => (int) $row->RELATION_ID, 'end' => $row->END];
  739. foreach ($nodes as $node => $data) $this->findPowiazania($node, $data['relation'], $data['end']);
  740. array_pop($this->path);
  741. }
  742. private function relationName($ID) {
  743. if (!isset($this->relations[$ID])) {
  744. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  745. $result = DB::getPDO()->fetchAll($query);
  746. $rels = array_map('reset', $result);
  747. $this->relations[$ID] = implode(", ", $rels);
  748. }
  749. return $this->relations[$ID];
  750. }
  751. private function generateItemsResults() {
  752. $xmlRoot2 = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  753. $xmlElements = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  754. $this->items_results = [];
  755. $items_kontrahenci = [];
  756. $items_kw_person = [];
  757. $kontrahenci = [];
  758. $kw_person = [];
  759. $refUmowyToKontrahenci = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_UMOWY/BI_audit_ENERGA_RUM_UMOWY', 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI');
  760. $refKwRequestedToKwRequestedPerson = ACL::getRefTable('default_db/BI_audit_KW_requested/BI_audit_KW_requested', 'default_db__x3A__BI_audit_KW_requested_person:BI_audit_KW_requested_person');
  761. foreach ($this->results as $result) {
  762. $item_results = [];
  763. foreach ($result as $ID => $rel) {
  764. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  765. $row = DB::getPDO()->fetchFirst($query);
  766. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  767. $obj = DB::fetch(DB::query($query));
  768. $item_result = [$row['REMOTE_TABLE'] => (array) $obj];
  769. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  770. $item_results['object'][] = $item_result;
  771. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  772. $kontrahenci[] = $row['REMOTE_ID'];
  773. $query = "select umowy.* from BI_audit_ENERGA_RUM_UMOWY umowy join `{$refUmowyToKontrahenci}` ref on umowy.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
  774. $res = DB::query($query);
  775. if (mysql_num_rows($res)) {
  776. $umowy = [];
  777. while ($obj = DB::fetch($res)) $umowy[] = (array) $obj;
  778. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  779. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  780. $items_kontrahenci[] = $item_kontrahenci;
  781. }
  782. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  783. $kw_person[] = $row['REMOTE_ID'];
  784. $query = "select kw.* from BI_audit_KW_requested kw join `{$refKwRequestedToKwRequestedPerson}` ref on kw.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
  785. $res = DB::query($query);
  786. if (mysql_num_rows($res)) {
  787. $kw = [];
  788. while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
  789. $item_kw_person['ID'] = $row['REMOTE_ID'];
  790. $item_kw_person['BI_audit_KW_requested'] = $kw;
  791. $items_kw_person[] = $item_kw_person;
  792. }
  793. }
  794. }
  795. $this->items_results[$xmlRoot2][$xmlElements][] = $item_results;
  796. }
  797. $this->items_results[$xmlRoot2]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  798. $this->items_results[$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;
  799. }
  800. public function saveToDb() {
  801. if (!$this->results) return null;
  802. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  803. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  804. $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
  805. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  806. foreach ($this->results as $result) {
  807. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  808. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  809. foreach ($result as $ID => $rel) {
  810. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  811. $object = DB::getPDO()->fetchFirst($query);
  812. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relations[$rel]]);
  813. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  814. $ref = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
  815. "default_db__x3A__{$object['REMOTE_TABLE']}:{$object['REMOTE_TABLE']}");
  816. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  817. }
  818. }
  819. }
  820. public function asXml() {
  821. if (!$this->results) return null;
  822. if (!$this->items_results) $this->generateItemsResults();
  823. $xmlRoot = "RelatedFeatureRoot";
  824. return V::arrayToXML($this->items_results, true, $xmlRoot);
  825. }
  826. public function asArray($subArray = null) {
  827. if (!$this->results) return null;
  828. if (!$this->items_results) $this->generateItemsResults();
  829. if ($subArray) {
  830. if (isset($this->items_results[$subArray])) return $this->items_results[$subArray];
  831. else return [];
  832. } else return $this->items_results;
  833. }
  834. public function powiazaniaFound() {
  835. if ($this->results) return true;
  836. else return false;
  837. }
  838. }