BiAuditGenerate.php 32 KB

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