BiAuditGenerate.php 45 KB

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