BiAuditGenerate.php 69 KB

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