BiAuditGenerate.php 48 KB

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