BiAuditGenerate.php 45 KB

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