BiAuditGenerate.php 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  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. default: throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate");
  355. }
  356. } catch (Exception $e) {
  357. SE_Layout::alert('danger',$e->getMessage());
  358. $_SESSION['REFERER'] = $this->REFERER;
  359. ?>
  360. <div class="container" style="text-align:center">
  361. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
  362. </div>
  363. <?php
  364. }
  365. }
  366. private function importKrsToPracownicy() {
  367. $action = V::get('action', '', $_POST);
  368. switch ($action) {
  369. case "search":
  370. $this->importKrsToPracownicySearch();
  371. break;
  372. default: $this->importKrsToPracownicyForm();
  373. }
  374. }
  375. private function importKrsToPracownicyForm() {
  376. ?>
  377. <div class="container" style="margin-top:20px">
  378. <legend>
  379. Importowanie osób z KRS do tabeli pracowników
  380. </legend>
  381. <div class="form-group">
  382. <div class="col-sm-12">
  383. <h4>Znajdź podmiot</h4>
  384. </div>
  385. </div>
  386. <form class="form-horizontal" method="post">
  387. <div class="form-group">
  388. <label class="col-sm-1 control-label">Nazwa</label>
  389. <div class="col-sm-4">
  390. <input type="text" class="form-control" name="nazwa" title="Podaj nazwę podmiotu">
  391. </div>
  392. </div>
  393. <div class="form-group">
  394. <label class="col-sm-1 control-label">KRS</label>
  395. <div class="col-sm-2">
  396. <input type="text" class="form-control" name="krs" pattern="^[0-9]{0,10}$" title="Podaj KRS"/>
  397. </div>
  398. </div>
  399. <div class="form-group">
  400. <label class="col-sm-1 control-label">NIP</label>
  401. <div class="col-sm-2">
  402. <input type="text" class="form-control" name="nip" pattern="^[0-9]{0,10}$" title="Podaj NIP (bez kresek i bez oznaczenia kraju)"/>
  403. </div>
  404. </div>
  405. <div class="form-group">
  406. <label class="col-sm-1 control-label">Regon</label>
  407. <div class="col-sm-2">
  408. <input type="text" class="form-control" name="regon" pattern="^[0-9]{0,9}$" title="Podaj regon"/>
  409. </div>
  410. </div>
  411. <div class="form-group">
  412. <div class="col-sm-offset-1 col-sm-11">
  413. <button type="submit" class="btn btn-primary" name="action" value="search">Szukaj</button>
  414. </div>
  415. </div>
  416. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  417. </form>
  418. </div>
  419. <?php
  420. }
  421. private function importKrsToPracownicySearch() {
  422. try {
  423. $subaction = V::get('subaction', '', $_POST);
  424. switch ($subaction) {
  425. case "listKrsPerson":
  426. $krsId = V::get('krsId', 0, $_POST, int);
  427. break;
  428. case "addKrsPersonToPracownicy":
  429. $personId = V::get('personId', [], $_POST);
  430. if (!$personId) throw new Exception("Błąd formularza");
  431. $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) . ")";
  432. DB::getPDO()->query($query);
  433. SE_Layout::alert('success', "Pomyślnie zaimportowano " . count($personId) . " pracownik" . ((count($personId) == 1) ? "a" : "ów"));
  434. $this->importKrsToPracownicyForm();
  435. return;
  436. default:
  437. $krsId = null;
  438. }
  439. if ($krsId) {
  440. $where = ["ID = '{$krsId}'"];
  441. } else {
  442. $items = [
  443. "nazwa" => 'like',
  444. "krs" => '=',
  445. "nip" => '=',
  446. "regon" => '=',
  447. ];
  448. $form = [];
  449. foreach ($items as $item => $type) {
  450. if ($param = V::get($item, '', $_POST)) {
  451. if ($type == 'like') $param = "%{$param}%";
  452. $form[$item] = DB::getPDO()->quote($param);
  453. }
  454. }
  455. if (!$form) throw new Exception("Nie wypełniono żadnego pola wyszukiwania!");
  456. $where = [];
  457. foreach ($form as $name => $value) $where[] = "`{$name}` {$items[$name]} {$value}";
  458. }
  459. } catch (Exception $e) {
  460. SE_Layout::alert('danger', $e->getMessage());
  461. $this->importKrsToPracownicyForm();
  462. return;
  463. }
  464. $query = "select * from `BI_audit_KRS` where " . implode(" and ", $where) . "order by ID limit 1001";
  465. $result = DB::getPDO()->fetchAll($query);
  466. if (count($result) == 1001) {
  467. SE_Layout::alert('danger', 'Znaleziono zbyt wiele wyników. Doprecyzuj parametry wyszukiwania.');
  468. $this->importKrsToPracownicyForm();
  469. return;
  470. } elseif (count($result) == 1) {
  471. $krsId = $result[0]['ID'];
  472. }
  473. ?>
  474. <div class="container" style="margin-top:20px">
  475. <form method="post">
  476. <legend>
  477. Importowanie osób z KRS do tabeli pracowników
  478. </legend>
  479. <div class="form-group">
  480. <div class="col-sm-12">
  481. <h4>Znalezione podmioty:</h4>
  482. </div>
  483. </div>
  484. <div class="form-group">
  485. <div class="col-sm-12">
  486. <table class="table table-bordered table-hover table-striped" height=5>
  487. <thead>
  488. <tr style="text-align:center; background-color:lightgray">
  489. <td width=1>Lp.</td>
  490. <td>Nazwa</td>
  491. <td>Adres</td>
  492. <td>KRS</td>
  493. <td>NIP</td>
  494. <td>Regon</td>
  495. <?php
  496. if (count($result) > 1) {
  497. ?>
  498. <td width=1>Wybierz</td>
  499. <?php
  500. }
  501. ?>
  502. </tr>
  503. </thead>
  504. <tbody>
  505. <?php
  506. if (!$result) echo '<tr><td align="center" colspan="7">Nie znaleziono podmiotu</td></tr>';
  507. else {
  508. $lp = 1;
  509. foreach ($result as $row) {
  510. $adres = $row['A_miejscowosc'];
  511. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  512. if ($row['A_nrDomu']) {
  513. $adres .= " {$row['A_nrDomu']}";
  514. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  515. }
  516. ?>
  517. <tr>
  518. <td align="right"><?=$lp++?></td>
  519. <td><?=$row['nazwa']?></td>
  520. <td><?=$adres?></td>
  521. <td><?=$row['krs']?></td>
  522. <td><?=$row['nip']?></td>
  523. <td><?=$row['regon']?></td>
  524. <?php
  525. if (count($result) > 1) {
  526. ?>
  527. <td align="center">
  528. <input type="radio" name="krsId" value="<?=$row['ID']?>"/>
  529. </td>
  530. <?php
  531. }
  532. ?>
  533. </tr>
  534. <?php
  535. }
  536. }
  537. ?>
  538. </tbody>
  539. </table>
  540. </div>
  541. </div>
  542. <?php
  543. if (count($result) > 1) {
  544. ?>
  545. <div class="form-group">
  546. <div class="col-sm-12">
  547. <?php
  548. foreach (array_keys($items) as $item) {
  549. ?>
  550. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  551. <?php
  552. }
  553. ?>
  554. <div class="containter" style="text-align:center">
  555. <button type="submit" class="btn btn-primary" name="subaction" value="listKrsPerson">Znajdź osoby powiązane z podmiotem</button>
  556. <a href="" class="btn btn-default">Powrót</a>
  557. </div>
  558. </div>
  559. </div>
  560. <?php
  561. } elseif ($krsId) {
  562. ?>
  563. <div class="form-group">
  564. <div class="col-sm-12">
  565. <h4>Znalezione osoby:</h4>
  566. </div>
  567. </div>
  568. <div class="form-group">
  569. <div class="col-sm-12">
  570. <table class="table table-bordered table-hover table-striped" height=5>
  571. <thead>
  572. <tr style="text-align:center; background-color:lightgray">
  573. <td width=1>Lp.</td>
  574. <td>Nazwisko</td>
  575. <td>Imiona</td>
  576. <td>Pesel</td>
  577. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  578. </tr>
  579. </thead>
  580. <tbody>
  581. <?php
  582. $refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
  583. $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}'";
  584. $result = DB::getPDO()->fetchAll($query);
  585. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono osób powiązanych z podmiotem</td></tr>';
  586. else {
  587. $lp = 1;
  588. foreach ($result as $row) {
  589. ?>
  590. <tr<?=($row['pracownicyId'] ? ' style="color:darkgrey"' : '')?>>
  591. <td align="right"><?=$lp++?></td>
  592. <td><?=$row['nazwisko']?></td>
  593. <td><?=$row['imiona']?></td>
  594. <td><?=$row['pesel']?></td>
  595. <td><input type="checkbox" name="personId[]" value="<?=$row['ID']?>" onClick="toggle(this)" <?=($row['pracownicyId'] ? "disabled" : "")?>/></td>
  596. </tr>
  597. <?php
  598. }
  599. }
  600. ?>
  601. </tbody>
  602. </table>
  603. <div class="containter" style="text-align:center">
  604. <button type="submit" class="btn btn-primary" name="subaction" value="addKrsPersonToPracownicy" onClick="return validate(this)">Dodaj zaznaczone osoby do tabeli pracowników</button>
  605. <a href="" class="btn btn-default">Powrót</a>
  606. </div>
  607. </div>
  608. </div>
  609. <?php
  610. }
  611. ?>
  612. <input type="hidden" name="action" value="search">
  613. </form>
  614. </div>
  615. <script language="JavaScript">
  616. <!--
  617. function toggleAll(source) {
  618. checkboxes = document.getElementsByName('personId[]');
  619. checked = false;
  620. for(var i=0, n=checkboxes.length;i<n;i++) {
  621. if (!checkboxes[i].disabled) {
  622. checkboxes[i].checked = source.checked;
  623. checked = true;
  624. }
  625. }
  626. if (source.checked && (!checked)) source.checked = false;
  627. }
  628. function toggle(source) {
  629. checkboxes = document.getElementsByName('personId[]');
  630. all = true;
  631. for(var i=0, n=checkboxes.length;i<n;i++) if(!checkboxes[i].disabled && checkboxes[i].checked == false) all = false;
  632. source.form['checkAll'].checked = all;
  633. }
  634. function validate(source) {
  635. checkboxes = document.getElementsByName('personId[]');
  636. checked = false;
  637. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked) checked = true;
  638. if (!checked) alert('Nie wybrano żadnej osoby!');
  639. return checked;
  640. }
  641. -->
  642. </script>
  643. <?php
  644. }
  645. public function defaultAction() {
  646. SE_Layout::gora();
  647. SE_Layout::menu();
  648. if (isset($_SESSION['REFERER'])) {
  649. $this->REFERER = $_SESSION['REFERER'];
  650. unset($_SESSION['REFERER']);
  651. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  652. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  653. if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
  654. elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
  655. if ($this->SOURCE) {
  656. $this->SOURCE['ID'] = $ID;
  657. $this->powiazania();
  658. }
  659. elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
  660. switch ($TABLE) {
  661. case "default_db/BI_audit_ENERGA_PRACOWNICY":
  662. $this->importKrsToPracownicy();
  663. break;
  664. default: SE_Layout::alert('danger', 'Błąd parametru');
  665. }
  666. }
  667. else SE_Layout::alert('danger', 'Błąd parametru');
  668. SE_Layout::dol();
  669. }
  670. private function getRefsTables($namespace) {
  671. try {
  672. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  673. if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
  674. $fields = $item['field'];
  675. $refsTables = [];
  676. foreach ($fields as $field) {
  677. list($type, $child) = explode(":", $field['xsdType'], 2);
  678. if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) $refsTables[] = ACL::getRefTable($namespace, $child);
  679. }
  680. return $refsTables;
  681. } catch (Exception $e) {
  682. echo "{$namespace} - {$e->getMessage}";
  683. return [];
  684. }
  685. }
  686. private function truncatePowiazaniaFromDB($ID) {
  687. $refsTables = $this->getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  688. if (!$refsTables) return null;
  689. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  690. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  691. $refsTables = array_diff($refsTables, [$refPowiazaniaToPowiazaniaRow]);
  692. $query = "delete from `" . implode("`, `", $refsTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  693. foreach ($refsTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  694. $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  695. DB::getPDO()->query($query);
  696. }
  697. private function deleteResultsFromDB($ID) {
  698. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  699. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  700. $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
  701. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  702. $refsTables = $this->getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  703. $sqlDeleteFrom = "delete from
  704. `{$refPowiazaniaToPowiazaniaRow}`,
  705. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
  706. `{$refPowiazaniaRowToPowiazaniaRowObject}`,
  707. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
  708. $sqlUsing = "
  709. using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  710. join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
  711. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
  712. join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
  713. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
  714. $sqlWhere = "
  715. where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  716. foreach ($refsTables as $refTable) {
  717. $sqlDeleteFrom .= ",\n`{$refTable}`";
  718. $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  719. }
  720. $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
  721. DB::getPDO()->query($query);
  722. }
  723. public function doGenerate() {
  724. function generatePhpScript($function) {
  725. return '<?php
  726. ini_set("memory_limit", "4G");
  727. define("DS", DIRECTORY_SEPARATOR);
  728. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  729. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  730. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  731. ini_set("display_startup_errors", "0");
  732. ini_set("log_errors", "1");
  733. ini_set("error_log", "/var/log/apache2/error_log");
  734. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  735. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  736. Lib::loadClass("Router");
  737. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  738. ';
  739. }
  740. try {
  741. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  742. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  743. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  744. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  745. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  746. ### Ustawienie zmiennych
  747. $powiazaniaDirLocation = $this->getMainDirectory();
  748. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  749. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  750. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  751. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  752. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  753. ### Utworzenie niezbędnych katalogów i plików
  754. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0755, true);
  755. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  756. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  757. $doGenerate = true;
  758. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part') and FILE_STATUS = 'TO_GENERATE'";
  759. $result = DB::getPDO()->fetchAll($query);
  760. if ($result) {
  761. $doGenerate = false;
  762. $sqlArr = [];
  763. if (file_exists($reloadCachePhpFile)) {
  764. if (file_exists($reloadCacheResultFile)) {
  765. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  766. if ($reloadCacheResult == "ok") {
  767. $sqlArr = [
  768. 'FILE_STATUS_info' => 'Odświeżono cache, oczekiwanie na wygenerowanie powiązań',
  769. 'BI_analiza_reloadCache' => 'No',
  770. ];
  771. $doGenerate = true;
  772. } else {
  773. $sqlArr = [
  774. 'FILE_STATUS' => 'ERROR',
  775. 'FILE_STATUS_info' => "Wystąpił błąd podczas odświeżania cache ({$reloadCacheResult})",
  776. ];
  777. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  778. $result = DB::getPDO()->fetchAll($query);
  779. }
  780. unlink($reloadCachePhpFile);
  781. unlink($reloadCachePidFile);
  782. unlink($reloadCacheResultFile);
  783. } elseif (file_exists($reloadCachePidFile)) {
  784. $pid = file_get_contents($reloadCachePidFile);
  785. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  786. $processShouldBeRunning = "php {$reloadCachePhpFile}";
  787. if ($processRunning != $processShouldBeRunning) {
  788. if (!file_exists($reloadCacheResultFile)) {
  789. $sqlArr = [
  790. 'FILE_STATUS' => 'ERROR',
  791. 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas odświeżania cache - nie znaleziono procesu potomnego",
  792. ];
  793. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  794. $result = DB::getPDO()->fetchAll($query);
  795. unlink($reloadCachePhpFile);
  796. unlink($reloadCachePidFile);
  797. unlink($reloadCacheResultFile);
  798. }
  799. }
  800. }
  801. } else {
  802. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  803. $result2 = DB::getPDO()->fetchValue($query);
  804. if ($result2) {
  805. $sqlArr = [
  806. 'FILE_STATUS_info' => 'Wstrzymano odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  807. ];
  808. } else {
  809. $sqlArr = [
  810. 'FILE_STATUS_info' => 'W trakcie odświeżania cache',
  811. ];
  812. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
  813. $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
  814. file_put_contents($reloadCachePhpFile, generatePhpScript("doReloadCache({$fullReloadCache})"));
  815. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  816. }
  817. }
  818. if ($sqlArr) {
  819. foreach ($result as $row) {
  820. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  821. }
  822. }
  823. }
  824. ### Generowanie powiązań
  825. if ($doGenerate) {
  826. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
  827. $result = DB::getPDO()->fetchAll($query);
  828. foreach ($result as $row) {
  829. $sqlArr = [
  830. 'ID' => $row['ID'],
  831. 'FILE_STATUS' => 'IN_PROGRESS',
  832. 'FILE_STATUS_info' => 'W trakcie generowania powiązań',
  833. ];
  834. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  835. $this->deleteResultsFromDB($row['ID']);
  836. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  837. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  838. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  839. file_put_contents($generatePowiazaniaPhpFile, generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  840. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  841. }
  842. }
  843. ### Weryfikacja świeżo wygenerowanych powiązań
  844. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  845. $result = DB::getPDO()->fetchAll($query);
  846. foreach ($result as $row) {
  847. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  848. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  849. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  850. $error = false;
  851. $success = false;
  852. $sqlArr = [];
  853. if (file_exists($generatePowiazaniaResultFile)) {
  854. $generatePowiazaniaResult = file_get_contents($generatePowiazaniaResultFile);
  855. if ($generatePowiazaniaResult == "ok") {
  856. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.xml";
  857. if (file_exists($xmlFile)) {
  858. if (filesize($xmlFile)) {
  859. $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  860. if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0777, false);
  861. if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
  862. else $success = true;
  863. } else $error = "Wystąpił nieznany błąd - plk xml został wygenerowany niepoprawnie";
  864. } else $error = "Wystąpił nienzany błąd - nie znaleziono pliku xml";
  865. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult})";
  866. } elseif (file_exists($generatePowiazaniaPidFile)) {
  867. $pid = file_get_contents($generatePowiazaniaPidFile);
  868. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  869. $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
  870. if ($processRunning != $processShouldBeRunning) {
  871. if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
  872. }
  873. }
  874. if ($error) {
  875. $sqlArr = [
  876. 'FILE_STATUS' => 'ERROR',
  877. 'FILE_STATUS_info' => $error,
  878. ];
  879. $this->deleteResultsFromDB($row['ID']);
  880. if (file_exists($xmlFile)) unlink($xmlFile);
  881. } elseif ($success) {
  882. $sqlArr = [
  883. 'FILE_STATUS' => 'GENERATED',
  884. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  885. ];
  886. $destXmlFile = "{$powiazanieDirLocation}/relations.xml";
  887. rename($xmlFile, $destXmlFile);
  888. }
  889. if ($sqlArr) {
  890. $sqlArr['ID'] = $row['ID'];
  891. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  892. if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
  893. if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
  894. if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
  895. }
  896. }
  897. } catch (Exception $e) {
  898. echo $e->getMessage()."\n";
  899. }
  900. }
  901. private function reloadCache_reTeryt($full = false) {
  902. Lib::loadClass('Teryt');
  903. function reTeryt($table) {
  904. $tableConf = [
  905. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  906. 'kodPocztowy' => 'Kod_pocztowy',
  907. 'miejscowosc' => 'Miejscowosc',
  908. 'ulica' => 'Ulica',
  909. ],
  910. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  911. 'kodPocztowy' => 'kodPocztowy',
  912. 'miejscowosc' => 'miejscowosc',
  913. 'ulica' => 'ulica',
  914. ],
  915. 'BI_audit_KRS' => [
  916. 'wojewodztwo' => 'S_wojewodztwo',
  917. 'powiat' => 'S_powiat',
  918. 'gmina' => 'S_gmina',
  919. 'miejscowosc' => 'A_miejscowosc',
  920. 'ulica' => 'A_ulica',
  921. 'kodPocztowy' => 'A_kod',
  922. ],
  923. 'BI_audit_CEIDG' => [
  924. 'wojewodztwo' => 'wojewodztwo',
  925. 'powiat' => 'powiat',
  926. 'gmina' => 'gmina',
  927. 'miejscowosc' => 'miejscowosc',
  928. 'ulica' => 'ulica',
  929. 'kodPocztowy' => 'kodPocztowy',
  930. ],
  931. ];
  932. $columns = ['kodPocztowy', 'miejscowosc', 'ulica'];
  933. $query = "select * from `{$table}` where TERYT_SYM is null";
  934. try {
  935. $adresy = DB::getPDO()->fetchall($query);
  936. foreach ($adresy as $adres) {
  937. $search = [];
  938. foreach ($columns as $column) $search[$column] = $adres[$tableConf[$table][$column]];
  939. try {
  940. $teryt = Teryt::search($search);
  941. if ($teryt) {
  942. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  943. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  944. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  945. }
  946. } catch (Exception $e) {
  947. }
  948. }
  949. } catch (Exception $e) {
  950. }
  951. }
  952. if ($full) {
  953. reTeryt('BI_audit_KRS');
  954. reTeryt('BI_audit_CEIDG');
  955. }
  956. reTeryt('BI_audit_ENERGA_RUM_KONTRAHENCI');
  957. reTeryt('BI_audit_ENERGA_PRACOWNICY_adresy');
  958. }
  959. private function reloadCache_updateAll($full = false) {
  960. $tables = [
  961. 'BI_audit_ENERGA_PRACOWNICY' => [
  962. 'fields' => [
  963. 'nip' => 'nip',
  964. 'regon' => 'regon',
  965. 'pesel' => 'pesel',
  966. ],
  967. 'base' => '0',
  968. //'where' => '',
  969. ],
  970. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  971. 'fields' => [
  972. 'TERYT_SYM' => 'TERYT_SYM',
  973. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  974. 'nrDomu' => 'nrBudynku',
  975. 'nrLokalu' => 'nrLokalu',
  976. ],
  977. 'base' => '0',
  978. //'where' => '',
  979. ],
  980. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  981. 'fields' => [
  982. 'krs' => 'KRS',
  983. 'nip' => 'NIP',
  984. 'regon' => 'REGON',
  985. 'pesel' => 'PESEL',
  986. 'TERYT_SYM' => 'TERYT_SYM',
  987. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  988. 'nrDomu' => 'Numer_budynku',
  989. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  990. ],
  991. 'base' => '0',
  992. 'where' => "ownCompany != 'Y'",
  993. ],
  994. 'BI_audit_KW_requested_person' => [
  995. 'fields' => [
  996. 'pesel' => 'Seller_person_pesel',
  997. 'krs' => 'Seller_person_KRS',
  998. 'nip' => 'Seller_person_NIP',
  999. 'regon' => 'Seller_person_REGON',
  1000. ],
  1001. 'base' => '0',
  1002. //'where' => '',
  1003. ],
  1004. ];
  1005. $tables_full = [
  1006. 'BI_audit_CEIDG' => [
  1007. 'fields' => [
  1008. 'nip' => 'nip',
  1009. 'regon' => 'regon',
  1010. 'TERYT_SYM' => 'TERYT_SYM',
  1011. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1012. 'nrDomu' => 'budynek',
  1013. 'nrLokalu' => 'lokal',
  1014. ],
  1015. 'base' => '1',
  1016. ],
  1017. 'BI_audit_CEIDG_pelnomocnicy' => [
  1018. 'fields' => [
  1019. 'nip' => 'nip',
  1020. 'TERYT_SYM' => 'TERYT_SYM',
  1021. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1022. 'nrDomu' => 'budynek',
  1023. 'nrLokalu' => 'lokal',
  1024. ],
  1025. 'base' => '1',
  1026. ],
  1027. 'BI_audit_CEIDG_powiazania' => [
  1028. 'fields' => [
  1029. 'nip' => 'nip',
  1030. 'regon' => 'regon',
  1031. ],
  1032. 'base' => '1',
  1033. ],
  1034. 'BI_audit_KRS' => [
  1035. 'fields' => [
  1036. 'krs' => 'krs',
  1037. 'nip' => 'nip',
  1038. 'regon' => 'regon',
  1039. 'TERYT_SYM' => 'TERYT_SYM',
  1040. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1041. 'nrDomu' => 'A_nrDomu',
  1042. 'nrLokalu' => 'A_nrLokalu',
  1043. ],
  1044. 'base' => '1',
  1045. ],
  1046. 'BI_audit_KRS_company' => [
  1047. 'fields' => [
  1048. 'regon' => 'regon',
  1049. 'krs' => 'krs',
  1050. ],
  1051. 'base' => '1',
  1052. ],
  1053. 'BI_audit_KRS_person' => [
  1054. 'fields' => [
  1055. 'pesel' => 'pesel',
  1056. ],
  1057. 'base' => '1',
  1058. ],
  1059. ];
  1060. if ($full) {
  1061. $tables = array_merge($tables_full, $tables);
  1062. $fullWhere = '1 = 1';
  1063. } else {
  1064. $fullWhere = 'BASE = 0';
  1065. }
  1066. $queries[] = "delete from BI_audit_ALL where {$fullWhere}";
  1067. $queries[] = "delete from BI_audit_ALL_ref where {$fullWhere}";
  1068. //$queries[] = "delete from BI_audit_ALL_ref_RELATIONS where {$fullWhere}"; // niepotrzebne
  1069. foreach ($tables as $name => $table) {
  1070. if (isset($table['where']) && $table['where']) $where = "where {$table['where']}";
  1071. else $where = '';
  1072. $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}";
  1073. }
  1074. $queries[] = "update BI_audit_ALL set nip = null where nip = 0";
  1075. $queries[] = "update BI_audit_ALL set regon = null where regon = 0";
  1076. $queries[] = "update BI_audit_ALL set krs = null where krs = 0";
  1077. $queries[] = "update BI_audit_ALL set pesel = null where pesel = 0";
  1078. $queries[] = "update BI_audit_ALL set TERYT_SYM = null where TERYT_SYM = 0";
  1079. $queries[] = "update BI_audit_ALL set TERYT_SYM_UL = null where TERYT_SYM_UL = 0";
  1080. $queries[] = "update BI_audit_ALL set nrDomu = null where trim(nrDomu) = ''";
  1081. $queries[] = "update BI_audit_ALL set nrLokalu = null where trim(nrLokalu) = ''";
  1082. $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}";
  1083. $queries[] = "set @var = (select round(coalesce(max(ID), '0.5'), 1) from BI_audit_ALL_ref_RELATIONS)";
  1084. $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";
  1085. if ($full) {
  1086. $refCeidgToCeidgPelnomocnicy = ACL::getRefTable('default_db/BI_audit_CEIDG/BI_audit_CEIDG', "default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy");
  1087. $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";
  1088. $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";
  1089. $refCeidgToCeidgPowiazania = ACL::getRefTable('default_db/BI_audit_CEIDG/BI_audit_CEIDG', "default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania");
  1090. $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";
  1091. $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";
  1092. $refKrsToKrsCompany = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company");
  1093. $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";
  1094. $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";
  1095. $refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
  1096. $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";
  1097. $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";
  1098. }
  1099. $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");
  1100. $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";
  1101. foreach ($queries as $query) DB::getPDO()->query($query);
  1102. $BiAuditRelations = new BiAuditRelations($full);
  1103. $query = "select ID from BI_audit_ALL where {$fullWhere} order by ID";
  1104. $result = DB::query($query);
  1105. while ($row = DB::fetch($result)) $BiAuditRelations->findRelations($row->ID);
  1106. }
  1107. public function doReloadCache($full = false) {
  1108. $powiazaniaDirLocation = $this->getMainDirectory();
  1109. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1110. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1111. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1112. file_put_contents($reloadCachePidFile, getmypid());
  1113. try {
  1114. $this->reloadCache_reTeryt($full);
  1115. $this->reloadCache_updateAll($full);
  1116. file_put_contents($reloadCacheResultFile, "ok");
  1117. } catch (Exception $e) {
  1118. file_put_contents($reloadCacheResultFile, $e->getMessage());
  1119. }
  1120. }
  1121. public function doGeneratePowiazania($ID) {
  1122. $powiazaniaDirLocation = $this->getMainDirectory();
  1123. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1124. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  1125. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  1126. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  1127. file_put_contents($pidFile, getmypid());
  1128. $tablesConf = [
  1129. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  1130. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  1131. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  1132. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  1133. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  1134. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  1135. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  1136. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  1137. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  1138. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  1139. ];
  1140. try {
  1141. $BiAuditPowiazania = new BiAuditPowiazania($ID);
  1142. if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  1143. file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  1144. $BiAuditPowiazania->saveToDb();
  1145. /* $powiazania = $BiAuditPowiazania->asArray('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  1146. if (!$powiazania) return false;
  1147. DB::getPDO()->query($query);
  1148. foreach ($powiazania['BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row'] as $row) {
  1149. $powiazaniaRowSqlArr = [];
  1150. $string_concat_path = [];
  1151. foreach ($row['object'] as $i => $object) {
  1152. $powiazaniaRowObjectSqlArr = [];
  1153. $table = array_keys($object)[0];
  1154. if (!isset($tablesConf[$table])) throw new Exception("Błąd danych konfiguracyjnych");
  1155. $concat = "table='{$table}'";
  1156. if (isset($object['relation_from'])) $concat .= ";relation_from='{$object['relation_from']}'";
  1157. foreach ($tablesConf[$table] as $field) {
  1158. if ($object[$table][$field]) $concat .= ";{$field}='{$object[$table][$field]}'";
  1159. }
  1160. if ($i == 0) $powiazaniaRowSqlArr['string_concat_from'] = $concat;
  1161. elseif ($i == count($row['object']) - 1) $powiazaniaRowSqlArr['string_concat_to'] = $concat;
  1162. else $string_concat_path[] = $concat;
  1163. }
  1164. $powiazaniaRowSqlArr['string_concat_path'] = implode(' / ', $string_concat_path);
  1165. $id_row = DB::getPDO()->insert("BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row", $powiazaniaRowSqlArr);
  1166. if (!$id_row) throw new Exception("Błąd bazy danych");
  1167. DB::getPDO()->insert('CRM__#REF_TABLE__25', ["PRIMARY_KEY" => $ID, "REMOTE_PRIMARY_KEY" => $id_row]);
  1168. }
  1169. */
  1170. file_put_contents($resultFile, "ok");
  1171. } catch (Exception $e) {
  1172. file_put_contents($resultFile, $e->getMessage());
  1173. }
  1174. }
  1175. public function reinstallAction() {
  1176. $this->reinstall();
  1177. die('OK');
  1178. }
  1179. public function reinstall() {
  1180. $sqlList = array();
  1181. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  1182. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  1183. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  1184. SQL;
  1185. $sqlList['ChangeStructure1'] = <<<SQL
  1186. 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';
  1187. SQL;
  1188. $sqlList['ChangeStructure2'] = <<<SQL
  1189. UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
  1190. SQL;
  1191. $sqlList['ChangeStructure3'] = <<<SQL
  1192. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
  1193. SQL;
  1194. $db = DB::getDB();
  1195. if ($db->has_errors()) {
  1196. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  1197. }
  1198. foreach ($sqlList as $sqlName => $sql) {
  1199. $res = $db->query($sql);
  1200. if ($db->has_errors()) {
  1201. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  1202. }
  1203. }
  1204. }
  1205. }
  1206. class BiAuditRelations {
  1207. private $RELATIONS_ID = [];
  1208. private $full;
  1209. private $relations = [
  1210. 'nip' => ['nip'],
  1211. 'regon' => ['regon'],
  1212. 'krs' => ['krs'],
  1213. 'pesel' => ['pesel'],
  1214. 'adres' => ['TERYT_SYM', 'TERYT_SYM_UL', 'nrDomu', 'nrLokalu'],
  1215. ];
  1216. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1217. private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  1218. public function __construct($full = false) {
  1219. $this->full = $full;
  1220. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  1221. $result = DB::getPDO()->fetchAll($query);
  1222. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  1223. }
  1224. private function getRelationID($name) {
  1225. if (!isset($this->RELATIONS_ID[$name])) {
  1226. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  1227. $newID = DB::getPDO()->fetchValue($query);
  1228. $this->RELATIONS_ID[$name] = $newID;
  1229. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  1230. DB::getPDO()->query($query);
  1231. }
  1232. return $this->RELATIONS_ID[$name];
  1233. }
  1234. public function findRelations($ID) {
  1235. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  1236. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  1237. $row = $result[0];
  1238. $joins = [];
  1239. $items = '';
  1240. foreach ($this->relations as $name => $columns) {
  1241. $ok = 0;
  1242. $join = [];
  1243. foreach ($columns as $column) {
  1244. $join[] = "t1.{$column} = t2.{$column}";
  1245. if ($row[$column]) $ok++;
  1246. }
  1247. if ($ok / count($columns) > 0.5) {
  1248. $joins[] = "(" . implode(" and ", $join) . ")";
  1249. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  1250. }
  1251. }
  1252. if (!$joins) return false;
  1253. if ($this->full) $where = "where t1.ID = {$ID} and t2.ID > {$ID}";
  1254. else $where = "where t1.ID = {$ID} and (t2.BASE = 1 or t2.ID > {$ID})";
  1255. $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 " .
  1256. "from BI_audit_ALL t1 join BI_audit_ALL t2 on " . implode(" or ", $joins) . " {$where}";
  1257. $result = DB::getPDO()->fetchAll($query);
  1258. foreach ($result as $row) {
  1259. $relationID = 0;
  1260. foreach ($this->relations as $name => $v) {
  1261. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  1262. }
  1263. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  1264. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  1265. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  1266. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  1267. if (!($start2 || $end1)) {
  1268. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
  1269. DB::getPDO()->query($query);
  1270. }
  1271. if (!($start1 || $end2)) {
  1272. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
  1273. DB::getPDO()->query($query);
  1274. }
  1275. }
  1276. }
  1277. }
  1278. class BiAuditPowiazania {
  1279. private $DEPTH;
  1280. private $ID;
  1281. private $endNodes;
  1282. private $path = [];
  1283. private $results = [];
  1284. private $items_results = [];
  1285. private $relations = [];
  1286. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1287. public function __construct($ID = 0) {
  1288. if (!$ID) throw new Exception("Wrong ID parameter");
  1289. $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')";
  1290. $result = DB::getPDO()->fetchAll($query);
  1291. if (!$result) throw new Exception("Błąd danych");
  1292. $this->DEPTH = (int) $result[0]['BI_analiza_depth'];
  1293. $this->ID = $ID;
  1294. $subQueries = [];
  1295. foreach ($this->destTables as $destTable) {
  1296. $refTable = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "default_db__x3A__{$destTable}:{$destTable}");
  1297. $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}'";
  1298. }
  1299. $query = implode(" union ", $subQueries);
  1300. $result = DB::getPDO()->fetchAll($query);
  1301. if (!$result) throw new Exception("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  1302. $this->endNodes = array_map('reset', $result);
  1303. $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  1304. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
  1305. $query = "select `all`.ID as ID from BI_audit_ALL `all` join `{$refPowiazaniaToPracownicy}` ref
  1306. on `all`.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and `all`.REMOTE_ID = ref.REMOTE_PRIMARY_KEY and ref.PRIMARY_KEY = '{$ID}'";
  1307. $result = DB::getPDO()->fetchAll($query);
  1308. foreach ($result as $row) $this->findPowiazania($row['ID']);
  1309. }
  1310. public function findPowiazania($ID, $relation = "", $end = 0) {
  1311. if (isset($this->path[$ID])) return false;
  1312. $this->path[$ID] = $relation;
  1313. if (!$relation) $relation = 0;
  1314. if ($end) {
  1315. if (in_array($ID, $this->endNodes)) $this->results[] = $this->path;
  1316. array_pop($this->path);
  1317. return true;
  1318. }
  1319. if (count($this->path) > $this->DEPTH) {
  1320. array_pop($this->path);
  1321. return false;
  1322. }
  1323. $nodes = [];
  1324. if ($relation) $where = "and ({$relation} & ref.RELATION_ID) != {$relation}";
  1325. else $where = "";
  1326. $query = "select ref.ID2, RELATION_ID, END from BI_audit_ALL_ref ref where ref.ID1 = '{$ID}' {$where}";
  1327. $result = DB::query($query);
  1328. while ($row = DB::fetch($result)) $nodes[$row->ID2] = ['relation' => (int) $row->RELATION_ID, 'end' => $row->END];
  1329. foreach ($nodes as $node => $data) $this->findPowiazania($node, $data['relation'], $data['end']);
  1330. array_pop($this->path);
  1331. }
  1332. private function relationName($ID) {
  1333. if (!isset($this->relations[$ID])) {
  1334. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  1335. $result = DB::getPDO()->fetchAll($query);
  1336. $rels = array_map('reset', $result);
  1337. $this->relations[$ID] = implode(", ", $rels);
  1338. }
  1339. return $this->relations[$ID];
  1340. }
  1341. private function generateItemsResults() {
  1342. $xmlRoot2 = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  1343. $xmlElements = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  1344. $this->items_results = [];
  1345. $items_kontrahenci = [];
  1346. $items_kw_person = [];
  1347. $kontrahenci = [];
  1348. $kw_person = [];
  1349. $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');
  1350. $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');
  1351. foreach ($this->results as $result) {
  1352. $item_results = [];
  1353. foreach ($result as $ID => $rel) {
  1354. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  1355. $row = DB::getPDO()->fetchFirst($query);
  1356. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  1357. $obj = DB::fetch(DB::query($query));
  1358. $item_result = [$row['REMOTE_TABLE'] => (array) $obj];
  1359. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  1360. $item_results['object'][] = $item_result;
  1361. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  1362. $kontrahenci[] = $row['REMOTE_ID'];
  1363. $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']}'";
  1364. $res = DB::query($query);
  1365. if (mysql_num_rows($res)) {
  1366. $umowy = [];
  1367. while ($obj = DB::fetch($res)) $umowy[] = (array) $obj;
  1368. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  1369. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  1370. $items_kontrahenci[] = $item_kontrahenci;
  1371. }
  1372. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  1373. $kw_person[] = $row['REMOTE_ID'];
  1374. $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']}'";
  1375. $res = DB::query($query);
  1376. if (mysql_num_rows($res)) {
  1377. $kw = [];
  1378. while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
  1379. $item_kw_person['ID'] = $row['REMOTE_ID'];
  1380. $item_kw_person['BI_audit_KW_requested'] = $kw;
  1381. $items_kw_person[] = $item_kw_person;
  1382. }
  1383. }
  1384. }
  1385. $this->items_results[$xmlRoot2][$xmlElements][] = $item_results;
  1386. }
  1387. $this->items_results[$xmlRoot2]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  1388. $this->items_results[$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;
  1389. }
  1390. public function saveToDb() {
  1391. if (!$this->results) return null;
  1392. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  1393. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  1394. $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
  1395. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  1396. foreach ($this->results as $result) {
  1397. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  1398. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  1399. foreach ($result as $ID => $rel) {
  1400. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  1401. $object = DB::getPDO()->fetchFirst($query);
  1402. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relations[$rel]]);
  1403. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  1404. $ref = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
  1405. "default_db__x3A__{$object['REMOTE_TABLE']}:{$object['REMOTE_TABLE']}");
  1406. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  1407. }
  1408. }
  1409. }
  1410. public function asXml() {
  1411. if (!$this->results) return null;
  1412. if (!$this->items_results) $this->generateItemsResults();
  1413. $xmlRoot = "RelatedFeatureRoot";
  1414. return V::arrayToXML($this->items_results, true, $xmlRoot);
  1415. }
  1416. public function asArray($subArray = null) {
  1417. if (!$this->results) return null;
  1418. if (!$this->items_results) $this->generateItemsResults();
  1419. if ($subArray) {
  1420. if (isset($this->items_results[$subArray])) return $this->items_results[$subArray];
  1421. else return [];
  1422. } else return $this->items_results;
  1423. }
  1424. public function powiazaniaFound() {
  1425. if ($this->results) return true;
  1426. else return false;
  1427. }
  1428. }