BiAuditGenerate.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. Lib::loadClass('FoldersConfig');
  4. Lib::loadClass('FileUploader');
  5. Lib::loadClass('ProcesHelper');
  6. class Route_UrlAction_BiAuditGenerate extends RouteBase {
  7. private $powiazanie = null;
  8. private $REFERER;
  9. public function handleAuth() {
  10. if (!User::logged()) {
  11. User::authByRequest();
  12. }
  13. }
  14. private function getDirectory($table, $id) {
  15. $folderConf = FoldersConfig::getAll($table.'_COLUMN');
  16. $record = new stdClass;
  17. $record->ID = $id;
  18. $uploader = new FileUploader($table.'_COLUMN', $record);
  19. $errMsg = "";
  20. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$$errMsg}", 404);
  21. $uploader->findFolder();
  22. return $uploader->getDestLocalPath(true);
  23. }
  24. private function getMainDirectory() {
  25. $folderConf = FoldersConfig::getAll('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_COLUMN');
  26. if (!isset($folderConf['mount_point'])) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
  27. return $folderConf['mount_point'];
  28. }
  29. private function initializePowiazaniaForm() {
  30. ?>
  31. <div class="container" style="margin-top:20px">
  32. <form class="form-horizontal" method="post">
  33. <legend>
  34. Generowanie powiązań :: <?=$this->powiazanie['L_APPOITMENT_INFO']?>
  35. <span class="pull-right"># <?=$this->powiazanie['ID']?></span>
  36. </legend>
  37. <div class="form-group">
  38. <div class="col-sm-12">
  39. <h4>Wybierz pracowników, dla których mają zostać wyszukane powiązania</h4>
  40. <table class="table table-bordered table-hover table-striped" height=5>
  41. <thead>
  42. <tr style="text-align:center; background-color:lightgray">
  43. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  44. <td width=1>ID</td>
  45. <td>Imiona</td>
  46. <td>Nazwisko</td>
  47. <td>Pesel</td>
  48. <td>NIP</td>
  49. <td>Regon</td>
  50. </tr>
  51. </thead>
  52. <tbody>
  53. <?php
  54. $pracownicy = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_PRACOWNICY");
  55. foreach ($pracownicy as $pracownik) {
  56. ?>
  57. <tr>
  58. <td><input type="checkbox" name="prID[]" value="<?=$pracownik['ID']?>" onClick="toggle(this)"/></td>
  59. <td align="right"><?=$pracownik['ID']?></td>
  60. <td><?=$pracownik['imiona']?></td>
  61. <td><?=$pracownik['nazwisko']?></td>
  62. <td><?=$pracownik['pesel']?></td>
  63. <td><?=$pracownik['nip']?></td>
  64. <td><?=$pracownik['regon']?></td>
  65. </tr>
  66. <?php
  67. }
  68. ?>
  69. <tr>
  70. <td><input type="checkbox" name="reloadCache"/></td>
  71. <td colspan=6>Odśwież cache (wymagane w przypadku, gdy dokonano dowolnych zmian w tabelach pracowników/kontrahentów)</td>
  72. </tr>
  73. </tbody>
  74. </table>
  75. </div>
  76. </div>
  77. <div class="form-group">
  78. <div class="col-sm-12">
  79. <div class="containter" style="text-align:center">
  80. <button type="submit" class="btn btn-primary" name="action" value="initialize">Generuj</button>
  81. <a href="<?=$this->REFERER?>" class="btn btn-default">Anuluj</a>
  82. </div>
  83. </div>
  84. </div>
  85. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  86. </form>
  87. </div>
  88. <script language="JavaScript">
  89. <!--
  90. function toggleAll(source) {
  91. checkboxes = document.getElementsByName('prID[]');
  92. for(var i=0, n=checkboxes.length;i<n;i++) checkboxes[i].checked = source.checked;
  93. }
  94. function toggle(source) {
  95. checkboxes = document.getElementsByName('prID[]');
  96. all = true;
  97. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked == false) all = false;
  98. source.form['checkAll'].checked = all;
  99. }
  100. -->
  101. </script>
  102. <?php
  103. }
  104. private function initializePowiazaniaSave() {
  105. $prID = V::get('prID', array(), $_POST);
  106. if (!$prID) throw new Exception("Nie wybrano żadnego pracownika!");
  107. $reloadCache = V::get('reloadCache', 'off', $_POST);
  108. $sqlArr = [
  109. 'ID' => $this->powiazanie['ID'],
  110. 'FILE_STATUS' => 'TO_GENERATE',
  111. 'BI_analiza_employees' => implode(',', $prID),
  112. ];
  113. if ($reloadCache == 'on') $sqlArr['BI_analiza_reloadCache'] = 'Y';
  114. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Y'";
  115. $result = DB::getPDO()->fetchValue($query);
  116. if ($result) $sqlArr['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache (wymagane dla innego rekordu)';
  117. elseif ($reloadCache == 'on') $sqlArr['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache';
  118. else $sqlArr['FILE_STATUS_info'] = "Oczekuje na wygenerowanie powiązań";
  119. $affected = DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  120. if ($affected) {
  121. SE_Layout::alert('success','Oznaczono rekord do wygenerowania');
  122. ?>
  123. <div class="container" style="text-align:center">
  124. <a href="<?=$this->REFERER?>" class="btn btn-primary">Powrót</a>
  125. </div>
  126. <?php
  127. } else {
  128. throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  129. }
  130. }
  131. private function initializePowiazania() {
  132. switch (V::get('action', '', $_POST)) {
  133. case "initialize":
  134. $this->initializePowiazaniaSave();
  135. break;
  136. default:
  137. $this->initializePowiazaniaForm();
  138. }
  139. }
  140. private function showPowiazania() {
  141. // $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  142. // $xmlFile = "{$powiazanieDirLocation}/relations.xml";
  143. // echo "<pre>" . htmlentities(file_get_contents($xmlFile)) . "</pre>";
  144. echo "Statystyki znalezionych powiązań [TODO]";
  145. }
  146. private function powiazania($ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA) {
  147. try {
  148. $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA}'");
  149. if (!$powiazania) throw new Exception("Błąd danych");
  150. $this->powiazanie = $powiazania[0];
  151. switch ($this->powiazanie['FILE_STATUS']) {
  152. case "NONE":
  153. $this->initializePowiazania();
  154. break;
  155. case "GENERATED":
  156. $this->showPowiazania();
  157. break;
  158. default:
  159. throw new Exception("Błędny status rekordu");
  160. }
  161. } catch (Exception $e) {
  162. SE_Layout::alert('danger',$e->getMessage());
  163. $_SESSION['REFERER'] = $this->REFERER;
  164. ?>
  165. <div class="container" style="text-align:center">
  166. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
  167. </div>
  168. <?php
  169. }
  170. }
  171. public function defaultAction() {
  172. SE_Layout::gora();
  173. SE_Layout::menu();
  174. if (isset($_SESSION['REFERER'])) {
  175. $this->REFERER = $_SESSION['REFERER'];
  176. unset($_SESSION['REFERER']);
  177. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  178. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  179. if (V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int') > 0) $this->powiazania(V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int'));
  180. else SE_Layout::alert('danger','Błąd parametru');
  181. SE_Layout::dol();
  182. }
  183. public function doGenerate() {
  184. function deleteResultsFromDB($ID) {
  185. $query = "delete from row, ref using BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row row join `CRM__#REF_TABLE__25` ref on row.ID=ref.REMOTE_PRIMARY_KEY where ref.PRIMARY_KEY='{$ID}'";
  186. DB::getPDO()->query($query);
  187. }
  188. function generatePhpScript($function) {
  189. return '<?php
  190. ini_set("memory_limit", "4G");
  191. define("DS", DIRECTORY_SEPARATOR);
  192. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  193. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  194. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  195. ini_set("display_startup_errors", "0");
  196. ini_set("log_errors", "1");
  197. ini_set("error_log", "/var/log/apache2/error_log");
  198. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  199. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  200. Lib::loadClass("Router");
  201. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  202. ';
  203. }
  204. try {
  205. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  206. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  207. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  208. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  209. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  210. ### Ustawienie zmiennych
  211. $powiazaniaDirLocation = $this->getMainDirectory();
  212. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  213. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  214. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  215. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  216. ### Utworzenie niezbędnych katalogów i plików
  217. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0755, true);
  218. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  219. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  220. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Y' and FILE_STATUS = 'TO_GENERATE'";
  221. $result = DB::getPDO()->fetchAll($query);
  222. if ($result) {
  223. $sqlArr = [];
  224. if (file_exists($reloadCachePhpFile)) {
  225. if (file_exists($reloadCacheResultFile)) {
  226. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  227. if ($reloadCacheResult == "ok") {
  228. $sqlArr = [
  229. 'FILE_STATUS_info' => 'Odświeżono cache, oczekiwanie na wygenerowanie powiązań',
  230. 'BI_analiza_reloadCache' => 'N',
  231. ];
  232. } else {
  233. $sqlArr = [
  234. 'FILE_STATUS' => 'ERROR',
  235. 'FILE_STATUS_info' => "Wystąpił błąd podczas odświeżania cache ({$reloadCacheResult})",
  236. ];
  237. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  238. $result = DB::getPDO()->fetchAll($query);
  239. }
  240. unlink($reloadCachePhpFile);
  241. unlink($reloadCacheResultFile);
  242. }
  243. } else {
  244. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  245. $result = DB::getPDO()->fetchValue($query);
  246. if ($result) {
  247. $sqlArr = [
  248. 'FILE_STATUS_info' => 'Wstrzymano odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  249. ];
  250. } else {
  251. $sqlArr = [
  252. 'FILE_STATUS_info' => 'W trakcie odświeżania cache',
  253. ];
  254. file_put_contents($reloadCachePhpFile, generatePhpScript('doReloadCache()'));
  255. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  256. }
  257. }
  258. if ($sqlArr) {
  259. foreach ($result as $row) {
  260. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  261. }
  262. }
  263. }
  264. ### Generowanie powiązań
  265. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  266. $result = DB::getPDO()->fetchAll($query);
  267. foreach ($result as $row) {
  268. $sqlArr = [
  269. 'ID' => $row['ID'],
  270. 'FILE_STATUS' => 'IN_PROGRESS',
  271. 'FILE_STATUS_info' => 'W trakcie generowania powiązań',
  272. ];
  273. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  274. deleteResultsFromDB($row['ID']);
  275. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  276. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  277. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  278. file_put_contents($generatePowiazaniaPhpFile, generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  279. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  280. }
  281. ### Weryfikacja świeżo wygenerowanych powiązań
  282. $query = "select ID, BI_analiza_depth from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  283. $result = DB::getPDO()->fetchAll($query);
  284. foreach ($result as $row) {
  285. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  286. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  287. if (file_exists($generatePowiazaniaResultFile)) {
  288. $error = false;
  289. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.xml";
  290. if (file_exists($xmlFile)) {
  291. if (filesize($xmlFile)) {
  292. $generatePowiazaniaResult = file_get_contents($generatePowiazaniaResultFile);
  293. if ($generatePowiazaniaResult == "ok") {
  294. $generatePowiazaniaSqlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.sql";
  295. if (!file_exists($generatePowiazaniaSqlFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu";
  296. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult})";
  297. } else $error = "Wystąpił nieznany błąd - plk xml został wygenerowany niepoprawnie";
  298. } else $error = "Wystąpił nienzany błąd - nie znaleziono pliku xml";
  299. if ($error) {
  300. $sqlArr = [
  301. 'FILE_STATUS' => 'ERROR',
  302. 'FILE_STATUS_info' => $error,
  303. ];
  304. deleteResultsFromDB($row['ID']);
  305. if (file_exists($xmlFile)) unlink($xmlFile);
  306. } else {
  307. $sqlArr = [
  308. 'FILE_STATUS' => 'GENERATED',
  309. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  310. ];
  311. $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  312. $destXmlFile = "{$powiazanieDirLocation}/relations.xml";
  313. rename($xmlFile, $destXmlFile);
  314. }
  315. $sqlArr['ID'] = $row['ID'];
  316. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  317. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  318. unlink($generatePowiazaniaPhpFile);
  319. unlink($generatePowiazaniaPidFile);
  320. unlink($generatePowiazaniaResultFile);
  321. if (file_exists($generatePowiazaniaSqlFile)) unlink($generatePowiazaniaSqlFile);
  322. } elseif (file_exists($generatePowiazaniaPidFile)) {
  323. $pid = file_get_contents($generatePowiazaniaPidFile);
  324. }
  325. }
  326. } catch (Exception $e) {
  327. echo $e->getMessage()."\n";
  328. }
  329. }
  330. private function reloadCache_reTeryt() {
  331. Lib::loadClass('Teryt');
  332. function reTeryt($table) {
  333. $tableConf = [
  334. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  335. 'kodPocztowy' => 'Kod_pocztowy',
  336. 'miejscowosc' => 'Miejscowosc',
  337. 'ulica' => 'Ulica',
  338. ],
  339. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  340. 'kodPocztowy' => 'kodPocztowy',
  341. 'miejscowosc' => 'miejscowosc',
  342. 'ulica' => 'ulica',
  343. ],
  344. ];
  345. $columns = ['kodPocztowy', 'miejscowosc', 'ulica'];
  346. $query = "select * from `{$table}` where TERYT_SYM is null";
  347. try {
  348. $adresy = DB::getPDO()->fetchall($query);
  349. foreach ($adresy as $adres) {
  350. $search = [];
  351. foreach ($columns as $column) $search[$column] = $adres[$tableConf[$table][$column]];
  352. try {
  353. $teryt = Teryt::search($search);
  354. if ($teryt) {
  355. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  356. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  357. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  358. }
  359. } catch (Exception $e) {
  360. }
  361. }
  362. } catch (Exception $e) {
  363. }
  364. }
  365. // reTeryt('BI_audit_ENERGA_RUM_KONTRAHENCI');
  366. reTeryt('BI_audit_ENERGA_PRACOWNICY_adresy');
  367. }
  368. private function reloadCache_updateAll() {
  369. $tables = [
  370. 'BI_audit_ENERGA_PRACOWNICY' => [
  371. 'fields' => [
  372. 'nip' => 'nip',
  373. 'regon' => 'regon',
  374. 'pesel' => 'pesel',
  375. ],
  376. //'where' => '',
  377. ],
  378. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  379. 'fields' => [
  380. 'TERYT_SYM' => 'TERYT_SYM',
  381. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  382. 'nrDomu' => 'nrBudynku',
  383. 'nrLokalu' => 'nrLokalu',
  384. ],
  385. //'where' => '',
  386. ],
  387. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  388. 'fields' => [
  389. 'nip' => 'NIP',
  390. 'regon' => 'REGON',
  391. 'pesel' => 'PESEL',
  392. 'TERYT_SYM' => 'TERYT_SYM',
  393. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  394. 'nrDomu' => 'Numer_budynku',
  395. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  396. ],
  397. 'where' => "ownCompany != 'Y'",
  398. ],
  399. 'BI_audit_KW_requested_person' => [
  400. 'fields' => [
  401. 'pesel' => 'Seller_person_pesel',
  402. 'krs' => 'Seller_person_KRS',
  403. 'nip' => 'Seller_person_NIP',
  404. 'regon' => 'Seller_person_REGON',
  405. ],
  406. //'where' => '',
  407. ],
  408. ];
  409. $queries[] = "delete from BI_audit_ALL where BASE = 0";
  410. $queries[] = "delete from BI_audit_ALL_ref where BASE = 0";
  411. $queries[] = "delete from BI_audit_ALL_ref_RELATIONS where BASE = 0";
  412. foreach ($tables as $name => $table) {
  413. if (isset($table['where']) && $table['where']) $where = "where {$table['where']}";
  414. else $where = '';
  415. $queries[] = "insert into BI_audit_ALL (REMOTE_TABLE, REMOTE_ID, " . implode(", ", array_keys($table['fields'])) . ") select '{$name}', ID, " . implode(", ", $table['fields']) . " from {$name} {$where}";
  416. }
  417. $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";
  418. $queries[] = "set @var = (select round(coalesce(max(ID), '0.5')) from BI_audit_ALL_ref_RELATIONS)";
  419. $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";
  420. $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 `BI_audit_ENERGA_PRACOWNICY` as pracownicy on all1.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and all1.REMOTE_ID = pracownicy.ID join BI_audit_ENERGA_PRACOWNICY_adresy as adresy on pracownicy.ID = adresy.ID_BI_audit_ENERGA_PRACOWNICY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY_adresy' and adresy.ID = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION";
  421. $queries[] = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID) select all2.ID, all1.ID, rel.ID from BI_audit_ALL as all1 join `BI_audit_ENERGA_PRACOWNICY` as pracownicy on all1.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and all1.REMOTE_ID = pracownicy.ID join BI_audit_ENERGA_PRACOWNICY_adresy as adresy on pracownicy.ID = adresy.ID_BI_audit_ENERGA_PRACOWNICY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY_adresy' and adresy.ID = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all2.REMOTE_TABLE = rel.RELATION";
  422. foreach ($queries as $query) DB::getPDO()->query($query);
  423. $BiAuditRelations = new BiAuditRelations();
  424. $query = "select ID from BI_audit_ALL where BASE = 0";
  425. $result = DB::query($query);
  426. while ($row = DB::fetch($result)) $BiAuditRelations->findRelations($row->ID);
  427. }
  428. public function doReloadCache() {
  429. $powiazaniaDirLocation = $this->getMainDirectory();
  430. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  431. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  432. try {
  433. $this->reloadCache_reTeryt();
  434. $this->reloadCache_updateAll();
  435. file_put_contents($reloadCacheResultFile, "ok");
  436. } catch (Exception $e) {
  437. file_put_contents($reloadCacheResultFile, $e->getMessage());
  438. }
  439. }
  440. public function doGeneratePowiazania($ID) {
  441. $powiazaniaDirLocation = $this->getMainDirectory();
  442. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  443. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  444. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  445. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  446. $sqlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.sql";
  447. file_put_contents($pidFile, getmypid());
  448. $tablesConf = [
  449. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  450. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  451. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  452. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  453. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  454. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  455. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  456. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  457. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  458. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  459. ];
  460. try {
  461. $query = "select BI_analiza_depth, BI_analiza_employees, A_ADM_COMPANY, A_CLASSIFIED from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$ID}' and FILE_STATUS = 'IN_PROGRESS' and BI_analiza_reloadCache != 'Y'";
  462. $result = DB::getPDO()->fetchAll($query);
  463. if (!$result) throw new Exception("Błąd danych");
  464. $powiazanie = $result[0];
  465. if (!preg_match('/^[[:digit:]]+(,[[:digit:]]+)*$/', $powiazanie['BI_analiza_employees'])) throw new Exception("Błąd danych");
  466. $query = "select ID from BI_audit_ALL where REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and REMOTE_ID in ({$powiazanie['BI_analiza_employees']})";
  467. $result = DB::getPDO()->fetchAll($query);
  468. $BiAuditPowiazania = new BiAuditPowiazania($powiazanie['BI_analiza_depth']);
  469. foreach ($result as $row) $BiAuditPowiazania->findPowiazania($row['ID']);
  470. if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  471. $xml = $BiAuditPowiazania->asXml();
  472. file_put_contents($xmlFile, $xml);
  473. file_put_contents($sqlFile, mysql_real_escape_string(gzcompress($xml)));
  474. $powiazania = $BiAuditPowiazania->asArray('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  475. if (!$powiazania) return false;
  476. DB::getPDO()->query($query);
  477. foreach ($powiazania['BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row'] as $row) {
  478. $powiazaniaRowSqlArr = [];
  479. $string_concat_path = [];
  480. foreach ($row['object'] as $i => $object) {
  481. $powiazaniaRowObjectSqlArr = [];
  482. $table = array_keys($object)[0];
  483. if (!isset($tablesConf[$table])) throw new Exception("Błąd danych konfiguracyjnych");
  484. $concat = "table='{$table}'";
  485. if (isset($object['relation_from'])) $concat .= ";relation_from='{$object['relation_from']}'";
  486. foreach ($tablesConf[$table] as $field) {
  487. if ($object[$table][$field]) $concat .= ";{$field}='{$object[$table][$field]}'";
  488. }
  489. if ($i == 0) $powiazaniaRowSqlArr['string_concat_from'] = $concat;
  490. elseif ($i == count($row['object']) - 1) $powiazaniaRowSqlArr['string_concat_to'] = $concat;
  491. else $string_concat_path[] = $concat;
  492. }
  493. $powiazaniaRowSqlArr['string_concat_path'] = implode(' / ', $string_concat_path);
  494. $powiazaniaRowSqlArr['A_ADM_COMPANY'] = $powiazanie['A_ADM_COMPANY'];
  495. $powiazaniaRowSqlArr['A_CLASSIFIED'] = $powiazanie['A_CLASSIFIED'];
  496. $id_row = DB::getPDO()->insert("BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row", $powiazaniaRowSqlArr);
  497. if (!$id_row) throw new Exception("Błąd bazy danych");
  498. DB::getPDO()->insert('CRM__#REF_TABLE__25', ["PRIMARY_KEY" => $ID, "REMOTE_PRIMARY_KEY" => $id_row]);
  499. }
  500. file_put_contents($resultFile, "ok");
  501. } catch (Exception $e) {
  502. file_put_contents($resultFile, $e->getMessage());
  503. }
  504. }
  505. public function reinstallAction() {
  506. $this->reinstall();
  507. die('OK');
  508. }
  509. public function reinstall() {
  510. $sqlList = array();
  511. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  512. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  513. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  514. SQL;
  515. $db = DB::getDB();
  516. if ($db->has_errors()) {
  517. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  518. }
  519. foreach ($sqlList as $sqlName => $sql) {
  520. $res = $db->query($sql);
  521. if ($db->has_errors()) {
  522. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  523. }
  524. }
  525. }
  526. }
  527. class BiAuditRelations {
  528. private $RELATIONS_ID = [];
  529. private $relations = [
  530. 'nip' => ['nip'],
  531. 'regon' => ['regon'],
  532. 'krs' => ['krs'],
  533. 'pesel' => ['pesel'],
  534. 'adres' => ['TERYT_SYM', 'TERYT_SYM_UL', 'nrDomu', 'nrLokalu'],
  535. ];
  536. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  537. public function __construct() {
  538. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  539. $result = DB::getPDO()->fetchAll($query);
  540. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  541. }
  542. private function getRelationID($name) {
  543. if (!isset($this->RELATIONS_ID[$name])) {
  544. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  545. $newID = DB::getPDO()->fetchValue($query);
  546. $this->RELATIONS_ID[$name] = $newID;
  547. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  548. DB::getPDO()->query($query);
  549. }
  550. return $this->RELATIONS_ID[$name];
  551. }
  552. public function findRelations($ID) {
  553. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  554. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  555. $row = $result[0];
  556. $joins = [];
  557. $items = '';
  558. foreach ($this->relations as $name => $columns) {
  559. $ok = 0;
  560. $join = [];
  561. foreach ($columns as $column) {
  562. $join[] = "t1.{$column} = t2.{$column}";
  563. if ($row[$column]) $ok++;
  564. }
  565. if ($ok / count($columns) > 0.5) {
  566. $joins[] = "(" . implode(" and ", $join) . ")";
  567. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  568. }
  569. }
  570. if (!$joins) return false;
  571. $query = "select t2.ID as ID, t1.REMOTE_TABLE as REMOTE_TABLE_1, t2.REMOTE_TABLE as REMOTE_TABLE_2 {$items} " .
  572. "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})";
  573. $result = DB::getPDO()->fetchAll($query);
  574. foreach ($result as $row) {
  575. $relationID = 0;
  576. foreach ($this->relations as $name => $v) {
  577. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  578. }
  579. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  580. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  581. if (!$end1) {
  582. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2})";
  583. DB::getPDO()->query($query);
  584. }
  585. if (!$end2) {
  586. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1})";
  587. DB::getPDO()->query($query);
  588. }
  589. }
  590. }
  591. }
  592. class BiAuditPowiazania {
  593. private $DEPTH;
  594. private $path = [];
  595. private $results = [];
  596. private $items_results = [];
  597. private $relations = [];
  598. public function __construct($depth = 0) {
  599. $this->DEPTH = (int) $depth;
  600. }
  601. public function findPowiazania($ID, $relation = "", $end = 0) {
  602. if (isset($this->path[$ID])) return false;
  603. $this->path[$ID] = $relation;
  604. if (!$relation) $relation = 0;
  605. if ($end) {
  606. $this->results[] = $this->path;
  607. array_pop($this->path);
  608. return true;
  609. }
  610. if (count($this->path) > $this->DEPTH) {
  611. array_pop($this->path);
  612. return false;
  613. }
  614. $nodes = [];
  615. if ($relation) $where = "and ({$relation} & ref.RELATION_ID) != {$relation}";
  616. else $where = "";
  617. $query = "select ref.ID2, RELATION_ID, END from BI_audit_ALL_ref ref where ref.ID1 = '{$ID}' {$where}";
  618. $result = DB::query($query);
  619. while ($row = DB::fetch($result)) $nodes[$row->ID2] = ['relation' => (int) $row->RELATION_ID, 'end' => $row->END];
  620. foreach ($nodes as $node => $data) $this->findPowiazania($node, $data['relation'], $data['end']);
  621. array_pop($this->path);
  622. }
  623. private function relationName($ID) {
  624. if (!isset($this->relations[$ID])) {
  625. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  626. $result = DB::getPDO()->fetchAll($query);
  627. $rels = array_map('reset', $result);
  628. $this->relations[$ID] = implode(", ", $rels);
  629. }
  630. return $this->relations[$ID];
  631. }
  632. private function generateItemsResults() {
  633. $xmlRoot2 = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  634. $xmlElements = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  635. $this->items_results = [];
  636. $items_kontrahenci = [];
  637. $items_kw_person = [];
  638. $kontrahenci = [];
  639. $kw_person = [];
  640. // $refTableUmowyToKontrahenci = 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');
  641. // $refTableKwToKwPerson = 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');
  642. // echo "{$refTableUmowyToKontrahenci} :: {$refTableKwToKwPerson} \n";
  643. // $refTablePowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  644. // echo ":: " . $refTablePowiazaniaToPowiazaniaRow . "::\n";
  645. foreach ($this->results as $result) {
  646. $item_results = [];
  647. foreach ($result as $ID => $rel) {
  648. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  649. $row = DB::getPDO()->fetchFirst($query);
  650. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  651. $obj = DB::fetch(DB::query($query));
  652. $item_result = [$row['REMOTE_TABLE'] => (array) $obj];
  653. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  654. $item_results['object'][] = $item_result;
  655. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  656. $kontrahenci[] = $row['REMOTE_ID'];
  657. $query = "select umowy.* from BI_audit_ENERGA_RUM_UMOWY umowy join `CRM__#REF_TABLE__23` ref on umowy.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
  658. $res = DB::query($query);
  659. if (mysql_num_rows($res)) {
  660. $umowy = [];
  661. while ($obj = DB::fetch($res)) $umowy[] = (array) $obj;
  662. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  663. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  664. $items_kontrahenci[] = $item_kontrahenci;
  665. }
  666. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  667. $kw_person[] = $row['REMOTE_ID'];
  668. $query = "select kw.* from BI_audit_KW_requested kw join `CRM__#REF_TABLE__24` ref on kw.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
  669. $res = DB::query($query);
  670. if (mysql_num_rows($res)) {
  671. $kw = [];
  672. while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
  673. $item_kw_person['ID'] = $row['REMOTE_ID'];
  674. $item_kw_person['BI_audit_KW_requested'] = $kw;
  675. $items_kw_person[] = $item_kw_person;
  676. }
  677. }
  678. }
  679. $this->items_results[$xmlRoot2][$xmlElements][] = $item_results;
  680. }
  681. $this->items_results[$xmlRoot2]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  682. $this->items_results[$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;
  683. }
  684. public function asXml() {
  685. if (!$this->results) return null;
  686. if (!$this->items_results) $this->generateItemsResults();
  687. $xmlRoot = "RelatedFeatureRoot";
  688. return V::arrayToXML($this->items_results, true, $xmlRoot);
  689. }
  690. public function asArray($subArray = null) {
  691. if (!$this->results) return null;
  692. if (!$this->items_results) $this->generateItemsResults();
  693. if ($subArray) {
  694. if (isset($this->items_results[$subArray])) return $this->items_results[$subArray];
  695. else return [];
  696. } else return $this->items_results;
  697. }
  698. public function powiazaniaFound() {
  699. if ($this->results) return true;
  700. else return false;
  701. }
  702. }