BiAuditGenerate.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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 powiazania($ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA) {
  141. try {
  142. $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA}'");
  143. if (!$powiazania) throw new Exception("Błąd danych");
  144. $this->powiazanie = $powiazania[0];
  145. switch ($this->powiazanie['FILE_STATUS']) {
  146. case "NONE":
  147. $this->initializePowiazania();
  148. break;
  149. default:
  150. throw new Exception("Błędny status rekordu");
  151. }
  152. } catch (Exception $e) {
  153. SE_Layout::alert('danger',$e->getMessage());
  154. $_SESSION['REFERER'] = $this->REFERER;
  155. ?>
  156. <div class="container" style="text-align:center">
  157. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
  158. </div>
  159. <?php
  160. }
  161. }
  162. public function defaultAction() {
  163. SE_Layout::gora();
  164. SE_Layout::menu();
  165. if (isset($_SESSION['REFERER'])) {
  166. $this->REFERER = $_SESSION['REFERER'];
  167. unset($_SESSION['REFERER']);
  168. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  169. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  170. 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'));
  171. else SE_Layout::alert('danger','Błąd parametru');
  172. SE_Layout::dol();
  173. }
  174. public function doGenerate() {
  175. function generatePhpScript($function) {
  176. return '<?php
  177. ini_set("memory_limit", "4G");
  178. define("DS", DIRECTORY_SEPARATOR);
  179. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  180. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  181. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  182. ini_set("display_startup_errors", "0");
  183. ini_set("log_errors", "1");
  184. ini_set("error_log", "/var/log/apache2/error_log");
  185. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  186. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  187. Lib::loadClass("Router");
  188. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  189. ';
  190. }
  191. try {
  192. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  193. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  194. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  195. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  196. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  197. ### Ustawienie zmiennych
  198. $powiazaniaDirLocation = $this->getMainDirectory();
  199. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  200. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  201. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  202. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  203. ### Utworzenie niezbędnych katalogów i plików
  204. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0755, true);
  205. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  206. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  207. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Y'";
  208. $result = DB::getPDO()->fetchAll($query);
  209. if ($result) {
  210. if (file_exists($reloadCachePhpFile)) {
  211. if (file_exists($reloadCacheResultFile)) {
  212. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  213. if ($reloadCacheResult == "ok") {
  214. $sqlArr = [
  215. 'FILE_STATUS_info' => 'Odświeżono cache, oczekiwanie na wygenerowanie powiązań',
  216. 'BI_analiza_reloadCache' => 'N',
  217. ];
  218. } else {
  219. $sqlArr = [
  220. 'FILE_STATUS' => 'ERROR',
  221. 'FILE_STATUS_info' => "Wystąpił błąd podczas odświeżania cache ({$reloadCacheResult})",
  222. 'BI_analiza_reloadCache' => 'N',
  223. ];
  224. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  225. $result = DB::getPDO()->fetchAll($query);
  226. }
  227. foreach ($result as $row) {
  228. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  229. }
  230. unlink($reloadCachePhpFile);
  231. unlink($reloadCacheResultFile);
  232. } else exit;
  233. } else {
  234. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  235. $result = DB::getPDO()->fetchValue($query);
  236. if ($result) exit;
  237. file_put_contents($reloadCachePhpFile, generatePhpScript('doReloadCache()'));
  238. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  239. exit;
  240. }
  241. }
  242. ### Generowanie powiązań
  243. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  244. $result = DB::getPDO()->fetchAll($query);
  245. foreach ($result as $row) {
  246. $sqlArr = [
  247. 'ID' => $row['ID'],
  248. 'FILE_STATUS' => 'IN_PROGRESS',
  249. 'FILE_STATUS_info' => 'W trakcie generowania powiązań',
  250. ];
  251. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  252. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  253. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  254. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  255. file_put_contents($generatePowiazaniaPhpFile, generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  256. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  257. }
  258. ### Weryfikacja świeżo wygenerowanych powiązań
  259. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  260. $result = DB::getPDO()->fetchAll($query);
  261. foreach ($result as $row) {
  262. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  263. if (file_exists($generatePowiazaniaResultFile)) {
  264. $generatePowiazaniaResult = file_get_contents($generatePowiazaniaResultFile);
  265. if ($generatePowiazaniaResult == "ok") {
  266. $sqlArr = [
  267. 'FILE_STATUS' => 'GENERATED',
  268. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  269. ];
  270. } else {
  271. $sqlArr = [
  272. 'FILE_STATUS' => 'ERROR',
  273. 'FILE_STATUS_info' => "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult})",
  274. ];
  275. }
  276. $sqlArr['ID'] = $row['ID'];
  277. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  278. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  279. unlink($generatePowiazaniaPhpFile);
  280. unlink($generatePowiazaniaResultFile);
  281. }
  282. }
  283. } catch (Exception $e) {
  284. echo $e->getMessage()."\n";
  285. }
  286. }
  287. private function reloadCache_reTeryt() {
  288. Lib::loadClass('Teryt');
  289. function reTeryt($table) {
  290. $tableConf = [
  291. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  292. 'kodPocztowy' => 'Kod_pocztowy',
  293. 'miejscowosc' => 'Miejscowosc',
  294. 'ulica' => 'Ulica',
  295. ],
  296. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  297. 'kodPocztowy' => 'kodPocztowy',
  298. 'miejscowosc' => 'miejscowosc',
  299. 'ulica' => 'ulica',
  300. ],
  301. ];
  302. $columns = ['kodPocztowy', 'miejscowosc', 'ulica'];
  303. $query = "select * from `{$table}` where TERYT_SYM is null";
  304. try {
  305. $adresy = DB::getPDO()->fetchall($query);
  306. foreach ($adresy as $adres) {
  307. $search = [];
  308. foreach ($columns as $column) $search[$column] = $adres[$tableConf[$table][$column]];
  309. try {
  310. $teryt = Teryt::search($search);
  311. if ($teryt) {
  312. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  313. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  314. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  315. }
  316. } catch (Exception $e) {
  317. }
  318. }
  319. } catch (Exception $e) {
  320. }
  321. }
  322. // reTeryt('BI_audit_ENERGA_RUM_KONTRAHENCI');
  323. reTeryt('BI_audit_ENERGA_PRACOWNICY_adresy');
  324. }
  325. private function reloadCache_updateAll() {
  326. $tables = [
  327. 'BI_audit_ENERGA_PRACOWNICY' => [
  328. 'fields' => [
  329. 'nip' => 'nip',
  330. 'regon' => 'regon',
  331. 'pesel' => 'pesel',
  332. ],
  333. //'where' => '',
  334. ],
  335. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  336. 'fields' => [
  337. 'TERYT_SYM' => 'TERYT_SYM',
  338. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  339. 'nrDomu' => 'nrBudynku',
  340. 'nrLokalu' => 'nrLokalu',
  341. ],
  342. //'where' => '',
  343. ],
  344. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  345. 'fields' => [
  346. 'nip' => 'NIP',
  347. 'regon' => 'REGON',
  348. 'pesel' => 'PESEL',
  349. 'TERYT_SYM' => 'TERYT_SYM',
  350. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  351. 'nrDomu' => 'Numer_budynku',
  352. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  353. ],
  354. 'where' => "ownCompany != 'Y'",
  355. ],
  356. 'BI_audit_KW_requested_person' => [
  357. 'fields' => [
  358. 'pesel' => 'Seller_person_pesel',
  359. 'krs' => 'Seller_person_KRS',
  360. 'nip' => 'Seller_person_NIP',
  361. 'regon' => 'Seller_person_REGON',
  362. ],
  363. //'where' => '',
  364. ],
  365. ];
  366. $queries[] = "delete from BI_audit_ALL where BASE = 0";
  367. $queries[] = "delete from BI_audit_ALL_ref where BASE = 0";
  368. $queries[] = "delete from BI_audit_ALL_ref_RELATIONS where BASE = 0";
  369. foreach ($tables as $name => $table) {
  370. if (isset($table['where']) && $table['where']) $where = "where {$table['where']}";
  371. else $where = '';
  372. $queries[] = "insert into BI_audit_ALL (REMOTE_TABLE, REMOTE_ID, " . implode(", ", array_keys($table['fields'])) . ") select '{$name}', ID, " . implode(", ", $table['fields']) . " from {$name} {$where}";
  373. }
  374. $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";
  375. $queries[] = "set @var = (select round(coalesce(max(ID), '0.5')) from BI_audit_ALL_ref_RELATIONS)";
  376. $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";
  377. $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";
  378. $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";
  379. foreach ($queries as $query) DB::getPDO()->query($query);
  380. $BiAuditRelations = new BiAuditRelations();
  381. $query = "select ID from BI_audit_ALL where BASE = 0";
  382. $result = DB::query($query);
  383. while ($row = DB::fetch($result)) $BiAuditRelations->findRelations($row->ID);
  384. }
  385. public function doReloadCache() {
  386. $powiazaniaDirLocation = $this->getMainDirectory();
  387. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  388. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  389. try {
  390. $this->reloadCache_reTeryt();
  391. $this->reloadCache_updateAll();
  392. file_put_contents($reloadCacheResultFile, "ok");
  393. } catch (Exception $e) {
  394. file_put_contents($reloadCacheResultFile, $e->getMessage());
  395. }
  396. }
  397. public function doGeneratePowiazania($ID) {
  398. $powiazaniaDirLocation = $this->getMainDirectory();
  399. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  400. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  401. $tablesConf = [
  402. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  403. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  404. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  405. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  406. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  407. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  408. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  409. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  410. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  411. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  412. ];
  413. try {
  414. $query = "select BI_analiza_depth, BI_analiza_employees from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$ID}' and FILE_STATUS = 'IN_PROGRESS' and BI_analiza_reloadCache != 'Y'";
  415. $result = DB::getPDO()->fetchAll($query);
  416. if (!$result) throw new Exception("Błąd danych");
  417. $powiazanie = $result[0];
  418. if (!preg_match('/^[[:digit:]]+(,[[:digit:]]+)?$/', $powiazanie['BI_analiza_employees'])) throw new Exception("Błąd danych");
  419. $query = "select ID from BI_audit_ALL where REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and REMOTE_ID in ({$powiazanie['BI_analiza_employees']})";
  420. $result = DB::getPDO()->fetchAll($query);
  421. $BiAuditPowiazania = new BiAuditPowiazania($powiazanie['BI_analiza_depth']);
  422. foreach ($result as $row) $BiAuditPowiazania->findPowiazania($row['ID']);
  423. $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $ID);
  424. $xmlFile = "{$powiazanieDirLocation}/relations_id{$ID}_depth{$powiazanie['BI_analiza_depth']}.xml";
  425. file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  426. $powiazania = $BiAuditPowiazania->asArray('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  427. if (!$powiazania) return false;
  428. $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=1";
  429. DB::getPDO()->query($query);
  430. foreach ($powiazania['BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row'] as $row) {
  431. $powiazaniaRowSqlArr = [];
  432. $string_concat_path = [];
  433. foreach ($row['object'] as $i => $object) {
  434. $powiazaniaRowObjectSqlArr = [];
  435. $table = array_keys($object)[0];
  436. if (!isset($tablesConf[$table])) throw new Exception("Błąd danych konfiguracyjnych");
  437. $concat = "table='{$table}'";
  438. if (isset($object['relation_from'])) $concat .= ";relation_from='{$object['relation_from']}'";
  439. foreach ($tablesConf[$table] as $field) {
  440. if ($object[$table][$field]) $concat .= ";{$field}='{$object[$table][$field]}'";
  441. }
  442. if ($i == 0) $powiazaniaRowSqlArr['string_concat_from'] = $concat;
  443. elseif ($i == count($row['object']) - 1) $powiazaniaRowSqlArr['string_concat_to'] = $concat;
  444. else $string_concat_path[] = $concat;
  445. }
  446. $powiazaniaRowSqlArr['string_concat_path'] = implode(' / ', $string_concat_path);
  447. $id_row = DB::getPDO()->insert("BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row", $powiazaniaRowSqlArr);
  448. if (!$id_row) throw new Exception("Błąd bazy danych"); DB::getPDO()->insert('CRM__#REF_TABLE__25', ["PRIMARY_KEY" => $ID, "REMOTE_PRIMARY_KEY" => $id_row]);
  449. }
  450. file_put_contents($generatePowiazaniaResultFile, "ok");
  451. } catch (Exception $e) {
  452. file_put_contents($generatePowiazaniaResultFile, $e->getMessage());
  453. }
  454. }
  455. public function reinstallAction() {
  456. $this->reinstall();
  457. die('OK');
  458. }
  459. public function reinstall() {
  460. $sqlList = array();
  461. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  462. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  463. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  464. SQL;
  465. $db = DB::getDB();
  466. if ($db->has_errors()) {
  467. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  468. }
  469. foreach ($sqlList as $sqlName => $sql) {
  470. $res = $db->query($sql);
  471. if ($db->has_errors()) {
  472. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  473. }
  474. }
  475. }
  476. }
  477. class BiAuditRelations {
  478. private $RELATIONS_ID = [];
  479. private $relations = [
  480. 'nip' => ['nip'],
  481. 'regon' => ['regon'],
  482. 'krs' => ['krs'],
  483. 'pesel' => ['pesel'],
  484. 'adres' => ['TERYT_SYM', 'TERYT_SYM_UL', 'nrDomu', 'nrLokalu'],
  485. ];
  486. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  487. public function __construct() {
  488. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  489. $result = DB::getPDO()->fetchAll($query);
  490. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  491. }
  492. private function getRelationID($name) {
  493. if (!isset($this->RELATIONS_ID[$name])) {
  494. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  495. $newID = DB::getPDO()->fetchValue($query);
  496. $this->RELATIONS_ID[$name] = $newID;
  497. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  498. DB::getPDO()->query($query);
  499. }
  500. return $this->RELATIONS_ID[$name];
  501. }
  502. public function findRelations($ID) {
  503. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  504. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  505. $row = $result[0];
  506. $joins = [];
  507. $items = '';
  508. foreach ($this->relations as $name => $columns) {
  509. $ok = 0;
  510. $join = [];
  511. foreach ($columns as $column) {
  512. $join[] = "t1.{$column} = t2.{$column}";
  513. if ($row[$column]) $ok++;
  514. }
  515. if ($ok / count($columns) > 0.5) {
  516. $joins[] = "(" . implode(" and ", $join) . ")";
  517. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  518. }
  519. }
  520. if (!$joins) return false;
  521. $query = "select t2.ID as ID, t1.REMOTE_TABLE as REMOTE_TABLE_1, t2.REMOTE_TABLE as REMOTE_TABLE_2 {$items} " .
  522. "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})";
  523. $result = DB::getPDO()->fetchAll($query);
  524. foreach ($result as $row) {
  525. $relationID = 0;
  526. foreach ($this->relations as $name => $v) {
  527. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  528. }
  529. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  530. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  531. if (!$end1) {
  532. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2})";
  533. DB::getPDO()->query($query);
  534. }
  535. if (!$end2) {
  536. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1})";
  537. DB::getPDO()->query($query);
  538. }
  539. }
  540. }
  541. }
  542. class BiAuditPowiazania {
  543. private $DEPTH;
  544. private $path = [];
  545. private $results = [];
  546. private $items_results = [];
  547. private $relations = [];
  548. public function __construct($depth = 0) {
  549. $this->DEPTH = (int) $depth;
  550. }
  551. public function findPowiazania($ID, $relation = "", $end = 0) {
  552. if (isset($this->path[$ID])) return false;
  553. $this->path[$ID] = $relation;
  554. if (!$relation) $relation = 0;
  555. if ($end) {
  556. $this->results[] = $this->path;
  557. array_pop($this->path);
  558. return true;
  559. }
  560. if (count($this->path) > $this->DEPTH) {
  561. array_pop($this->path);
  562. return false;
  563. }
  564. $nodes = [];
  565. if ($relation) $where = "and ({$relation} & ref.RELATION_ID) != {$relation}";
  566. else $where = "";
  567. $query = "select ref.ID2, RELATION_ID, END from BI_audit_ALL_ref ref where ref.ID1 = '{$ID}' {$where}";
  568. $result = DB::query($query);
  569. while ($row = DB::fetch($result)) $nodes[$row->ID2] = ['relation' => (int) $row->RELATION_ID, 'end' => $row->END];
  570. foreach ($nodes as $node => $data) $this->findPowiazania($node, $data['relation'], $data['end']);
  571. array_pop($this->path);
  572. }
  573. private function relationName($ID) {
  574. if (!isset($this->relations[$ID])) {
  575. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  576. $result = DB::getPDO()->fetchAll($query);
  577. $rels = array_map('reset', $result);
  578. $this->relations[$ID] = implode(", ", $rels);
  579. }
  580. return $this->relations[$ID];
  581. }
  582. private function generateItemsResults() {
  583. $xmlRoot2 = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  584. $xmlElements = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  585. $this->items_results = [];
  586. $items_kontrahenci = [];
  587. $items_kw_person = [];
  588. $kontrahenci = [];
  589. $kw_person = [];
  590. // $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');
  591. // $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');
  592. // echo "{$refTableUmowyToKontrahenci} :: {$refTableKwToKwPerson} \n";
  593. // $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');
  594. // echo ":: " . $refTablePowiazaniaToPowiazaniaRow . "::\n";
  595. foreach ($this->results as $result) {
  596. $item_results = [];
  597. foreach ($result as $ID => $rel) {
  598. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  599. $row = DB::getPDO()->fetchFirst($query);
  600. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  601. $obj = DB::fetch(DB::query($query));
  602. $item_result = [$row['REMOTE_TABLE'] => (array) $obj];
  603. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  604. $item_results['object'][] = $item_result;
  605. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  606. $kontrahenci[] = $row['REMOTE_ID'];
  607. $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']}'";
  608. $res = DB::query($query);
  609. if (mysql_num_rows($res)) {
  610. $umowy = [];
  611. while ($obj = DB::fetch($res)) $umowy[] = (array) $obj;
  612. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  613. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  614. $items_kontrahenci[] = $item_kontrahenci;
  615. }
  616. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  617. $kw_person[] = $row['REMOTE_ID'];
  618. $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']}'";
  619. $res = DB::query($query);
  620. if (mysql_num_rows($res)) {
  621. $kw = [];
  622. while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
  623. $item_kw_person['ID'] = $row['REMOTE_ID'];
  624. $item_kw_person['BI_audit_KW_requested'] = $kw;
  625. $items_kw_person[] = $item_kw_person;
  626. }
  627. }
  628. }
  629. $this->items_results[$xmlRoot2][$xmlElements][] = $item_results;
  630. }
  631. $this->items_results[$xmlRoot2]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  632. $this->items_results[$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;
  633. }
  634. public function asXml() {
  635. if (!$this->items_results) $this->generateItemsResults();
  636. $xmlRoot = "RelatedFeatureRoot";
  637. return V::arrayToXML($this->items_results, true, $xmlRoot);
  638. }
  639. public function asArray($subArray = null) {
  640. if (!$this->items_results) $this->generateItemsResults();
  641. if ($subArray) {
  642. if (isset($this->items_results[$subArray])) return $this->items_results[$subArray];
  643. else return [];
  644. } else return $this->items_results;
  645. }
  646. }