BiAuditGenerate.php 48 KB

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