BiAuditGenerate.php 57 KB

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