BiAuditGenerate.php 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632
  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="<?=$_SERVER['HTTP_REFERER']?>" 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 class="form-group">
  705. <div class="col-sm-12">
  706. <div class="containter" style="text-align:center">
  707. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-default">Powrót</a>
  708. </div>
  709. </div>
  710. </div>
  711. </div>
  712. <?php
  713. }
  714. public function defaultAction() {
  715. SE_Layout::gora();
  716. SE_Layout::menu();
  717. if (isset($_SESSION['REFERER'])) {
  718. $this->REFERER = $_SESSION['REFERER'];
  719. unset($_SESSION['REFERER']);
  720. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  721. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  722. if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
  723. elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
  724. elseif (($ID = V::get('ID_BI_audit_KRS', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  725. elseif (($ID = V::get('ID_BI_audit_KRS_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS_person';
  726. if ($this->SOURCE) {
  727. $this->SOURCE['ID'] = $ID;
  728. $this->powiazania();
  729. }
  730. elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
  731. switch ($TABLE) {
  732. case "default_db/BI_audit_ENERGA_PRACOWNICY":
  733. $this->importKrsToPracownicy();
  734. break;
  735. default: SE_Layout::alert('danger', 'Błąd parametru');
  736. }
  737. }
  738. else SE_Layout::alert('danger', 'Błąd parametru');
  739. SE_Layout::dol();
  740. }
  741. private function getRefsTables($namespace) {
  742. try {
  743. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  744. if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
  745. $fields = $item['field'];
  746. $refsTables = [];
  747. foreach ($fields as $field) {
  748. list($type, $child) = explode(":", $field['xsdType'], 2);
  749. if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) $refsTables[] = ACL::getRefTable($namespace, $child);
  750. }
  751. return $refsTables;
  752. } catch (Exception $e) {
  753. echo "{$namespace} - {$e->getMessage}";
  754. return [];
  755. }
  756. }
  757. private function truncatePowiazaniaFromDB($ID) {
  758. $refsTables = $this->getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  759. if (!$refsTables) return null;
  760. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  761. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  762. $refsTables = array_diff($refsTables, [$refPowiazaniaToPowiazaniaRow]);
  763. $query = "delete from `" . implode("`, `", $refsTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  764. foreach ($refsTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  765. $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  766. DB::getPDO()->query($query);
  767. }
  768. private function deleteResultsFromDB($ID) {
  769. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  770. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  771. $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
  772. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  773. $refsTables = $this->getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  774. $sqlDeleteFrom = "delete from
  775. `{$refPowiazaniaToPowiazaniaRow}`,
  776. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
  777. `{$refPowiazaniaRowToPowiazaniaRowObject}`,
  778. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
  779. $sqlUsing = "
  780. using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  781. join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
  782. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
  783. join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
  784. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
  785. $sqlWhere = "
  786. where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  787. foreach ($refsTables as $refTable) {
  788. $sqlDeleteFrom .= ",\n`{$refTable}`";
  789. $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  790. }
  791. $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
  792. DB::getPDO()->query($query);
  793. }
  794. public function doGenerate() {
  795. function generatePhpScript($function) {
  796. return '<?php
  797. ini_set("memory_limit", "4G");
  798. define("DS", DIRECTORY_SEPARATOR);
  799. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  800. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  801. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  802. ini_set("display_startup_errors", "0");
  803. ini_set("log_errors", "1");
  804. ini_set("error_log", "/var/log/apache2/error_log");
  805. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  806. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  807. Lib::loadClass("Router");
  808. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  809. ';
  810. }
  811. try {
  812. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  813. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  814. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  815. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  816. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  817. ### Ustawienie zmiennych
  818. $powiazaniaDirLocation = $this->getMainDirectory();
  819. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  820. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  821. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  822. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  823. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  824. ### Utworzenie niezbędnych katalogów i plików
  825. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0755, true);
  826. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  827. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  828. $doGenerate = true;
  829. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part') and FILE_STATUS = 'TO_GENERATE'";
  830. $result = DB::getPDO()->fetchAll($query);
  831. if ($result) {
  832. $doGenerate = false;
  833. $sqlArr = [];
  834. if (file_exists($reloadCachePhpFile)) {
  835. if (file_exists($reloadCacheResultFile)) {
  836. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  837. if ($reloadCacheResult == "ok") {
  838. $sqlArr = [
  839. 'FILE_STATUS_info' => 'Odświeżono cache, oczekiwanie na wygenerowanie powiązań',
  840. 'BI_analiza_reloadCache' => 'No',
  841. ];
  842. $doGenerate = true;
  843. } else {
  844. $sqlArr = [
  845. 'FILE_STATUS' => 'ERROR',
  846. 'FILE_STATUS_info' => "Wystąpił błąd podczas odświeżania cache ({$reloadCacheResult})",
  847. ];
  848. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  849. $result = DB::getPDO()->fetchAll($query);
  850. }
  851. unlink($reloadCachePhpFile);
  852. unlink($reloadCachePidFile);
  853. unlink($reloadCacheResultFile);
  854. } elseif (file_exists($reloadCachePidFile)) {
  855. $pid = file_get_contents($reloadCachePidFile);
  856. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  857. $processShouldBeRunning = "php {$reloadCachePhpFile}";
  858. if ($processRunning != $processShouldBeRunning) {
  859. if (!file_exists($reloadCacheResultFile)) {
  860. $sqlArr = [
  861. 'FILE_STATUS' => 'ERROR',
  862. 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas odświeżania cache - nie znaleziono procesu potomnego",
  863. ];
  864. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  865. $result = DB::getPDO()->fetchAll($query);
  866. unlink($reloadCachePhpFile);
  867. unlink($reloadCachePidFile);
  868. unlink($reloadCacheResultFile);
  869. }
  870. }
  871. }
  872. } else {
  873. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  874. $result2 = DB::getPDO()->fetchValue($query);
  875. if ($result2) {
  876. $sqlArr = [
  877. 'FILE_STATUS_info' => 'Wstrzymano odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  878. ];
  879. } else {
  880. $sqlArr = [
  881. 'FILE_STATUS_info' => 'W trakcie odświeżania cache',
  882. ];
  883. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
  884. $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
  885. file_put_contents($reloadCachePhpFile, generatePhpScript("doReloadCache({$fullReloadCache})"));
  886. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  887. }
  888. }
  889. if ($sqlArr) {
  890. foreach ($result as $row) {
  891. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  892. }
  893. }
  894. }
  895. ### Generowanie powiązań
  896. if ($doGenerate) {
  897. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
  898. $result = DB::getPDO()->fetchAll($query);
  899. foreach ($result as $row) {
  900. $sqlArr = [
  901. 'ID' => $row['ID'],
  902. 'FILE_STATUS' => 'IN_PROGRESS',
  903. 'FILE_STATUS_info' => 'W trakcie generowania powiązań',
  904. ];
  905. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  906. $this->deleteResultsFromDB($row['ID']);
  907. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  908. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  909. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  910. file_put_contents($generatePowiazaniaPhpFile, generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  911. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  912. }
  913. }
  914. ### Weryfikacja świeżo wygenerowanych powiązań
  915. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  916. $result = DB::getPDO()->fetchAll($query);
  917. foreach ($result as $row) {
  918. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  919. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  920. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  921. $error = false;
  922. $success = false;
  923. $sqlArr = [];
  924. if (file_exists($generatePowiazaniaResultFile)) {
  925. $generatePowiazaniaResult = file_get_contents($generatePowiazaniaResultFile);
  926. if ($generatePowiazaniaResult == "ok") {
  927. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.xml";
  928. if (file_exists($xmlFile)) {
  929. if (filesize($xmlFile)) {
  930. $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  931. if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0777, false);
  932. if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
  933. else $success = true;
  934. } else $error = "Wystąpił nieznany błąd - plk xml został wygenerowany niepoprawnie";
  935. } else $error = "Wystąpił nienzany błąd - nie znaleziono pliku xml";
  936. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult})";
  937. } elseif (file_exists($generatePowiazaniaPidFile)) {
  938. $pid = file_get_contents($generatePowiazaniaPidFile);
  939. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  940. $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
  941. if ($processRunning != $processShouldBeRunning) {
  942. if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
  943. }
  944. }
  945. if ($error) {
  946. $sqlArr = [
  947. 'FILE_STATUS' => 'ERROR',
  948. 'FILE_STATUS_info' => $error,
  949. ];
  950. $this->deleteResultsFromDB($row['ID']);
  951. if (file_exists($xmlFile)) unlink($xmlFile);
  952. } elseif ($success) {
  953. $sqlArr = [
  954. 'FILE_STATUS' => 'GENERATED',
  955. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  956. ];
  957. $destXmlFile = "{$powiazanieDirLocation}/relations.xml";
  958. rename($xmlFile, $destXmlFile);
  959. }
  960. if ($sqlArr) {
  961. $sqlArr['ID'] = $row['ID'];
  962. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  963. if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
  964. if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
  965. if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
  966. }
  967. }
  968. } catch (Exception $e) {
  969. echo $e->getMessage()."\n";
  970. }
  971. }
  972. private function reloadCache_reTeryt($full = false) {
  973. Lib::loadClass('Teryt');
  974. function reTeryt($table) {
  975. $tableConf = [
  976. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  977. 'kodPocztowy' => 'Kod_pocztowy',
  978. 'miejscowosc' => 'Miejscowosc',
  979. 'ulica' => 'Ulica',
  980. ],
  981. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  982. 'kodPocztowy' => 'kodPocztowy',
  983. 'miejscowosc' => 'miejscowosc',
  984. 'ulica' => 'ulica',
  985. ],
  986. 'BI_audit_KRS' => [
  987. 'wojewodztwo' => 'S_wojewodztwo',
  988. 'powiat' => 'S_powiat',
  989. 'gmina' => 'S_gmina',
  990. 'miejscowosc' => 'A_miejscowosc',
  991. 'ulica' => 'A_ulica',
  992. 'kodPocztowy' => 'A_kod',
  993. ],
  994. 'BI_audit_CEIDG' => [
  995. 'wojewodztwo' => 'wojewodztwo',
  996. 'powiat' => 'powiat',
  997. 'gmina' => 'gmina',
  998. 'miejscowosc' => 'miejscowosc',
  999. 'ulica' => 'ulica',
  1000. 'kodPocztowy' => 'kodPocztowy',
  1001. ],
  1002. ];
  1003. $columns = ['kodPocztowy', 'miejscowosc', 'ulica'];
  1004. $query = "select * from `{$table}` where TERYT_SYM is null";
  1005. try {
  1006. $adresy = DB::getPDO()->fetchall($query);
  1007. foreach ($adresy as $adres) {
  1008. $search = [];
  1009. foreach ($columns as $column) $search[$column] = $adres[$tableConf[$table][$column]];
  1010. try {
  1011. $teryt = Teryt::search($search);
  1012. if ($teryt) {
  1013. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  1014. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  1015. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  1016. }
  1017. } catch (Exception $e) {
  1018. }
  1019. }
  1020. } catch (Exception $e) {
  1021. }
  1022. }
  1023. if ($full) {
  1024. reTeryt('BI_audit_KRS');
  1025. reTeryt('BI_audit_CEIDG');
  1026. }
  1027. reTeryt('BI_audit_ENERGA_RUM_KONTRAHENCI');
  1028. reTeryt('BI_audit_ENERGA_PRACOWNICY_adresy');
  1029. }
  1030. private function reloadCache_updateAll($full = false) {
  1031. $tables = [
  1032. 'BI_audit_ENERGA_PRACOWNICY' => [
  1033. 'fields' => [
  1034. 'nip' => 'nip',
  1035. 'regon' => 'regon',
  1036. 'pesel' => 'pesel',
  1037. ],
  1038. 'base' => '0',
  1039. //'where' => '',
  1040. ],
  1041. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1042. 'fields' => [
  1043. 'TERYT_SYM' => 'TERYT_SYM',
  1044. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1045. 'nrDomu' => 'nrBudynku',
  1046. 'nrLokalu' => 'nrLokalu',
  1047. ],
  1048. 'base' => '0',
  1049. //'where' => '',
  1050. ],
  1051. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1052. 'fields' => [
  1053. 'krs' => 'KRS',
  1054. 'nip' => 'NIP',
  1055. 'regon' => 'REGON',
  1056. 'pesel' => 'PESEL',
  1057. 'TERYT_SYM' => 'TERYT_SYM',
  1058. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1059. 'nrDomu' => 'Numer_budynku',
  1060. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  1061. ],
  1062. 'base' => '0',
  1063. 'where' => "ownCompany != 'Y'",
  1064. ],
  1065. 'BI_audit_KW_requested_person' => [
  1066. 'fields' => [
  1067. 'pesel' => 'Seller_person_pesel',
  1068. 'krs' => 'Seller_person_KRS',
  1069. 'nip' => 'Seller_person_NIP',
  1070. 'regon' => 'Seller_person_REGON',
  1071. ],
  1072. 'base' => '0',
  1073. //'where' => '',
  1074. ],
  1075. ];
  1076. $tables_full = [
  1077. 'BI_audit_CEIDG' => [
  1078. 'fields' => [
  1079. 'nip' => 'nip',
  1080. 'regon' => 'regon',
  1081. 'TERYT_SYM' => 'TERYT_SYM',
  1082. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1083. 'nrDomu' => 'budynek',
  1084. 'nrLokalu' => 'lokal',
  1085. ],
  1086. 'base' => '1',
  1087. ],
  1088. 'BI_audit_CEIDG_pelnomocnicy' => [
  1089. 'fields' => [
  1090. 'nip' => 'nip',
  1091. 'TERYT_SYM' => 'TERYT_SYM',
  1092. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1093. 'nrDomu' => 'budynek',
  1094. 'nrLokalu' => 'lokal',
  1095. ],
  1096. 'base' => '1',
  1097. ],
  1098. 'BI_audit_CEIDG_powiazania' => [
  1099. 'fields' => [
  1100. 'nip' => 'nip',
  1101. 'regon' => 'regon',
  1102. ],
  1103. 'base' => '1',
  1104. ],
  1105. 'BI_audit_KRS' => [
  1106. 'fields' => [
  1107. 'krs' => 'krs',
  1108. 'nip' => 'nip',
  1109. 'regon' => 'regon',
  1110. 'TERYT_SYM' => 'TERYT_SYM',
  1111. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1112. 'nrDomu' => 'A_nrDomu',
  1113. 'nrLokalu' => 'A_nrLokalu',
  1114. ],
  1115. 'base' => '1',
  1116. ],
  1117. 'BI_audit_KRS_company' => [
  1118. 'fields' => [
  1119. 'regon' => 'regon',
  1120. 'krs' => 'krs',
  1121. ],
  1122. 'base' => '1',
  1123. ],
  1124. 'BI_audit_KRS_person' => [
  1125. 'fields' => [
  1126. 'pesel' => 'pesel',
  1127. ],
  1128. 'base' => '1',
  1129. ],
  1130. ];
  1131. if ($full) {
  1132. $tables = array_merge($tables_full, $tables);
  1133. $fullWhere = '1 = 1';
  1134. } else {
  1135. $fullWhere = 'BASE = 0';
  1136. }
  1137. $queries[] = "delete from BI_audit_ALL where {$fullWhere}";
  1138. $queries[] = "delete from BI_audit_ALL_ref where {$fullWhere}";
  1139. //$queries[] = "delete from BI_audit_ALL_ref_RELATIONS where {$fullWhere}"; // niepotrzebne
  1140. foreach ($tables as $name => $table) {
  1141. if (isset($table['where']) && $table['where']) $where = "where {$table['where']}";
  1142. else $where = '';
  1143. $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}";
  1144. }
  1145. $queries[] = "update BI_audit_ALL set nip = null where nip = 0";
  1146. $queries[] = "update BI_audit_ALL set regon = null where regon = 0";
  1147. $queries[] = "update BI_audit_ALL set krs = null where krs = 0";
  1148. $queries[] = "update BI_audit_ALL set pesel = null where pesel = 0";
  1149. $queries[] = "update BI_audit_ALL set TERYT_SYM = null where TERYT_SYM = 0";
  1150. $queries[] = "update BI_audit_ALL set TERYT_SYM_UL = null where TERYT_SYM_UL = 0";
  1151. $queries[] = "update BI_audit_ALL set nrDomu = null where trim(nrDomu) = ''";
  1152. $queries[] = "update BI_audit_ALL set nrLokalu = null where trim(nrLokalu) = ''";
  1153. $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}";
  1154. $queries[] = "set @var = (select round(coalesce(max(ID), '0.5'), 1) from BI_audit_ALL_ref_RELATIONS)";
  1155. $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";
  1156. if ($full) {
  1157. $refCeidgToCeidgPelnomocnicy = ACL::getRefTable('default_db/BI_audit_CEIDG/BI_audit_CEIDG', "default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy");
  1158. $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";
  1159. $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";
  1160. $refCeidgToCeidgPowiazania = ACL::getRefTable('default_db/BI_audit_CEIDG/BI_audit_CEIDG', "default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania");
  1161. $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";
  1162. $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";
  1163. $refKrsToKrsCompany = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company");
  1164. $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";
  1165. $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";
  1166. $refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
  1167. $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";
  1168. $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";
  1169. }
  1170. $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");
  1171. $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";
  1172. foreach ($queries as $query) DB::getPDO()->query($query);
  1173. $BiAuditRelations = new BiAuditRelations($full);
  1174. $query = "select ID from BI_audit_ALL where {$fullWhere} order by ID";
  1175. $result = DB::query($query);
  1176. while ($row = DB::fetch($result)) $BiAuditRelations->findRelations($row->ID);
  1177. }
  1178. public function doReloadCache($full = false) {
  1179. $powiazaniaDirLocation = $this->getMainDirectory();
  1180. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1181. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1182. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1183. file_put_contents($reloadCachePidFile, getmypid());
  1184. try {
  1185. $this->reloadCache_reTeryt($full);
  1186. $this->reloadCache_updateAll($full);
  1187. file_put_contents($reloadCacheResultFile, "ok");
  1188. } catch (Exception $e) {
  1189. file_put_contents($reloadCacheResultFile, $e->getMessage());
  1190. }
  1191. }
  1192. public function doGeneratePowiazania($ID) {
  1193. $powiazaniaDirLocation = $this->getMainDirectory();
  1194. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1195. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  1196. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  1197. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  1198. file_put_contents($pidFile, getmypid());
  1199. $tablesConf = [
  1200. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  1201. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  1202. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  1203. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  1204. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  1205. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  1206. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  1207. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  1208. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  1209. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  1210. ];
  1211. try {
  1212. $BiAuditPowiazania = new BiAuditPowiazania($ID);
  1213. if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  1214. file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  1215. $BiAuditPowiazania->saveToDb();
  1216. /* $powiazania = $BiAuditPowiazania->asArray('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  1217. if (!$powiazania) return false;
  1218. DB::getPDO()->query($query);
  1219. foreach ($powiazania['BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row'] as $row) {
  1220. $powiazaniaRowSqlArr = [];
  1221. $string_concat_path = [];
  1222. foreach ($row['object'] as $i => $object) {
  1223. $powiazaniaRowObjectSqlArr = [];
  1224. $table = array_keys($object)[0];
  1225. if (!isset($tablesConf[$table])) throw new Exception("Błąd danych konfiguracyjnych");
  1226. $concat = "table='{$table}'";
  1227. if (isset($object['relation_from'])) $concat .= ";relation_from='{$object['relation_from']}'";
  1228. foreach ($tablesConf[$table] as $field) {
  1229. if ($object[$table][$field]) $concat .= ";{$field}='{$object[$table][$field]}'";
  1230. }
  1231. if ($i == 0) $powiazaniaRowSqlArr['string_concat_from'] = $concat;
  1232. elseif ($i == count($row['object']) - 1) $powiazaniaRowSqlArr['string_concat_to'] = $concat;
  1233. else $string_concat_path[] = $concat;
  1234. }
  1235. $powiazaniaRowSqlArr['string_concat_path'] = implode(' / ', $string_concat_path);
  1236. $id_row = DB::getPDO()->insert("BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row", $powiazaniaRowSqlArr);
  1237. if (!$id_row) throw new Exception("Błąd bazy danych");
  1238. DB::getPDO()->insert('CRM__#REF_TABLE__25', ["PRIMARY_KEY" => $ID, "REMOTE_PRIMARY_KEY" => $id_row]);
  1239. }
  1240. */
  1241. file_put_contents($resultFile, "ok");
  1242. } catch (Exception $e) {
  1243. file_put_contents($resultFile, $e->getMessage());
  1244. }
  1245. }
  1246. public function reinstallAction() {
  1247. $this->reinstall();
  1248. die('OK');
  1249. }
  1250. public function reinstall() {
  1251. $sqlList = array();
  1252. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  1253. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  1254. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  1255. SQL;
  1256. $sqlList['ChangeStructure1'] = <<<SQL
  1257. 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';
  1258. SQL;
  1259. $sqlList['ChangeStructure2'] = <<<SQL
  1260. UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
  1261. SQL;
  1262. $sqlList['ChangeStructure3'] = <<<SQL
  1263. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
  1264. SQL;
  1265. $db = DB::getDB();
  1266. if ($db->has_errors()) {
  1267. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  1268. }
  1269. foreach ($sqlList as $sqlName => $sql) {
  1270. $res = $db->query($sql);
  1271. if ($db->has_errors()) {
  1272. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  1273. }
  1274. }
  1275. }
  1276. }
  1277. class BiAuditRelations {
  1278. private $RELATIONS_ID = [];
  1279. private $full;
  1280. private $relations = [
  1281. 'nip' => ['nip'],
  1282. 'regon' => ['regon'],
  1283. 'krs' => ['krs'],
  1284. 'pesel' => ['pesel'],
  1285. 'adres' => ['TERYT_SYM', 'TERYT_SYM_UL', 'nrDomu', 'nrLokalu'],
  1286. ];
  1287. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1288. private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  1289. public function __construct($full = false) {
  1290. $this->full = $full;
  1291. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  1292. $result = DB::getPDO()->fetchAll($query);
  1293. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  1294. }
  1295. private function getRelationID($name) {
  1296. if (!isset($this->RELATIONS_ID[$name])) {
  1297. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  1298. $newID = DB::getPDO()->fetchValue($query);
  1299. $this->RELATIONS_ID[$name] = $newID;
  1300. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  1301. DB::getPDO()->query($query);
  1302. }
  1303. return $this->RELATIONS_ID[$name];
  1304. }
  1305. public function findRelations($ID) {
  1306. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  1307. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  1308. $row = $result[0];
  1309. $joins = [];
  1310. $items = '';
  1311. foreach ($this->relations as $name => $columns) {
  1312. $ok = 0;
  1313. $join = [];
  1314. foreach ($columns as $column) {
  1315. $join[] = "t1.{$column} = t2.{$column}";
  1316. if ($row[$column]) $ok++;
  1317. }
  1318. if ($ok / count($columns) > 0.5) {
  1319. $joins[] = "(" . implode(" and ", $join) . ")";
  1320. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  1321. }
  1322. }
  1323. if (!$joins) return false;
  1324. if ($this->full) $where = "where t1.ID = {$ID} and t2.ID > {$ID}";
  1325. else $where = "where t1.ID = {$ID} and (t2.BASE = 1 or t2.ID > {$ID})";
  1326. $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 " .
  1327. "from BI_audit_ALL t1 join BI_audit_ALL t2 on " . implode(" or ", $joins) . " {$where}";
  1328. $result = DB::getPDO()->fetchAll($query);
  1329. foreach ($result as $row) {
  1330. $relationID = 0;
  1331. foreach ($this->relations as $name => $v) {
  1332. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  1333. }
  1334. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  1335. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  1336. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  1337. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  1338. if (!($start2 || $end1)) {
  1339. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
  1340. DB::getPDO()->query($query);
  1341. }
  1342. if (!($start1 || $end2)) {
  1343. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
  1344. DB::getPDO()->query($query);
  1345. }
  1346. }
  1347. }
  1348. }
  1349. class BiAuditPowiazania {
  1350. private $DEPTH;
  1351. private $ID;
  1352. private $endNodes;
  1353. private $path = [];
  1354. private $results = [];
  1355. private $items_results = [];
  1356. private $relations = [];
  1357. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1358. public function __construct($ID = 0) {
  1359. if (!$ID) throw new Exception("Wrong ID parameter");
  1360. $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')";
  1361. $result = DB::getPDO()->fetchAll($query);
  1362. if (!$result) throw new Exception("Błąd danych");
  1363. $this->DEPTH = (int) $result[0]['BI_analiza_depth'];
  1364. $this->ID = $ID;
  1365. $subQueries = [];
  1366. foreach ($this->destTables as $destTable) {
  1367. $refTable = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "default_db__x3A__{$destTable}:{$destTable}");
  1368. $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}'";
  1369. }
  1370. $query = implode(" union ", $subQueries);
  1371. $result = DB::getPDO()->fetchAll($query);
  1372. if (!$result) throw new Exception("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  1373. $this->endNodes = array_map('reset', $result);
  1374. $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  1375. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
  1376. $query = "select `all`.ID as ID from BI_audit_ALL `all` join `{$refPowiazaniaToPracownicy}` ref
  1377. on `all`.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and `all`.REMOTE_ID = ref.REMOTE_PRIMARY_KEY and ref.PRIMARY_KEY = '{$ID}'";
  1378. $result = DB::getPDO()->fetchAll($query);
  1379. foreach ($result as $row) $this->findPowiazania($row['ID']);
  1380. }
  1381. public function findPowiazania($ID, $relation = "", $end = 0) {
  1382. if (isset($this->path[$ID])) return false;
  1383. $this->path[$ID] = $relation;
  1384. if (!$relation) $relation = 0;
  1385. if ($end) {
  1386. if (in_array($ID, $this->endNodes)) $this->results[] = $this->path;
  1387. array_pop($this->path);
  1388. return true;
  1389. }
  1390. if (count($this->path) > $this->DEPTH) {
  1391. array_pop($this->path);
  1392. return false;
  1393. }
  1394. $nodes = [];
  1395. if ($relation) $where = "and ({$relation} & ref.RELATION_ID) != {$relation}";
  1396. else $where = "";
  1397. $query = "select ref.ID2, RELATION_ID, END from BI_audit_ALL_ref ref where ref.ID1 = '{$ID}' {$where}";
  1398. $result = DB::query($query);
  1399. while ($row = DB::fetch($result)) $nodes[$row->ID2] = ['relation' => (int) $row->RELATION_ID, 'end' => $row->END];
  1400. foreach ($nodes as $node => $data) $this->findPowiazania($node, $data['relation'], $data['end']);
  1401. array_pop($this->path);
  1402. }
  1403. private function relationName($ID) {
  1404. if (!isset($this->relations[$ID])) {
  1405. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  1406. $result = DB::getPDO()->fetchAll($query);
  1407. $rels = array_map('reset', $result);
  1408. $this->relations[$ID] = implode(", ", $rels);
  1409. }
  1410. return $this->relations[$ID];
  1411. }
  1412. private function generateItemsResults() {
  1413. $xmlRoot2 = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  1414. $xmlElements = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  1415. $this->items_results = [];
  1416. $items_kontrahenci = [];
  1417. $items_kw_person = [];
  1418. $kontrahenci = [];
  1419. $kw_person = [];
  1420. $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');
  1421. $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');
  1422. foreach ($this->results as $result) {
  1423. $item_results = [];
  1424. foreach ($result as $ID => $rel) {
  1425. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  1426. $row = DB::getPDO()->fetchFirst($query);
  1427. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  1428. $obj = DB::fetch(DB::query($query));
  1429. $item_result = [$row['REMOTE_TABLE'] => (array) $obj];
  1430. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  1431. $item_results['object'][] = $item_result;
  1432. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  1433. $kontrahenci[] = $row['REMOTE_ID'];
  1434. $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']}'";
  1435. $res = DB::query($query);
  1436. if (mysql_num_rows($res)) {
  1437. $umowy = [];
  1438. while ($obj = DB::fetch($res)) $umowy[] = (array) $obj;
  1439. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  1440. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  1441. $items_kontrahenci[] = $item_kontrahenci;
  1442. }
  1443. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  1444. $kw_person[] = $row['REMOTE_ID'];
  1445. $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']}'";
  1446. $res = DB::query($query);
  1447. if (mysql_num_rows($res)) {
  1448. $kw = [];
  1449. while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
  1450. $item_kw_person['ID'] = $row['REMOTE_ID'];
  1451. $item_kw_person['BI_audit_KW_requested'] = $kw;
  1452. $items_kw_person[] = $item_kw_person;
  1453. }
  1454. }
  1455. }
  1456. $this->items_results[$xmlRoot2][$xmlElements][] = $item_results;
  1457. }
  1458. $this->items_results[$xmlRoot2]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  1459. $this->items_results[$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;
  1460. }
  1461. public function saveToDb() {
  1462. if (!$this->results) return null;
  1463. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  1464. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  1465. $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
  1466. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  1467. foreach ($this->results as $result) {
  1468. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  1469. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  1470. foreach ($result as $ID => $rel) {
  1471. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  1472. $object = DB::getPDO()->fetchFirst($query);
  1473. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relations[$rel]]);
  1474. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  1475. $ref = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
  1476. "default_db__x3A__{$object['REMOTE_TABLE']}:{$object['REMOTE_TABLE']}");
  1477. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  1478. }
  1479. }
  1480. }
  1481. public function asXml() {
  1482. if (!$this->results) return null;
  1483. if (!$this->items_results) $this->generateItemsResults();
  1484. $xmlRoot = "RelatedFeatureRoot";
  1485. return V::arrayToXML($this->items_results, true, $xmlRoot);
  1486. }
  1487. public function asArray($subArray = null) {
  1488. if (!$this->results) return null;
  1489. if (!$this->items_results) $this->generateItemsResults();
  1490. if ($subArray) {
  1491. if (isset($this->items_results[$subArray])) return $this->items_results[$subArray];
  1492. else return [];
  1493. } else return $this->items_results;
  1494. }
  1495. public function powiazaniaFound() {
  1496. if ($this->results) return true;
  1497. else return false;
  1498. }
  1499. }