BiAuditGenerate.php 45 KB

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