BiAuditGenerate.php 37 KB

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