BiAuditGenerate.php 48 KB

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