BiAuditGenerate.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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. exit;
  264. }
  265. ### Generowanie powiązań
  266. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  267. $result = DB::getPDO()->fetchAll($query);
  268. foreach ($result as $row) {
  269. $sqlArr = [
  270. 'ID' => $row['ID'],
  271. 'FILE_STATUS' => 'IN_PROGRESS',
  272. 'FILE_STATUS_info' => 'W trakcie generowania powiązań',
  273. ];
  274. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  275. deleteResultsFromDB($row['ID']);
  276. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  277. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  278. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  279. file_put_contents($generatePowiazaniaPhpFile, generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  280. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  281. }
  282. ### Weryfikacja świeżo wygenerowanych powiązań
  283. $query = "select ID, BI_analiza_depth from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  284. $result = DB::getPDO()->fetchAll($query);
  285. foreach ($result as $row) {
  286. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  287. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  288. if (file_exists($generatePowiazaniaResultFile)) {
  289. $error = false;
  290. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.xml";
  291. if (file_exists($xmlFile)) {
  292. if (filesize($xmlFile)) {
  293. $generatePowiazaniaResult = file_get_contents($generatePowiazaniaResultFile);
  294. if ($generatePowiazaniaResult == "ok") {
  295. $generatePowiazaniaSqlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.sql";
  296. if (!file_exists($generatePowiazaniaSqlFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu";
  297. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult})";
  298. } else $error = "Wystąpił nieznany błąd - plk xml został wygenerowany niepoprawnie";
  299. } else $error = "Wystąpił nienzany błąd - nie znaleziono pliku xml";
  300. if ($error) {
  301. $sqlArr = [
  302. 'FILE_STATUS' => 'ERROR',
  303. 'FILE_STATUS_info' => $error,
  304. ];
  305. deleteResultsFromDB($row['ID']);
  306. if (file_exists($xmlFile)) unlink($xmlFile);
  307. } else {
  308. $sqlArr = [
  309. 'FILE_STATUS' => 'GENERATED',
  310. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  311. ];
  312. $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  313. $destXmlFile = "{$powiazanieDirLocation}/relations.xml";
  314. rename($xmlFile, $destXmlFile);
  315. }
  316. $sqlArr['ID'] = $row['ID'];
  317. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  318. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  319. unlink($generatePowiazaniaPhpFile);
  320. unlink($generatePowiazaniaPidFile);
  321. unlink($generatePowiazaniaResultFile);
  322. if (file_exists($generatePowiazaniaSqlFile)) unlink($generatePowiazaniaSqlFile);
  323. } elseif (file_exists($generatePowiazaniaPidFile)) {
  324. $pid = file_get_contents($generatePowiazaniaPidFile);
  325. }
  326. }
  327. } catch (Exception $e) {
  328. echo $e->getMessage()."\n";
  329. }
  330. }
  331. private function reloadCache_reTeryt() {
  332. Lib::loadClass('Teryt');
  333. function reTeryt($table) {
  334. $tableConf = [
  335. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  336. 'kodPocztowy' => 'Kod_pocztowy',
  337. 'miejscowosc' => 'Miejscowosc',
  338. 'ulica' => 'Ulica',
  339. ],
  340. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  341. 'kodPocztowy' => 'kodPocztowy',
  342. 'miejscowosc' => 'miejscowosc',
  343. 'ulica' => 'ulica',
  344. ],
  345. ];
  346. $columns = ['kodPocztowy', 'miejscowosc', 'ulica'];
  347. $query = "select * from `{$table}` where TERYT_SYM is null";
  348. try {
  349. $adresy = DB::getPDO()->fetchall($query);
  350. foreach ($adresy as $adres) {
  351. $search = [];
  352. foreach ($columns as $column) $search[$column] = $adres[$tableConf[$table][$column]];
  353. try {
  354. $teryt = Teryt::search($search);
  355. if ($teryt) {
  356. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  357. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  358. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  359. }
  360. } catch (Exception $e) {
  361. }
  362. }
  363. } catch (Exception $e) {
  364. }
  365. }
  366. // reTeryt('BI_audit_ENERGA_RUM_KONTRAHENCI');
  367. reTeryt('BI_audit_ENERGA_PRACOWNICY_adresy');
  368. }
  369. private function reloadCache_updateAll() {
  370. $tables = [
  371. 'BI_audit_ENERGA_PRACOWNICY' => [
  372. 'fields' => [
  373. 'nip' => 'nip',
  374. 'regon' => 'regon',
  375. 'pesel' => 'pesel',
  376. ],
  377. //'where' => '',
  378. ],
  379. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  380. 'fields' => [
  381. 'TERYT_SYM' => 'TERYT_SYM',
  382. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  383. 'nrDomu' => 'nrBudynku',
  384. 'nrLokalu' => 'nrLokalu',
  385. ],
  386. //'where' => '',
  387. ],
  388. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  389. 'fields' => [
  390. 'nip' => 'NIP',
  391. 'regon' => 'REGON',
  392. 'pesel' => 'PESEL',
  393. 'TERYT_SYM' => 'TERYT_SYM',
  394. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  395. 'nrDomu' => 'Numer_budynku',
  396. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  397. ],
  398. 'where' => "ownCompany != 'Y'",
  399. ],
  400. 'BI_audit_KW_requested_person' => [
  401. 'fields' => [
  402. 'pesel' => 'Seller_person_pesel',
  403. 'krs' => 'Seller_person_KRS',
  404. 'nip' => 'Seller_person_NIP',
  405. 'regon' => 'Seller_person_REGON',
  406. ],
  407. //'where' => '',
  408. ],
  409. ];
  410. $queries[] = "delete from BI_audit_ALL where BASE = 0";
  411. $queries[] = "delete from BI_audit_ALL_ref where BASE = 0";
  412. $queries[] = "delete from BI_audit_ALL_ref_RELATIONS where BASE = 0";
  413. foreach ($tables as $name => $table) {
  414. if (isset($table['where']) && $table['where']) $where = "where {$table['where']}";
  415. else $where = '';
  416. $queries[] = "insert into BI_audit_ALL (REMOTE_TABLE, REMOTE_ID, " . implode(", ", array_keys($table['fields'])) . ") select '{$name}', ID, " . implode(", ", $table['fields']) . " from {$name} {$where}";
  417. }
  418. $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";
  419. $queries[] = "set @var = (select round(coalesce(max(ID), '0.5')) from BI_audit_ALL_ref_RELATIONS)";
  420. $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";
  421. $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";
  422. $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";
  423. foreach ($queries as $query) DB::getPDO()->query($query);
  424. $BiAuditRelations = new BiAuditRelations();
  425. $query = "select ID from BI_audit_ALL where BASE = 0";
  426. $result = DB::query($query);
  427. while ($row = DB::fetch($result)) $BiAuditRelations->findRelations($row->ID);
  428. }
  429. public function doReloadCache() {
  430. $powiazaniaDirLocation = $this->getMainDirectory();
  431. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  432. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  433. try {
  434. $this->reloadCache_reTeryt();
  435. $this->reloadCache_updateAll();
  436. file_put_contents($reloadCacheResultFile, "ok");
  437. } catch (Exception $e) {
  438. file_put_contents($reloadCacheResultFile, $e->getMessage());
  439. }
  440. }
  441. public function doGeneratePowiazania($ID) {
  442. $powiazaniaDirLocation = $this->getMainDirectory();
  443. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  444. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  445. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  446. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  447. $sqlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.sql";
  448. file_put_contents($pidFile, getmypid());
  449. $tablesConf = [
  450. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  451. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  452. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  453. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  454. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  455. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  456. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  457. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  458. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  459. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  460. ];
  461. try {
  462. $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'";
  463. $result = DB::getPDO()->fetchAll($query);
  464. if (!$result) throw new Exception("Błąd danych");
  465. $powiazanie = $result[0];
  466. if (!preg_match('/^[[:digit:]]+(,[[:digit:]]+)*$/', $powiazanie['BI_analiza_employees'])) throw new Exception("Błąd danych");
  467. $query = "select ID from BI_audit_ALL where REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and REMOTE_ID in ({$powiazanie['BI_analiza_employees']})";
  468. $result = DB::getPDO()->fetchAll($query);
  469. $BiAuditPowiazania = new BiAuditPowiazania($powiazanie['BI_analiza_depth']);
  470. foreach ($result as $row) $BiAuditPowiazania->findPowiazania($row['ID']);
  471. if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  472. $xml = $BiAuditPowiazania->asXml();
  473. file_put_contents($xmlFile, $xml);
  474. file_put_contents($sqlFile, mysql_real_escape_string(gzcompress($xml)));
  475. $powiazania = $BiAuditPowiazania->asArray('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  476. if (!$powiazania) return false;
  477. DB::getPDO()->query($query);
  478. foreach ($powiazania['BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row'] as $row) {
  479. $powiazaniaRowSqlArr = [];
  480. $string_concat_path = [];
  481. foreach ($row['object'] as $i => $object) {
  482. $powiazaniaRowObjectSqlArr = [];
  483. $table = array_keys($object)[0];
  484. if (!isset($tablesConf[$table])) throw new Exception("Błąd danych konfiguracyjnych");
  485. $concat = "table='{$table}'";
  486. if (isset($object['relation_from'])) $concat .= ";relation_from='{$object['relation_from']}'";
  487. foreach ($tablesConf[$table] as $field) {
  488. if ($object[$table][$field]) $concat .= ";{$field}='{$object[$table][$field]}'";
  489. }
  490. if ($i == 0) $powiazaniaRowSqlArr['string_concat_from'] = $concat;
  491. elseif ($i == count($row['object']) - 1) $powiazaniaRowSqlArr['string_concat_to'] = $concat;
  492. else $string_concat_path[] = $concat;
  493. }
  494. $powiazaniaRowSqlArr['string_concat_path'] = implode(' / ', $string_concat_path);
  495. $powiazaniaRowSqlArr['A_ADM_COMPANY'] = $powiazanie['A_ADM_COMPANY'];
  496. $powiazaniaRowSqlArr['A_CLASSIFIED'] = $powiazanie['A_CLASSIFIED'];
  497. $id_row = DB::getPDO()->insert("BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row", $powiazaniaRowSqlArr);
  498. if (!$id_row) throw new Exception("Błąd bazy danych");
  499. DB::getPDO()->insert('CRM__#REF_TABLE__25', ["PRIMARY_KEY" => $ID, "REMOTE_PRIMARY_KEY" => $id_row]);
  500. }
  501. file_put_contents($resultFile, "ok");
  502. } catch (Exception $e) {
  503. file_put_contents($resultFile, $e->getMessage());
  504. }
  505. }
  506. public function reinstallAction() {
  507. $this->reinstall();
  508. die('OK');
  509. }
  510. public function reinstall() {
  511. $sqlList = array();
  512. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  513. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  514. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  515. SQL;
  516. $db = DB::getDB();
  517. if ($db->has_errors()) {
  518. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  519. }
  520. foreach ($sqlList as $sqlName => $sql) {
  521. $res = $db->query($sql);
  522. if ($db->has_errors()) {
  523. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  524. }
  525. }
  526. }
  527. }
  528. class BiAuditRelations {
  529. private $RELATIONS_ID = [];
  530. private $relations = [
  531. 'nip' => ['nip'],
  532. 'regon' => ['regon'],
  533. 'krs' => ['krs'],
  534. 'pesel' => ['pesel'],
  535. 'adres' => ['TERYT_SYM', 'TERYT_SYM_UL', 'nrDomu', 'nrLokalu'],
  536. ];
  537. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  538. public function __construct() {
  539. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  540. $result = DB::getPDO()->fetchAll($query);
  541. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  542. }
  543. private function getRelationID($name) {
  544. if (!isset($this->RELATIONS_ID[$name])) {
  545. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  546. $newID = DB::getPDO()->fetchValue($query);
  547. $this->RELATIONS_ID[$name] = $newID;
  548. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  549. DB::getPDO()->query($query);
  550. }
  551. return $this->RELATIONS_ID[$name];
  552. }
  553. public function findRelations($ID) {
  554. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  555. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  556. $row = $result[0];
  557. $joins = [];
  558. $items = '';
  559. foreach ($this->relations as $name => $columns) {
  560. $ok = 0;
  561. $join = [];
  562. foreach ($columns as $column) {
  563. $join[] = "t1.{$column} = t2.{$column}";
  564. if ($row[$column]) $ok++;
  565. }
  566. if ($ok / count($columns) > 0.5) {
  567. $joins[] = "(" . implode(" and ", $join) . ")";
  568. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  569. }
  570. }
  571. if (!$joins) return false;
  572. $query = "select t2.ID as ID, t1.REMOTE_TABLE as REMOTE_TABLE_1, t2.REMOTE_TABLE as REMOTE_TABLE_2 {$items} " .
  573. "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})";
  574. $result = DB::getPDO()->fetchAll($query);
  575. foreach ($result as $row) {
  576. $relationID = 0;
  577. foreach ($this->relations as $name => $v) {
  578. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  579. }
  580. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  581. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  582. if (!$end1) {
  583. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2})";
  584. DB::getPDO()->query($query);
  585. }
  586. if (!$end2) {
  587. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1})";
  588. DB::getPDO()->query($query);
  589. }
  590. }
  591. }
  592. }
  593. class BiAuditPowiazania {
  594. private $DEPTH;
  595. private $path = [];
  596. private $results = [];
  597. private $items_results = [];
  598. private $relations = [];
  599. public function __construct($depth = 0) {
  600. $this->DEPTH = (int) $depth;
  601. }
  602. public function findPowiazania($ID, $relation = "", $end = 0) {
  603. if (isset($this->path[$ID])) return false;
  604. $this->path[$ID] = $relation;
  605. if (!$relation) $relation = 0;
  606. if ($end) {
  607. $this->results[] = $this->path;
  608. array_pop($this->path);
  609. return true;
  610. }
  611. if (count($this->path) > $this->DEPTH) {
  612. array_pop($this->path);
  613. return false;
  614. }
  615. $nodes = [];
  616. if ($relation) $where = "and ({$relation} & ref.RELATION_ID) != {$relation}";
  617. else $where = "";
  618. $query = "select ref.ID2, RELATION_ID, END from BI_audit_ALL_ref ref where ref.ID1 = '{$ID}' {$where}";
  619. $result = DB::query($query);
  620. while ($row = DB::fetch($result)) $nodes[$row->ID2] = ['relation' => (int) $row->RELATION_ID, 'end' => $row->END];
  621. foreach ($nodes as $node => $data) $this->findPowiazania($node, $data['relation'], $data['end']);
  622. array_pop($this->path);
  623. }
  624. private function relationName($ID) {
  625. if (!isset($this->relations[$ID])) {
  626. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  627. $result = DB::getPDO()->fetchAll($query);
  628. $rels = array_map('reset', $result);
  629. $this->relations[$ID] = implode(", ", $rels);
  630. }
  631. return $this->relations[$ID];
  632. }
  633. private function generateItemsResults() {
  634. $xmlRoot2 = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  635. $xmlElements = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  636. $this->items_results = [];
  637. $items_kontrahenci = [];
  638. $items_kw_person = [];
  639. $kontrahenci = [];
  640. $kw_person = [];
  641. // $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');
  642. // $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');
  643. // echo "{$refTableUmowyToKontrahenci} :: {$refTableKwToKwPerson} \n";
  644. // $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');
  645. // echo ":: " . $refTablePowiazaniaToPowiazaniaRow . "::\n";
  646. foreach ($this->results as $result) {
  647. $item_results = [];
  648. foreach ($result as $ID => $rel) {
  649. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  650. $row = DB::getPDO()->fetchFirst($query);
  651. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  652. $obj = DB::fetch(DB::query($query));
  653. $item_result = [$row['REMOTE_TABLE'] => (array) $obj];
  654. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  655. $item_results['object'][] = $item_result;
  656. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  657. $kontrahenci[] = $row['REMOTE_ID'];
  658. $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']}'";
  659. $res = DB::query($query);
  660. if (mysql_num_rows($res)) {
  661. $umowy = [];
  662. while ($obj = DB::fetch($res)) $umowy[] = (array) $obj;
  663. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  664. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  665. $items_kontrahenci[] = $item_kontrahenci;
  666. }
  667. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  668. $kw_person[] = $row['REMOTE_ID'];
  669. $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']}'";
  670. $res = DB::query($query);
  671. if (mysql_num_rows($res)) {
  672. $kw = [];
  673. while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
  674. $item_kw_person['ID'] = $row['REMOTE_ID'];
  675. $item_kw_person['BI_audit_KW_requested'] = $kw;
  676. $items_kw_person[] = $item_kw_person;
  677. }
  678. }
  679. }
  680. $this->items_results[$xmlRoot2][$xmlElements][] = $item_results;
  681. }
  682. $this->items_results[$xmlRoot2]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  683. $this->items_results[$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;
  684. }
  685. public function asXml() {
  686. if (!$this->results) return null;
  687. if (!$this->items_results) $this->generateItemsResults();
  688. $xmlRoot = "RelatedFeatureRoot";
  689. return V::arrayToXML($this->items_results, true, $xmlRoot);
  690. }
  691. public function asArray($subArray = null) {
  692. if (!$this->results) return null;
  693. if (!$this->items_results) $this->generateItemsResults();
  694. if ($subArray) {
  695. if (isset($this->items_results[$subArray])) return $this->items_results[$subArray];
  696. else return [];
  697. } else return $this->items_results;
  698. }
  699. public function powiazaniaFound() {
  700. if ($this->results) return true;
  701. else return false;
  702. }
  703. }