BiAuditGenerate.php 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729
  1. <?php
  2. //TODO optimal - akcja aby doruzcic do pracownikow do analizy jakas spolke z kontekstu przegladania KRS - zapytanie przyklad:
  3. // insert ignore into BI_audit_ENERGA_PRACOWNICY (imiona, nazwisko, pesel, source )
  4. // select p.imiona, p.nazwisko, p.pesel, 'ENSO_STORA/zadanie' from `BI_audit_KRS_person` as p
  5. // right join `CRM__#REF_TABLE__12` as r on r.`REMOTE_PRIMARY_KEY`=p.ID
  6. // right join BI_audit_KRS as k on k.ID=r.`PRIMARY_KEY`
  7. // where k.`nazwa` like '%Stora%enso%';
  8. //TODO mozliwosc przerwania przetwarzania
  9. Lib::loadClass('RouteBase');
  10. Lib::loadClass('FoldersConfig');
  11. Lib::loadClass('FileUploader');
  12. Lib::loadClass('ProcesHelper');
  13. Lib::loadClass('SchemaFactory');
  14. Lib::loadClass('Core_AclHelper');
  15. Lib::loadClass('Core_AclSimpleSchemaBase');
  16. class Route_UrlAction_BiAuditGenerate extends RouteBase {
  17. private $powiazanie = null;
  18. private $SOURCE = null;
  19. private $REFERER;
  20. public function handleAuth() {
  21. if (!User::logged()) {
  22. User::authByRequest();
  23. }
  24. }
  25. private function getDirectory($table, $id) {
  26. $folderConf = FoldersConfig::getAll($table.'_COLUMN');
  27. $record = new stdClass;
  28. $record->ID = $id;
  29. $uploader = new FileUploader($table.'_COLUMN', $record);
  30. $errMsg = "";
  31. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$$errMsg}", 404);
  32. $uploader->findFolder();
  33. return $uploader->getDestLocalPath(true);
  34. }
  35. private function getUrl($table, $id) {
  36. $folderConf = FoldersConfig::getAll($table.'_COLUMN');
  37. $record = new stdClass;
  38. $record->ID = $id;
  39. $uploader = new FileUploader($table.'_COLUMN', $record);
  40. $errMsg = "";
  41. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$$errMsg}", 404);
  42. return $uploader->getFolderWeb() . "/" . $uploader->getDestFolder(true);
  43. }
  44. private function getMainDirectory() {
  45. $folderConf = FoldersConfig::getAll('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_COLUMN');
  46. if (!isset($folderConf['mount_point'])) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
  47. return $folderConf['mount_point'];
  48. }
  49. private function initializePowiazaniaForm() {
  50. ?>
  51. <div class="container" style="margin-top:20px">
  52. <form class="form-horizontal" method="post">
  53. <legend>
  54. Generowanie powiązań :: <?=$this->powiazanie['L_APPOITMENT_INFO']?>
  55. <span class="pull-right"># <?=$this->powiazanie['ID']?></span>
  56. </legend>
  57. <div class="form-group">
  58. <div class="col-sm-12">
  59. <h4>Wybierz pracowników, dla których mają zostać wyszukane powiązania</h4>
  60. <table class="table table-bordered table-hover table-striped" height=5>
  61. <thead>
  62. <tr style="text-align:center; background-color:lightgray">
  63. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  64. <td width=1>ID</td>
  65. <td>Imiona</td>
  66. <td>Nazwisko</td>
  67. <td>Pesel</td>
  68. <td>NIP</td>
  69. <td>Regon</td>
  70. <td>source</td>
  71. </tr>
  72. </thead>
  73. <tbody>
  74. <?php
  75. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
  76. $queryFeatures = $acl->buildQuery(['limit' => 0]);
  77. $pracownicy = $queryFeatures->getItems();
  78. foreach ($pracownicy as $pracownik) {
  79. ?>
  80. <tr>
  81. <td><input type="checkbox" name="prID[]" value="<?=$pracownik['ID']?>" onClick="toggle(this)"/></td>
  82. <td align="right"><?=$pracownik['ID']?></td>
  83. <td><?=$pracownik['imiona']?></td>
  84. <td><?=$pracownik['nazwisko']?></td>
  85. <td><?=$pracownik['pesel']?></td>
  86. <td><?=$pracownik['nip']?></td>
  87. <td><?=$pracownik['regon']?></td>
  88. <td><?=$pracownik['source']?></td>
  89. </tr>
  90. <?php
  91. }
  92. ?>
  93. </tbody>
  94. </table>
  95. </div>
  96. </div>
  97. <div class="form-group">
  98. <label class="col-sm-2 control-label">
  99. Odśwież cache
  100. </label>
  101. <div class="col-sm-2">
  102. <select name="reloadCache" class="form-control">
  103. <option value="No" selected>Nie</option>
  104. <option value="Part">Częściowe</option>
  105. <option value="Full">Pełne</option>
  106. </select>
  107. </div>
  108. </div>
  109. <div class="form-group">
  110. <div class="col-sm-offset-2 col-sm-10">
  111. Częściowe odświeżenie wymagane w przypadku, gdy dokonano dowolnych zmian w tabelach pracowników/kontrahentów.<br/>
  112. Pełne odświeżenie wymagane w przypadku modyfikacji baz KRS lub CEiDG (UWAGA - trwa to wiele godzin)
  113. </div>
  114. </div>
  115. <div class="form-group">
  116. <div class="col-sm-12">
  117. <div class="containter" style="text-align:center">
  118. <button type="submit" class="btn btn-primary" name="action" value="initialize">Generuj</button>
  119. <a href="<?=$this->REFERER?>" class="btn btn-default">Anuluj</a>
  120. </div>
  121. </div>
  122. </div>
  123. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  124. </form>
  125. </div>
  126. <script language="JavaScript">
  127. <!--
  128. function toggleAll(source) {
  129. checkboxes = document.getElementsByName('prID[]');
  130. for(var i=0, n=checkboxes.length;i<n;i++) checkboxes[i].checked = source.checked;
  131. }
  132. function toggle(source) {
  133. checkboxes = document.getElementsByName('prID[]');
  134. all = true;
  135. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked == false) all = false;
  136. source.form['checkAll'].checked = all;
  137. }
  138. -->
  139. </script>
  140. <?php
  141. }
  142. private function initializePowiazaniaSave() {
  143. $prID = V::get('prID', array(), $_POST);
  144. if (!$prID) throw new Exception("Nie wybrano żadnego pracownika!");
  145. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
  146. $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
  147. $kontrahenci = $queryFeatures->getItems();
  148. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_KW_requested_person/BI_audit_KW_requested_person');
  149. $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
  150. $requestedPersons = $queryFeatures->getItems();
  151. if (!($kontrahenci || $requestedPersons)) throw new Exception("Nie znaleziono żadnego obiektu końcowego");
  152. $sqlUpdate = ['FILE_STATUS' => 'TO_GENERATE'];
  153. $reloadCache = V::get('reloadCache', 'No', $_POST);
  154. $reloadCacheAvailable = ['Full', 'Part', 'No'];
  155. if (!in_array($reloadCache, $reloadCacheAvailable)) throw new Exception("Błąd formularza!");
  156. $sqlUpdate['BI_analiza_reloadCache'] = $reloadCache;
  157. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part')";
  158. $result = DB::getPDO()->fetchValue($query);
  159. if ($result) $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache (wymagane dla innego rekordu)';
  160. elseif ($reloadCache != 'No') $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache';
  161. else $sqlUpdate['FILE_STATUS_info'] = "Oczekuje na wygenerowanie powiązań";
  162. if ($this->powiazanie) { // wyzwolone z poziomu tabeli BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA - aktualizujemy istniejący rekord
  163. $powiazanieID = $this->powiazanie['ID'];
  164. } else { // wyzwolone z poziomu tabeli BI_audit_ENERGA_PRACOWNICY - dodajemy nowy rekord
  165. if (count($prID) != 1) throw new Exception("Błąd formularza!");
  166. if (!($lAppoitmentInfo = V::get('info', false, $_POST))) throw new Exception("Błąd formularza!");
  167. if (!($BiAnalizaDepth = V::get('depth', false, $_POST))) throw new Exception("Błąd formularza!");
  168. $query = "select * from BI_audit_ENERGA_PRACOWNICY where ID='{$prID[0]}'";
  169. $result = DB::getPDO()->fetchFirst($query);
  170. if (!$result) throw new Exception("Błąd formularza!");
  171. $sqlInsert = [
  172. 'L_APPOITMENT_INFO' => $lAppoitmentInfo,
  173. 'A_STATUS' => 'NORMAL',
  174. 'A_STATUS_INFO' => 'Dodane przez BiAuditGenerate z poziomu tabeli BI_audit_ENERGA_PRACOWNICY',
  175. 'A_ADM_COMPANY' => $result['A_ADM_COMPANY'],
  176. 'A_CLASSIFIED' => $result['A_CLASSIFIED'],
  177. 'FILE_STATUS' => 'NONE',
  178. 'FILE_STATUS_info' => 'Oczekuję na zdefiniowanie danych wejściowych',
  179. 'BI_analiza_reloadCache' => $sqlUpdate['BI_analiza_reloadCache'],
  180. 'BI_analiza_depth' => $BiAnalizaDepth,
  181. ];
  182. $powiazanieID = DB::getDB()->ADD_NEW_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', (object)$sqlInsert);
  183. if ($powiazanieID) SE_Layout::alert('success','Dodano rekord do wygenerowania powiązań');
  184. else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  185. }
  186. $sqlUpdate['ID'] = $powiazanieID;
  187. $this->truncatePowiazaniaFromDB($powiazanieID);
  188. $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  189. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
  190. foreach ($prID as $v) DB::getPDO()->insert($refPowiazaniaToPracownicy, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $v]);
  191. $refPowiazaniaToKontrahenci = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  192. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI');
  193. foreach ($kontrahenci as $kontrahent) DB::getPDO()->insert($refPowiazaniaToKontrahenci, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $kontrahent['ID']]);
  194. $refPowiazaniaToKwRequestedPreson = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  195. 'default_db__x3A__BI_audit_KW_requested_person:BI_audit_KW_requested_person');
  196. foreach ($requestedPersons as $requestedPerson) DB::getPDO()->insert($refPowiazaniaToKwRequestedPreson, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $requestedPerson['ID']]);
  197. $affected = DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlUpdate);
  198. if ($affected) {
  199. if ($this->powiazanie) {
  200. SE_Layout::alert('success','Oznaczono rekord do wygenerowania powiązań');
  201. ?>
  202. <div class="container" style="text-align:center">
  203. <a href="<?=$this->REFERER?>" class="btn btn-primary">Powrót</a>
  204. </div>
  205. <?php
  206. }
  207. } else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  208. }
  209. private function initializePowiazania() {
  210. switch (V::get('action', '', $_POST)) {
  211. case "initialize":
  212. $this->initializePowiazaniaSave();
  213. break;
  214. default:
  215. $this->initializePowiazaniaForm();
  216. }
  217. }
  218. private function showPowiazania() {
  219. // echo "Statystyki znalezionych powiązań [TODO]";
  220. $dir = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  221. $pdfFile = "{$dir}/relations.pdf";
  222. $htmlFile = "{$dir}/html/relations-{$this->powiazanie['ID']}.html";
  223. $htmlZipFile = "{$dir}/html.zip";
  224. $url = $this->getUrl('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  225. $pdfUrl = "{$url}/relations.pdf";
  226. $htmlUrl = "{$url}/html/relations-{$this->powiazanie['ID']}.html";
  227. $htmlZipUrl = "{$url}/html.zip";
  228. ?>
  229. <div class="container" style="margin-top:20px">
  230. <legend>
  231. Wygenerowany raport nr <?=$this->powiazanie['ID']?>
  232. </legend>
  233. <div class="form-group">
  234. <div class="col-sm-12">
  235. <?php
  236. if (file_exists($pdfFile)) {
  237. ?>
  238. <a href="<?=$pdfUrl?>" target="_blank" class="btn btn-primary">Pokaż raport PDF</a>
  239. <?php
  240. }
  241. if (file_exists($htmlFile)) {
  242. ?>
  243. <a href="<?=$htmlUrl?>" target="_blank" class="btn btn-primary">Pokaż raport HTML</a>
  244. <?php
  245. }
  246. if (file_exists($htmlZipFile)) {
  247. ?>
  248. <a href="<?=$htmlZipUrl?>" target="_blank" download="Raport <?=$this->powiazanie['ID']?>.zip" class="btn btn-primary">Pobierz raport HTML</a>
  249. <?php
  250. }
  251. ?>
  252. <br/><br/><a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  253. </div>
  254. </div>
  255. </div>
  256. <?php
  257. }
  258. private function showPowiazaniaList() {
  259. switch (V::get('action', '', $_POST)) {
  260. case "initialize":
  261. $this->initializePowiazaniaSave();
  262. break;
  263. }
  264. $this->showPowiazaniaListForm();
  265. }
  266. private function showPowiazaniaListForm() {
  267. if (!$this->SOURCE['ID']) throw new Exception("Błąd danych");
  268. elseif ($this->SOURCE['TABLE'] != 'BI_audit_ENERGA_PRACOWNICY') throw new Exception("Błąd danych");
  269. $query = "select * from `{$this->SOURCE['TABLE']}` where ID = '{$this->SOURCE['ID']}'";
  270. $pracownik = DB::getPDO()->fetchFirst($query);
  271. if (!$pracownik) throw new Exception("Błąd danych");
  272. ?>
  273. <div class="container" style="margin-top:20px">
  274. <legend>
  275. Lista wygenerowanych powiązań :: <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>
  276. <span class="pull-right"># <?=$pracownik['ID']?></span>
  277. </legend>
  278. <div class="form-group">
  279. <div class="col-sm-12">
  280. <h4>Lista wygenerowanych powiązań, w których znajduje się pracownik</h4>
  281. <table class="table table-bordered table-hover table-striped" height=5>
  282. <thead>
  283. <tr style="text-align:center; background-color:lightgray">
  284. <td width=1>ID</td>
  285. <td>Adnotacje</td>
  286. <td>Głębokość analizy</td>
  287. <td>Status raportu</td>
  288. <td>Status raportu - informacje</td>
  289. <td>Indywidualny raport</td>
  290. <td width=1></td>
  291. </tr>
  292. </thead>
  293. <tbody>
  294. <?php
  295. $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  296. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
  297. $query = "select `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.*
  298. from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  299. join `{$refPowiazaniaToPracownicy}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPracownicy}`.`PRIMARY_KEY`
  300. where `REMOTE_PRIMARY_KEY` = '{$this->SOURCE['ID']}'";
  301. $result = DB::getPDO()->fetchAll($query);
  302. if (!$result) echo '<tr><td align="center" colspan="7">Brak znalezionych powiązań</td></tr>';
  303. else {
  304. foreach ($result as $row) {
  305. $query = "select count(*) from `{$refPowiazaniaToPracownicy}` where `PRIMARY_KEY` = '{$row['ID']}'";
  306. $count = DB::getPDO()->fetchValue($query);
  307. ?>
  308. <tr>
  309. <td align="right"><?=$row['ID']?></td>
  310. <td><?=$row['L_APPOITMENT_INFO']?></td>
  311. <td><?=$row['BI_analiza_depth']?></td>
  312. <td><?=$row['FILE_STATUS']?></td>
  313. <td><?=$row['FILE_STATUS_info']?></td>
  314. <td><?=($count > 1 ? 'Nie' : 'Tak')?></td>
  315. <td><?=UI::hButtonPost("Pokaż w tabeli", ['class' => 'btn-info btn-xs', 'action' => "index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA&ff_ID={$row['ID']}", 'data' > ['f_ID' => $row['ID']]])?></td>
  316. </tr>
  317. <?php
  318. }
  319. }
  320. ?>
  321. </tbody>
  322. </table>
  323. </div>
  324. </div>
  325. <div class="form-group">
  326. <div class="col-sm-12">
  327. <h4>Dodaj nowe zadanie generowania powiazań dla tego pracownika</h4>
  328. </div>
  329. </div>
  330. <form class="form-horizontal" method="post">
  331. <div class="form-group">
  332. <label class="col-sm-4 control-label">Głębokość poszukiwań (liczba rekurencji)</label>
  333. <div class="col-sm-1">
  334. <input type="number" class="form-control" name="depth" data-bind="value:replyNumber" min="1" max="9" value="6" required/>
  335. </div>
  336. </div>
  337. <div class="form-group">
  338. <label class="col-sm-4 control-label">Adnotacje</label>
  339. <div class="col-sm-4">
  340. <input type="text" class="form-control" name="info" value="Indywidualnie dla <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>" required/>
  341. </div>
  342. </div>
  343. <div class="form-group">
  344. <label class="col-sm-4 control-label">
  345. Odśwież cache
  346. </label>
  347. <div class="col-sm-2">
  348. <select name="reloadCache" class="form-control">
  349. <option value="No" selected>Nie</option>
  350. <option value="Part">Częściowe</option>
  351. <option value="Full">Pełne</option>
  352. </select>
  353. </div>
  354. </div>
  355. <div class="form-group">
  356. <div class="col-sm-offset-4 col-sm-8">
  357. Częściowe odświeżenie wymagane w przypadku, gdy dokonano dowolnych zmian w tabelach pracowników/kontrahentów.<br/>
  358. Pełne odświeżenie wymagane w przypadku modyfikacji baz KRS lub CEiDG (UWAGA - trwa to wiele godzin)
  359. </div>
  360. </div>
  361. <div class="form-group">
  362. <div class="col-sm-12">
  363. <div class="containter" style="text-align:center">
  364. <button type="submit" class="btn btn-primary" name="action" value="initialize">Generuj</button>
  365. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  366. </div>
  367. </div>
  368. </div>
  369. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  370. <input type="hidden" name="prID[]" value="<?=$pracownik['ID']?>">
  371. </form>
  372. </div>
  373. <?php
  374. }
  375. private function powiazania() {
  376. try {
  377. if (!$this->SOURCE) throw new Exception("Błąd danych");
  378. elseif (!(isset($this->SOURCE['TABLE']) && isset($this->SOURCE['ID']))) throw new Exception("Błąd danych");
  379. switch ($this->SOURCE['TABLE']) {
  380. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  381. $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->SOURCE['ID']}'");
  382. if (!$powiazania) throw new Exception("Błąd danych");
  383. $this->powiazanie = $powiazania[0];
  384. switch ($this->powiazanie['FILE_STATUS']) {
  385. case "NONE":
  386. $this->initializePowiazania();
  387. break;
  388. case "GENERATED":
  389. $this->showPowiazania();
  390. break;
  391. default: throw new Exception("Błędny status rekordu");
  392. }
  393. break;
  394. case "BI_audit_ENERGA_PRACOWNICY":
  395. $this->showPowiazaniaList();
  396. break;
  397. case "BI_audit_KRS":
  398. $this->importKrsToPracownicySearch($this->SOURCE['ID']);
  399. break;
  400. case "BI_audit_KRS_person":
  401. $this->showKrsForKrsPerson();
  402. break;
  403. default: throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate");
  404. }
  405. } catch (Exception $e) {
  406. SE_Layout::alert('danger',$e->getMessage());
  407. $_SESSION['REFERER'] = $this->REFERER;
  408. ?>
  409. <div class="container" style="text-align:center">
  410. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
  411. </div>
  412. <?php
  413. }
  414. }
  415. private function importKrsToPracownicy() {
  416. $action = V::get('action', '', $_POST);
  417. switch ($action) {
  418. case "search":
  419. $this->importKrsToPracownicySearch();
  420. break;
  421. default: $this->importKrsToPracownicyForm();
  422. }
  423. }
  424. private function importKrsToPracownicyForm() {
  425. ?>
  426. <div class="container" style="margin-top:20px">
  427. <legend>
  428. Importowanie osób z KRS do tabeli pracowników
  429. </legend>
  430. <div class="form-group">
  431. <div class="col-sm-12">
  432. <h4>Znajdź podmiot</h4>
  433. </div>
  434. </div>
  435. <form class="form-horizontal" method="post">
  436. <div class="form-group">
  437. <label class="col-sm-1 control-label">Nazwa</label>
  438. <div class="col-sm-4">
  439. <input type="text" class="form-control" name="nazwa" title="Podaj nazwę podmiotu">
  440. </div>
  441. </div>
  442. <div class="form-group">
  443. <label class="col-sm-1 control-label">KRS</label>
  444. <div class="col-sm-2">
  445. <input type="text" class="form-control" name="krs" pattern="^[0-9]{0,10}$" title="Podaj KRS"/>
  446. </div>
  447. </div>
  448. <div class="form-group">
  449. <label class="col-sm-1 control-label">NIP</label>
  450. <div class="col-sm-2">
  451. <input type="text" class="form-control" name="nip" pattern="^[0-9]{0,10}$" title="Podaj NIP (bez kresek i bez oznaczenia kraju)"/>
  452. </div>
  453. </div>
  454. <div class="form-group">
  455. <label class="col-sm-1 control-label">Regon</label>
  456. <div class="col-sm-2">
  457. <input type="text" class="form-control" name="regon" pattern="^[0-9]{0,9}$" title="Podaj regon"/>
  458. </div>
  459. </div>
  460. <div class="form-group">
  461. <div class="col-sm-offset-1 col-sm-11">
  462. <button type="submit" class="btn btn-primary" name="action" value="search">Szukaj</button>
  463. </div>
  464. </div>
  465. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  466. </form>
  467. </div>
  468. <?php
  469. }
  470. private function importKrsToPracownicySearch($krsId = null) {
  471. try {
  472. $subaction = V::get('subaction', '', $_POST);
  473. switch ($subaction) {
  474. case "listKrsPerson":
  475. $krsId = V::get('krsId', 0, $_POST, int);
  476. break;
  477. case "addKrsPersonToPracownicy":
  478. $personId = V::get('personId', [], $_POST);
  479. if (!$personId) throw new Exception("Błąd formularza");
  480. $query = "insert into BI_audit_ENERGA_PRACOWNICY (source, imiona, nazwisko, pesel) select 'KRS', imiona, nazwisko, pesel from BI_audit_KRS_person where ID in (" . implode(", ", $personId) . ")";
  481. DB::getPDO()->query($query);
  482. SE_Layout::alert('success', "Pomyślnie zaimportowano " . count($personId) . " pracownik" . ((count($personId) == 1) ? "a" : "ów"));
  483. $this->importKrsToPracownicyForm();
  484. return;
  485. case "addKrsCompanyToKontrachenci":
  486. $krsId = V::get('krsId', 0, $_POST, int);
  487. if (!$krsId) throw new Exception("Błąd formularza");
  488. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (uwagi, Pelna_nazwa_kontrahenta, REGON, NIP, KRS) select 'import z KRS', nazwa, regon, nip, krs from BI_audit_KRS where ID = ".$krsId." ";
  489. DB::getPDO()->query($query);
  490. return;
  491. }
  492. if ($krsId) {
  493. $where = ["ID = '{$krsId}'"];
  494. } else {
  495. $items = [
  496. "nazwa" => 'like',
  497. "krs" => '=',
  498. "nip" => '=',
  499. "regon" => '=',
  500. ];
  501. $form = [];
  502. foreach ($items as $item => $type) {
  503. if ($param = V::get($item, '', $_POST)) {
  504. if ($type == 'like') $param = "%{$param}%";
  505. $form[$item] = DB::getPDO()->quote($param);
  506. }
  507. }
  508. if (!$form) throw new Exception("Nie wypełniono żadnego pola wyszukiwania!");
  509. $where = [];
  510. foreach ($form as $name => $value) $where[] = "`{$name}` {$items[$name]} {$value}";
  511. }
  512. } catch (Exception $e) {
  513. SE_Layout::alert('danger', $e->getMessage());
  514. $this->importKrsToPracownicyForm();
  515. return;
  516. }
  517. $query = "select * from `BI_audit_KRS` where " . implode(" and ", $where) . "order by ID limit 1001";
  518. $result = DB::getPDO()->fetchAll($query);
  519. if (count($result) == 1001) {
  520. SE_Layout::alert('danger', 'Znaleziono zbyt wiele wyników. Doprecyzuj parametry wyszukiwania.');
  521. $this->importKrsToPracownicyForm();
  522. return;
  523. } elseif (count($result) == 1) {
  524. $krsId = $result[0]['ID'];
  525. }
  526. ?>
  527. <div class="container" style="margin-top:20px">
  528. <form method="post">
  529. <legend>
  530. Importowanie osób z KRS do tabeli pracowników
  531. </legend>
  532. <div class="form-group">
  533. <div class="col-sm-12">
  534. <h4>Znalezione podmioty:</h4>
  535. </div>
  536. </div>
  537. <div class="form-group">
  538. <div class="col-sm-12">
  539. <table class="table table-bordered table-hover table-striped" height=5>
  540. <thead>
  541. <tr style="text-align:center; background-color:lightgray">
  542. <td width=1>Lp.</td>
  543. <td>Nazwa</td>
  544. <td>Adres</td>
  545. <td>KRS</td>
  546. <td>NIP</td>
  547. <td>Regon</td>
  548. <td>(Akcja)</td>
  549. <?php
  550. if (count($result) > 1) {
  551. ?>
  552. <td width=1>Wybierz</td>
  553. <?php
  554. }
  555. ?>
  556. </tr>
  557. </thead>
  558. <tbody>
  559. <?php
  560. if (!$result) echo '<tr><td align="center" colspan="7">Nie znaleziono podmiotu</td></tr>';
  561. else {
  562. $lp = 1;
  563. foreach ($result as $row) {
  564. $adres = $row['A_miejscowosc'];
  565. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  566. if ($row['A_nrDomu']) {
  567. $adres .= " {$row['A_nrDomu']}";
  568. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  569. }
  570. ?>
  571. <tr>
  572. <td align="right"><?=$lp++?></td>
  573. <td><?=htmlspecialchars($row['nazwa'])?></td>
  574. <td><?=htmlspecialchars($adres)?></td>
  575. <td><?=$row['krs']?></td>
  576. <td><?=$row['nip']?></td>
  577. <td><?=$row['regon']?></td>
  578. <td>
  579. <button type="submit" class="btn btn-primary" name="subaction" value="addKrsCompanyToKontrachenci" onClick="return validate(this)">Dodaj firme do kontrachentow.</button>
  580. </td>
  581. <?php
  582. if (count($result) > 1) {
  583. ?>
  584. <td align="center">
  585. <input type="radio" name="krsId" value="<?=$row['ID']?>"/>
  586. </td>
  587. <?php
  588. }
  589. ?>
  590. </tr>
  591. <?php
  592. }
  593. }
  594. ?>
  595. </tbody>
  596. </table>
  597. </div>
  598. </div>
  599. <?php
  600. if (count($result) > 1) {
  601. ?>
  602. <div class="form-group">
  603. <div class="col-sm-12">
  604. <?php
  605. foreach (array_keys($items) as $item) {
  606. ?>
  607. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  608. <?php
  609. }
  610. ?>
  611. <div class="containter" style="text-align:center">
  612. <button type="submit" class="btn btn-primary" name="subaction" value="listKrsPerson">Znajdź osoby powiązane z podmiotem</button>
  613. <a href="" class="btn btn-default">Powrót</a>
  614. </div>
  615. </div>
  616. </div>
  617. <?php
  618. } elseif ($krsId) {
  619. ?>
  620. <div class="form-group">
  621. <div class="col-sm-12">
  622. <h4>Znalezione osoby:</h4>
  623. </div>
  624. </div>
  625. <div class="form-group">
  626. <div class="col-sm-12">
  627. <table class="table table-bordered table-hover table-striped" height=5>
  628. <thead>
  629. <tr style="text-align:center; background-color:lightgray">
  630. <td width=1>Lp.</td>
  631. <td>Nazwisko</td>
  632. <td>Imiona</td>
  633. <td>Pesel</td>
  634. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  635. </tr>
  636. </thead>
  637. <tbody>
  638. <?php
  639. $refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
  640. $query = "select person.*, pracownicy.ID as pracownicyId from `{$refKrsToKrsPerson}` ref join `BI_audit_KRS_person` person on ref.REMOTE_PRIMARY_KEY = person.ID left join BI_audit_ENERGA_PRACOWNICY pracownicy on person.pesel = pracownicy.pesel where ref.PRIMARY_KEY = '{$krsId}'";
  641. $result = DB::getPDO()->fetchAll($query);
  642. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono osób powiązanych z podmiotem</td></tr>';
  643. else {
  644. $lp = 1;
  645. foreach ($result as $row) {
  646. ?>
  647. <tr<?=($row['pracownicyId'] ? ' style="color:darkgrey"' : '')?>>
  648. <td align="right"><?=$lp++?></td>
  649. <td><?=$row['nazwisko']?></td>
  650. <td><?=$row['imiona']?></td>
  651. <td><?=$row['pesel']?></td>
  652. <td><input type="checkbox" name="personId[]" value="<?=$row['ID']?>" onClick="toggle(this)" <?=($row['pracownicyId'] ? "disabled" : "")?>/></td>
  653. </tr>
  654. <?php
  655. }
  656. }
  657. ?>
  658. </tbody>
  659. </table>
  660. <div class="containter" style="text-align:center">
  661. <button type="submit" class="btn btn-primary" name="subaction" value="addKrsPersonToPracownicy" onClick="return validate(this)">Dodaj zaznaczone osoby do tabeli pracowników</button>
  662. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-default">Powrót</a>
  663. </div>
  664. </div>
  665. </div>
  666. <?php
  667. }
  668. ?>
  669. <input type="hidden" name="action" value="search">
  670. </form>
  671. </div>
  672. <script language="JavaScript">
  673. <!--
  674. function toggleAll(source) {
  675. checkboxes = document.getElementsByName('personId[]');
  676. checked = false;
  677. for(var i=0, n=checkboxes.length;i<n;i++) {
  678. if (!checkboxes[i].disabled) {
  679. checkboxes[i].checked = source.checked;
  680. checked = true;
  681. }
  682. }
  683. if (source.checked && (!checked)) source.checked = false;
  684. }
  685. function toggle(source) {
  686. checkboxes = document.getElementsByName('personId[]');
  687. all = true;
  688. for(var i=0, n=checkboxes.length;i<n;i++) if(!checkboxes[i].disabled && checkboxes[i].checked == false) all = false;
  689. source.form['checkAll'].checked = all;
  690. }
  691. function validate(source) {
  692. checkboxes = document.getElementsByName('personId[]');
  693. checked = false;
  694. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked) checked = true;
  695. if (!checked) alert('Nie wybrano żadnej osoby!');
  696. return checked;
  697. }
  698. -->
  699. </script>
  700. <?php
  701. }
  702. private function showKrsForKrsPerson() {
  703. $query = "select * from BI_audit_KRS_person where ID = '{$this->SOURCE['ID']}'";
  704. $result = DB::getPDO()->fetchFirst($query);
  705. ?>
  706. <div class="container" style="margin-top:20px">
  707. <legend>
  708. Lista podmiotów, w których występuje <?="{$result['nazwisko']} {$result['imiona']}" . ($result['pesel'] ? " (PESEL: {$result['pesel']})" : "")?>
  709. </legend>
  710. <div class="form-group">
  711. <div class="col-sm-12">
  712. <table class="table table-bordered table-hover table-striped" height=5>
  713. <thead>
  714. <tr style="text-align:center; background-color:lightgray">
  715. <td width=1>Lp.</td>
  716. <td>Nazwa</td>
  717. <td>Adres</td>
  718. <td>KRS</td>
  719. <td>NIP</td>
  720. <td>Regon</td>
  721. <td width=1></td>
  722. </tr>
  723. </thead>
  724. <tbody>
  725. <?php
  726. $refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
  727. $query = "select krs.* from `{$refKrsToKrsPerson}` ref join BI_audit_KRS krs on ref.PRIMARY_KEY = krs.ID where ref.REMOTE_PRIMARY_KEY = '{$this->SOURCE['ID']}'";
  728. $result = DB::getPDO()->fetchAll($query);
  729. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono powiązanych podmiotów</td></tr>';
  730. else {
  731. $lp = 1;
  732. foreach ($result as $row) {
  733. $adres = $row['A_miejscowosc'];
  734. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  735. if ($row['A_nrDomu']) {
  736. $adres .= " {$row['A_nrDomu']}";
  737. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  738. }
  739. ?>
  740. <tr>
  741. <td align="right"><?=$lp++?></td>
  742. <td><?=htmlspecialchars($row['nazwa'])?></td>
  743. <td><?=htmlspecialchars($adres)?></td>
  744. <td><?=$row['krs']?></td>
  745. <td><?=$row['nip']?></td>
  746. <td><?=$row['regon']?></td>
  747. <td><?=UI::hButtonPost("Pokaż w tabeli", ['class' => 'btn-info btn-xs', 'action' => "index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_KRS/BI_audit_KRS&ff_ID={$row['ID']}", 'data' > ['f_ID' => $row['ID']]])?></td>
  748. </tr>
  749. <?php
  750. }
  751. }
  752. ?>
  753. </tbody>
  754. </table>
  755. </div>
  756. </div>
  757. <div class="form-group">
  758. <div class="col-sm-12">
  759. <div class="containter" style="text-align:center">
  760. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-default">Powrót</a>
  761. </div>
  762. </div>
  763. </div>
  764. </div>
  765. <?php
  766. }
  767. public function defaultAction() {
  768. SE_Layout::gora();
  769. SE_Layout::menu();
  770. if (isset($_SESSION['REFERER'])) {
  771. $this->REFERER = $_SESSION['REFERER'];
  772. unset($_SESSION['REFERER']);
  773. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  774. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  775. if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
  776. elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
  777. elseif (($ID = V::get('ID_BI_audit_KRS', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  778. elseif (($ID = V::get('ID_BI_audit_KRS_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS_person';
  779. if ($this->SOURCE) {
  780. $this->SOURCE['ID'] = $ID;
  781. $this->powiazania();
  782. }
  783. elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
  784. switch ($TABLE) {
  785. case "default_db/BI_audit_ENERGA_PRACOWNICY":
  786. $this->importKrsToPracownicy();
  787. break;
  788. default: SE_Layout::alert('danger', 'Błąd parametru');
  789. }
  790. }
  791. else SE_Layout::alert('danger', 'Błąd parametru');
  792. SE_Layout::dol();
  793. }
  794. private function getRefsTables($namespace) {
  795. try {
  796. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  797. if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
  798. $fields = $item['field'];
  799. $refsTables = [];
  800. foreach ($fields as $field) {
  801. list($type, $child) = explode(":", $field['xsdType'], 2);
  802. if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) $refsTables[] = ACL::getRefTable($namespace, $child);
  803. }
  804. return $refsTables;
  805. } catch (Exception $e) {
  806. echo "{$namespace} - {$e->getMessage}";
  807. return [];
  808. }
  809. }
  810. private function truncatePowiazaniaFromDB($ID) {
  811. $refsTables = $this->getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  812. if (!$refsTables) return null;
  813. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  814. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  815. $refsTables = array_diff($refsTables, [$refPowiazaniaToPowiazaniaRow]);
  816. $query = "delete from `" . implode("`, `", $refsTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  817. foreach ($refsTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  818. $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  819. DB::getPDO()->query($query);
  820. }
  821. private function deleteResultsFromDB($ID) {
  822. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  823. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  824. $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
  825. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  826. $refsTables = $this->getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  827. $sqlDeleteFrom = "delete from
  828. `{$refPowiazaniaToPowiazaniaRow}`,
  829. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
  830. `{$refPowiazaniaRowToPowiazaniaRowObject}`,
  831. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
  832. $sqlUsing = "
  833. using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  834. join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
  835. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
  836. join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
  837. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
  838. $sqlWhere = "
  839. where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  840. foreach ($refsTables as $refTable) {
  841. $sqlDeleteFrom .= ",\n`{$refTable}`";
  842. $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  843. }
  844. $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
  845. DB::getPDO()->query($query);
  846. }
  847. public function doGenerate() {
  848. function generatePhpScript($function) {
  849. return '<?php
  850. ini_set("memory_limit", "4G");
  851. define("DS", DIRECTORY_SEPARATOR);
  852. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  853. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  854. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  855. ini_set("display_startup_errors", "0");
  856. ini_set("log_errors", "1");
  857. ini_set("error_log", "/var/log/apache2/error_log");
  858. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  859. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  860. Lib::loadClass("Router");
  861. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  862. ';
  863. }
  864. try {
  865. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  866. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  867. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  868. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  869. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  870. ### Ustawienie zmiennych
  871. $powiazaniaDirLocation = $this->getMainDirectory();
  872. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  873. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  874. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  875. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  876. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  877. ### Utworzenie niezbędnych katalogów i plików
  878. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0755, true);
  879. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  880. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  881. $doGenerate = true;
  882. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part') and FILE_STATUS = 'TO_GENERATE'";
  883. $result = DB::getPDO()->fetchAll($query);
  884. if ($result) {
  885. $doGenerate = false;
  886. $sqlArr = [];
  887. if (file_exists($reloadCachePhpFile)) {
  888. if (file_exists($reloadCacheResultFile)) {
  889. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  890. if ($reloadCacheResult == "ok") {
  891. $sqlArr = [
  892. 'FILE_STATUS_info' => 'Odświeżono cache, oczekiwanie na wygenerowanie powiązań',
  893. 'BI_analiza_reloadCache' => 'No',
  894. ];
  895. $doGenerate = true;
  896. } else {
  897. $sqlArr = [
  898. 'FILE_STATUS' => 'ERROR',
  899. 'FILE_STATUS_info' => "Wystąpił błąd podczas odświeżania cache ({$reloadCacheResult})",
  900. ];
  901. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  902. $result = DB::getPDO()->fetchAll($query);
  903. }
  904. unlink($reloadCachePhpFile);
  905. unlink($reloadCachePidFile);
  906. unlink($reloadCacheResultFile);
  907. } elseif (file_exists($reloadCachePidFile)) {
  908. $pid = file_get_contents($reloadCachePidFile);
  909. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  910. $processShouldBeRunning = "php {$reloadCachePhpFile}";
  911. if ($processRunning != $processShouldBeRunning) {
  912. if (!file_exists($reloadCacheResultFile)) {
  913. $sqlArr = [
  914. 'FILE_STATUS' => 'ERROR',
  915. 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas odświeżania cache - nie znaleziono procesu potomnego",
  916. ];
  917. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  918. $result = DB::getPDO()->fetchAll($query);
  919. unlink($reloadCachePhpFile);
  920. unlink($reloadCachePidFile);
  921. unlink($reloadCacheResultFile);
  922. }
  923. }
  924. }
  925. } else {
  926. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  927. $result2 = DB::getPDO()->fetchValue($query);
  928. if ($result2) {
  929. $sqlArr = [
  930. 'FILE_STATUS_info' => 'Wstrzymano odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  931. ];
  932. } else {
  933. $sqlArr = [
  934. 'FILE_STATUS_info' => 'W trakcie odświeżania cache',
  935. ];
  936. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
  937. $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
  938. file_put_contents($reloadCachePhpFile, generatePhpScript("doReloadCache({$fullReloadCache})"));
  939. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  940. }
  941. }
  942. if ($sqlArr) {
  943. foreach ($result as $row) {
  944. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  945. }
  946. }
  947. }
  948. ### Generowanie powiązań
  949. if ($doGenerate) {
  950. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
  951. $result = DB::getPDO()->fetchAll($query);
  952. foreach ($result as $row) {
  953. $sqlArr = [
  954. 'ID' => $row['ID'],
  955. 'FILE_STATUS' => 'IN_PROGRESS',
  956. 'FILE_STATUS_info' => 'W trakcie generowania powiązań',
  957. ];
  958. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  959. $this->deleteResultsFromDB($row['ID']);
  960. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  961. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  962. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  963. file_put_contents($generatePowiazaniaPhpFile, generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  964. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  965. }
  966. }
  967. ### Weryfikacja świeżo wygenerowanych powiązań
  968. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  969. $result = DB::getPDO()->fetchAll($query);
  970. foreach ($result as $row) {
  971. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  972. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  973. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  974. $generatePowiazaniaPdfFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pdf";
  975. $generatePowiazaniaHtmlDir = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.html";
  976. $generatePowiazaniaHtmlZipFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.zip";
  977. $error = false;
  978. $success = false;
  979. $sqlArr = [];
  980. if (file_exists($generatePowiazaniaResultFile)) {
  981. $generatePowiazaniaResult = file_get_contents($generatePowiazaniaResultFile);
  982. if ($generatePowiazaniaResult == "ok") {
  983. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.xml";
  984. if (file_exists($xmlFile)) {
  985. if (filesize($xmlFile)) {
  986. $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  987. if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0777, false);
  988. if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
  989. else $success = true;
  990. } else $error = "Wystąpił nieznany błąd - plk xml został wygenerowany niepoprawnie";
  991. } else $error = "Wystąpił nienzany błąd - nie znaleziono pliku xml";
  992. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult})";
  993. } elseif (file_exists($generatePowiazaniaPidFile)) {
  994. $pid = file_get_contents($generatePowiazaniaPidFile);
  995. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  996. $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
  997. if ($processRunning != $processShouldBeRunning) {
  998. if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
  999. }
  1000. }
  1001. if ($error) {
  1002. $sqlArr = [
  1003. 'FILE_STATUS' => 'ERROR',
  1004. 'FILE_STATUS_info' => $error,
  1005. ];
  1006. $this->deleteResultsFromDB($row['ID']);
  1007. if (file_exists($xmlFile)) unlink($xmlFile);
  1008. } elseif ($success) {
  1009. $sqlArr = [
  1010. 'FILE_STATUS' => 'GENERATED',
  1011. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  1012. ];
  1013. $destXmlFile = "{$powiazanieDirLocation}/relations.xml";
  1014. $destPdfFile = "{$powiazanieDirLocation}/relations.pdf";
  1015. $destHtmlDir = "{$powiazanieDirLocation}/html";
  1016. $destHtmlZipFile = "{$powiazanieDirLocation}/html.zip";
  1017. rename($xmlFile, $destXmlFile);
  1018. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1019. if (file_exists($generatePowiazaniaHtmlDir)) {
  1020. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1021. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1022. }
  1023. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1024. }
  1025. if ($sqlArr) {
  1026. $sqlArr['ID'] = $row['ID'];
  1027. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1028. if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
  1029. if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
  1030. if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
  1031. }
  1032. }
  1033. } catch (Exception $e) {
  1034. echo $e->getMessage()."\n";
  1035. }
  1036. }
  1037. private function reloadCache_reTeryt($full = false) {
  1038. Lib::loadClass('Teryt');
  1039. function reTeryt($table) {
  1040. $tableConf = [
  1041. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1042. 'kodPocztowy' => 'Kod_pocztowy',
  1043. 'miejscowosc' => 'Miejscowosc',
  1044. 'ulica' => 'Ulica',
  1045. ],
  1046. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1047. 'kodPocztowy' => 'kodPocztowy',
  1048. 'miejscowosc' => 'miejscowosc',
  1049. 'ulica' => 'ulica',
  1050. ],
  1051. 'BI_audit_KRS' => [
  1052. 'wojewodztwo' => 'S_wojewodztwo',
  1053. 'powiat' => 'S_powiat',
  1054. 'gmina' => 'S_gmina',
  1055. 'miejscowosc' => 'A_miejscowosc',
  1056. 'ulica' => 'A_ulica',
  1057. 'kodPocztowy' => 'A_kod',
  1058. ],
  1059. 'BI_audit_CEIDG' => [
  1060. 'wojewodztwo' => 'wojewodztwo',
  1061. 'powiat' => 'powiat',
  1062. 'gmina' => 'gmina',
  1063. 'miejscowosc' => 'miejscowosc',
  1064. 'ulica' => 'ulica',
  1065. 'kodPocztowy' => 'kodPocztowy',
  1066. ],
  1067. ];
  1068. $columns = ['kodPocztowy', 'miejscowosc', 'ulica'];
  1069. $query = "select * from `{$table}` where TERYT_SYM is null";
  1070. try {
  1071. $adresy = DB::getPDO()->fetchall($query);
  1072. foreach ($adresy as $adres) {
  1073. $search = [];
  1074. foreach ($columns as $column) $search[$column] = $adres[$tableConf[$table][$column]];
  1075. try {
  1076. $teryt = Teryt::search($search);
  1077. if ($teryt) {
  1078. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  1079. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  1080. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  1081. }
  1082. } catch (Exception $e) {
  1083. }
  1084. }
  1085. } catch (Exception $e) {
  1086. }
  1087. }
  1088. if ($full) {
  1089. reTeryt('BI_audit_KRS');
  1090. reTeryt('BI_audit_CEIDG');
  1091. }
  1092. reTeryt('BI_audit_ENERGA_RUM_KONTRAHENCI');
  1093. reTeryt('BI_audit_ENERGA_PRACOWNICY_adresy');
  1094. }
  1095. private function reloadCache_updateAll($full = false) {
  1096. $tables = [
  1097. 'BI_audit_ENERGA_PRACOWNICY' => [
  1098. 'fields' => [
  1099. 'nip' => 'nip',
  1100. 'regon' => 'regon',
  1101. 'pesel' => 'pesel',
  1102. ],
  1103. 'base' => '0',
  1104. //'where' => '',
  1105. ],
  1106. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1107. 'fields' => [
  1108. 'TERYT_SYM' => 'TERYT_SYM',
  1109. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1110. 'nrDomu' => 'nrBudynku',
  1111. 'nrLokalu' => 'nrLokalu',
  1112. ],
  1113. 'base' => '0',
  1114. //'where' => '',
  1115. ],
  1116. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1117. 'fields' => [
  1118. 'krs' => 'KRS',
  1119. 'nip' => 'NIP',
  1120. 'regon' => 'REGON',
  1121. 'pesel' => 'PESEL',
  1122. 'TERYT_SYM' => 'TERYT_SYM',
  1123. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1124. 'nrDomu' => 'Numer_budynku',
  1125. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  1126. ],
  1127. 'base' => '0',
  1128. 'where' => "ownCompany != 'Y'",
  1129. ],
  1130. 'BI_audit_KW_requested_person' => [
  1131. 'fields' => [
  1132. 'pesel' => 'Seller_person_pesel',
  1133. 'krs' => 'Seller_person_KRS',
  1134. 'nip' => 'Seller_person_NIP',
  1135. 'regon' => 'Seller_person_REGON',
  1136. ],
  1137. 'base' => '0',
  1138. //'where' => '',
  1139. ],
  1140. ];
  1141. $tables_full = [
  1142. 'BI_audit_CEIDG' => [
  1143. 'fields' => [
  1144. 'nip' => 'nip',
  1145. 'regon' => 'regon',
  1146. 'TERYT_SYM' => 'TERYT_SYM',
  1147. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1148. 'nrDomu' => 'budynek',
  1149. 'nrLokalu' => 'lokal',
  1150. ],
  1151. 'base' => '1',
  1152. ],
  1153. 'BI_audit_CEIDG_pelnomocnicy' => [
  1154. 'fields' => [
  1155. 'nip' => 'nip',
  1156. 'TERYT_SYM' => 'TERYT_SYM',
  1157. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1158. 'nrDomu' => 'budynek',
  1159. 'nrLokalu' => 'lokal',
  1160. ],
  1161. 'base' => '1',
  1162. ],
  1163. 'BI_audit_CEIDG_powiazania' => [
  1164. 'fields' => [
  1165. 'nip' => 'nip',
  1166. 'regon' => 'regon',
  1167. ],
  1168. 'base' => '1',
  1169. ],
  1170. 'BI_audit_KRS' => [
  1171. 'fields' => [
  1172. 'krs' => 'krs',
  1173. 'nip' => 'nip',
  1174. 'regon' => 'regon',
  1175. 'TERYT_SYM' => 'TERYT_SYM',
  1176. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1177. 'nrDomu' => 'A_nrDomu',
  1178. 'nrLokalu' => 'A_nrLokalu',
  1179. ],
  1180. 'base' => '1',
  1181. ],
  1182. 'BI_audit_KRS_company' => [
  1183. 'fields' => [
  1184. 'regon' => 'regon',
  1185. 'krs' => 'krs',
  1186. ],
  1187. 'base' => '1',
  1188. ],
  1189. 'BI_audit_KRS_person' => [
  1190. 'fields' => [
  1191. 'pesel' => 'pesel',
  1192. ],
  1193. 'base' => '1',
  1194. ],
  1195. ];
  1196. if ($full) {
  1197. $tables = array_merge($tables_full, $tables);
  1198. $fullWhere = '1 = 1';
  1199. } else {
  1200. $fullWhere = 'BASE = 0';
  1201. }
  1202. $queries[] = "delete from BI_audit_ALL where {$fullWhere}";
  1203. $queries[] = "delete from BI_audit_ALL_ref where {$fullWhere}";
  1204. //$queries[] = "delete from BI_audit_ALL_ref_RELATIONS where {$fullWhere}"; // niepotrzebne
  1205. foreach ($tables as $name => $table) {
  1206. if (isset($table['where']) && $table['where']) $where = "where {$table['where']}";
  1207. else $where = '';
  1208. $queries[] = "insert into BI_audit_ALL (REMOTE_TABLE, REMOTE_ID, BASE, " . implode(", ", array_keys($table['fields'])) . ") select '{$name}', ID, '{$table['base']}', " . implode(", ", $table['fields']) . " from {$name} {$where}";
  1209. }
  1210. $queries[] = "update BI_audit_ALL set nip = null where nip = 0";
  1211. $queries[] = "update BI_audit_ALL set regon = null where regon = 0";
  1212. $queries[] = "update BI_audit_ALL set krs = null where krs = 0";
  1213. $queries[] = "update BI_audit_ALL set pesel = null where pesel = 0";
  1214. $queries[] = "update BI_audit_ALL set TERYT_SYM = null where TERYT_SYM = 0";
  1215. $queries[] = "update BI_audit_ALL set TERYT_SYM_UL = null where TERYT_SYM_UL = 0";
  1216. $queries[] = "update BI_audit_ALL set nrDomu = null where trim(nrDomu) = ''";
  1217. $queries[] = "update BI_audit_ALL set nrLokalu = null where trim(nrLokalu) = ''";
  1218. $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 {$fullWhere}";
  1219. $queries[] = "set @var = (select round(coalesce(max(ID), '0.5'), 1) from BI_audit_ALL_ref_RELATIONS)";
  1220. $queries[] = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION, BASE) select @var:=@var*2, a.RELATION, a.BASE from (select a.REMOTE_TABLE as RELATION, a.BASE as BASE 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 order by a.BASE desc) as a left join BI_audit_ALL_ref_RELATIONS r on a.RELATION = r.RELATION where r.RELATION is null";
  1221. if ($full) {
  1222. $refCeidgToCeidgPelnomocnicy = ACL::getRefTable('default_db/BI_audit_CEIDG/BI_audit_CEIDG', "default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy");
  1223. $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all1.ID, all2.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refCeidgToCeidgPelnomocnicy}` as ref on all1.REMOTE_TABLE = 'BI_audit_CEIDG' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_CEIDG_pelnomocnicy' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION";
  1224. $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all2.ID, all1.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refCeidgToCeidgPelnomocnicy}` as ref on all1.REMOTE_TABLE = 'BI_audit_CEIDG' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_CEIDG_pelnomocnicy' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all2.REMOTE_TABLE = rel.RELATION";
  1225. $refCeidgToCeidgPowiazania = ACL::getRefTable('default_db/BI_audit_CEIDG/BI_audit_CEIDG', "default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania");
  1226. $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all1.ID, all2.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refCeidgToCeidgPowiazania}` as ref on all1.REMOTE_TABLE = 'BI_audit_CEIDG' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_CEIDG_powiazania' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION";
  1227. $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all2.ID, all1.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refCeidgToCeidgPowiazania}` as ref on all1.REMOTE_TABLE = 'BI_audit_CEIDG' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_CEIDG_powiazania' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all2.REMOTE_TABLE = rel.RELATION";
  1228. $refKrsToKrsCompany = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company");
  1229. $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all1.ID, all2.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refKrsToKrsCompany}` as ref on all1.REMOTE_TABLE = 'BI_audit_KRS' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_KRS_company' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION";
  1230. $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all2.ID, all1.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refKrsToKrsCompany}` as ref on all1.REMOTE_TABLE = 'BI_audit_KRS' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_KRS_company' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all2.REMOTE_TABLE = rel.RELATION";
  1231. $refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
  1232. $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all1.ID, all2.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refKrsToKrsPerson}` as ref on all1.REMOTE_TABLE = 'BI_audit_KRS' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_KRS_person' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION";
  1233. $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all2.ID, all1.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refKrsToKrsPerson}` as ref on all1.REMOTE_TABLE = 'BI_audit_KRS' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_KRS_person' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all2.REMOTE_TABLE = rel.RELATION";
  1234. }
  1235. $refPracownicyToPracownicyAdresy = ACL::getRefTable('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY', "default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy");
  1236. $queries[] = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all1.ID, all2.ID, rel.ID, 0 from BI_audit_ALL as all1 join `{$refPracownicyToPracownicyAdresy}` 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";
  1237. foreach ($queries as $query) DB::getPDO()->query($query);
  1238. $BiAuditRelations = new BiAuditRelations($full);
  1239. $query = "select ID from BI_audit_ALL where {$fullWhere} order by ID";
  1240. $result = DB::query($query);
  1241. while ($row = DB::fetch($result)) $BiAuditRelations->findRelations($row->ID);
  1242. }
  1243. public function doReloadCache($full = false) {
  1244. $powiazaniaDirLocation = $this->getMainDirectory();
  1245. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1246. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1247. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1248. file_put_contents($reloadCachePidFile, getmypid());
  1249. try {
  1250. $this->reloadCache_reTeryt($full);
  1251. $this->reloadCache_updateAll($full);
  1252. file_put_contents($reloadCacheResultFile, "ok");
  1253. } catch (Exception $e) {
  1254. file_put_contents($reloadCacheResultFile, $e->getMessage());
  1255. }
  1256. }
  1257. public function doGeneratePowiazania($ID) {
  1258. $powiazaniaDirLocation = $this->getMainDirectory();
  1259. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1260. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  1261. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  1262. $pdfFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pdf";
  1263. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  1264. file_put_contents($pidFile, getmypid());
  1265. $tablesConf = [
  1266. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  1267. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  1268. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  1269. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  1270. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  1271. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  1272. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  1273. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  1274. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  1275. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  1276. ];
  1277. try {
  1278. $BiAuditPowiazania = new BiAuditPowiazania($ID);
  1279. if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  1280. file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  1281. $BiAuditPowiazania->saveToDb();
  1282. $BiAuditPowiazania->generatePdfAndHtml($tasksDirLocation);
  1283. /* $powiazania = $BiAuditPowiazania->asArray('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  1284. if (!$powiazania) return false;
  1285. DB::getPDO()->query($query);
  1286. foreach ($powiazania['BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row'] as $row) {
  1287. $powiazaniaRowSqlArr = [];
  1288. $string_concat_path = [];
  1289. foreach ($row['object'] as $i => $object) {
  1290. $powiazaniaRowObjectSqlArr = [];
  1291. $table = array_keys($object)[0];
  1292. if (!isset($tablesConf[$table])) throw new Exception("Błąd danych konfiguracyjnych");
  1293. $concat = "table='{$table}'";
  1294. if (isset($object['relation_from'])) $concat .= ";relation_from='{$object['relation_from']}'";
  1295. foreach ($tablesConf[$table] as $field) {
  1296. if ($object[$table][$field]) $concat .= ";{$field}='{$object[$table][$field]}'";
  1297. }
  1298. if ($i == 0) $powiazaniaRowSqlArr['string_concat_from'] = $concat;
  1299. elseif ($i == count($row['object']) - 1) $powiazaniaRowSqlArr['string_concat_to'] = $concat;
  1300. else $string_concat_path[] = $concat;
  1301. }
  1302. $powiazaniaRowSqlArr['string_concat_path'] = implode(' / ', $string_concat_path);
  1303. $id_row = DB::getPDO()->insert("BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row", $powiazaniaRowSqlArr);
  1304. if (!$id_row) throw new Exception("Błąd bazy danych");
  1305. DB::getPDO()->insert('CRM__#REF_TABLE__25', ["PRIMARY_KEY" => $ID, "REMOTE_PRIMARY_KEY" => $id_row]);
  1306. }
  1307. */
  1308. file_put_contents($resultFile, "ok");
  1309. } catch (Exception $e) {
  1310. file_put_contents($resultFile, $e->getMessage());
  1311. }
  1312. }
  1313. public function reinstallAction() {
  1314. $this->reinstall();
  1315. die('OK');
  1316. }
  1317. public function reinstall() {
  1318. $sqlList = array();
  1319. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  1320. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  1321. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  1322. SQL;
  1323. $sqlList['ChangeStructure1'] = <<<SQL
  1324. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Y','N','Full','Part','No') NOT NULL DEFAULT 'No';
  1325. SQL;
  1326. $sqlList['ChangeStructure2'] = <<<SQL
  1327. UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
  1328. SQL;
  1329. $sqlList['ChangeStructure3'] = <<<SQL
  1330. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
  1331. SQL;
  1332. $db = DB::getDB();
  1333. if ($db->has_errors()) {
  1334. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  1335. }
  1336. foreach ($sqlList as $sqlName => $sql) {
  1337. $res = $db->query($sql);
  1338. if ($db->has_errors()) {
  1339. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  1340. }
  1341. }
  1342. }
  1343. }
  1344. class BiAuditRelations {
  1345. private $RELATIONS_ID = [];
  1346. private $full;
  1347. private $relations = [
  1348. 'nip' => ['nip'],
  1349. 'regon' => ['regon'],
  1350. 'krs' => ['krs'],
  1351. 'pesel' => ['pesel'],
  1352. 'adres' => ['TERYT_SYM', 'TERYT_SYM_UL', 'nrDomu', 'nrLokalu'],
  1353. ];
  1354. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1355. private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  1356. public function __construct($full = false) {
  1357. $this->full = $full;
  1358. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  1359. $result = DB::getPDO()->fetchAll($query);
  1360. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  1361. }
  1362. private function getRelationID($name) {
  1363. if (!isset($this->RELATIONS_ID[$name])) {
  1364. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  1365. $newID = DB::getPDO()->fetchValue($query);
  1366. $this->RELATIONS_ID[$name] = $newID;
  1367. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  1368. DB::getPDO()->query($query);
  1369. }
  1370. return $this->RELATIONS_ID[$name];
  1371. }
  1372. public function findRelations($ID) {
  1373. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  1374. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  1375. $row = $result[0];
  1376. $joins = [];
  1377. $items = '';
  1378. foreach ($this->relations as $name => $columns) {
  1379. $ok = 0;
  1380. $join = [];
  1381. foreach ($columns as $column) {
  1382. $join[] = "t1.{$column} = t2.{$column}";
  1383. if ($row[$column]) $ok++;
  1384. }
  1385. if ($ok / count($columns) > 0.5) {
  1386. $joins[] = "(" . implode(" and ", $join) . ")";
  1387. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  1388. }
  1389. }
  1390. if (!$joins) return false;
  1391. if ($this->full) $where = "where t1.ID = {$ID} and t2.ID > {$ID}";
  1392. else $where = "where t1.ID = {$ID} and (t2.BASE = 1 or t2.ID > {$ID})";
  1393. $query = "select t2.ID as ID, t1.REMOTE_TABLE as REMOTE_TABLE_1, t2.REMOTE_TABLE as REMOTE_TABLE_2 {$items}, t1.BASE * t2.BASE as BASE " .
  1394. "from BI_audit_ALL t1 join BI_audit_ALL t2 on " . implode(" or ", $joins) . " {$where}";
  1395. $result = DB::getPDO()->fetchAll($query);
  1396. foreach ($result as $row) {
  1397. $relationID = 0;
  1398. foreach ($this->relations as $name => $v) {
  1399. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  1400. }
  1401. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  1402. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  1403. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  1404. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  1405. if (!($start2 || $end1)) {
  1406. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
  1407. DB::getPDO()->query($query);
  1408. }
  1409. if (!($start1 || $end2)) {
  1410. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
  1411. DB::getPDO()->query($query);
  1412. }
  1413. }
  1414. }
  1415. }
  1416. class BiAuditPowiazania {
  1417. private $DEPTH;
  1418. private $ID;
  1419. private $endNodes;
  1420. private $path = [];
  1421. private $results = [];
  1422. private $items_results = [];
  1423. private $relations = [];
  1424. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1425. public function __construct($ID = 0) {
  1426. if (!$ID) throw new Exception("Wrong ID parameter");
  1427. $query = "select BI_analiza_depth from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$ID}' and FILE_STATUS = 'IN_PROGRESS' and BI_analiza_reloadCache not in ('Full', 'Part')";
  1428. $result = DB::getPDO()->fetchAll($query);
  1429. if (!$result) throw new Exception("Błąd danych");
  1430. $this->DEPTH = (int) $result[0]['BI_analiza_depth'];
  1431. $this->ID = $ID;
  1432. $subQueries = [];
  1433. foreach ($this->destTables as $destTable) {
  1434. $refTable = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "default_db__x3A__{$destTable}:{$destTable}");
  1435. $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}'";
  1436. }
  1437. $query = implode(" union ", $subQueries);
  1438. $result = DB::getPDO()->fetchAll($query);
  1439. if (!$result) throw new Exception("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  1440. $this->endNodes = array_map('reset', $result);
  1441. $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  1442. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
  1443. $query = "select `all`.ID as ID from BI_audit_ALL `all` join `{$refPowiazaniaToPracownicy}` ref
  1444. on `all`.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and `all`.REMOTE_ID = ref.REMOTE_PRIMARY_KEY and ref.PRIMARY_KEY = '{$ID}'";
  1445. $result = DB::getPDO()->fetchAll($query);
  1446. foreach ($result as $row) $this->findPowiazania($row['ID']);
  1447. }
  1448. public function findPowiazania($ID, $relation = "", $end = 0) {
  1449. if (isset($this->path[$ID])) return false;
  1450. $this->path[$ID] = $relation;
  1451. if (!$relation) $relation = 0;
  1452. if ($end) {
  1453. if (in_array($ID, $this->endNodes)) $this->results[] = $this->path;
  1454. array_pop($this->path);
  1455. return true;
  1456. }
  1457. if (count($this->path) > $this->DEPTH) {
  1458. array_pop($this->path);
  1459. return false;
  1460. }
  1461. $nodes = [];
  1462. if ($relation) $where = "and ({$relation} & ref.RELATION_ID) != {$relation}";
  1463. else $where = "";
  1464. $query = "select ref.ID2, RELATION_ID, END from BI_audit_ALL_ref ref where ref.ID1 = '{$ID}' {$where}";
  1465. $result = DB::query($query);
  1466. while ($row = DB::fetch($result)) $nodes[$row->ID2] = ['relation' => (int) $row->RELATION_ID, 'end' => $row->END];
  1467. foreach ($nodes as $node => $data) $this->findPowiazania($node, $data['relation'], $data['end']);
  1468. array_pop($this->path);
  1469. }
  1470. private function relationName($ID) {
  1471. if (!isset($this->relations[$ID])) {
  1472. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  1473. $result = DB::getPDO()->fetchAll($query);
  1474. $rels = array_map('reset', $result);
  1475. $this->relations[$ID] = implode(", ", $rels);
  1476. }
  1477. return $this->relations[$ID];
  1478. }
  1479. private function generateItemsResults() {
  1480. $xmlRoot2 = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  1481. $xmlElements = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  1482. $this->items_results = [];
  1483. $items_kontrahenci = [];
  1484. $items_kw_person = [];
  1485. $kontrahenci = [];
  1486. $kw_person = [];
  1487. $refUmowyToKontrahenci = 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');
  1488. $refKwRequestedToKwRequestedPerson = 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');
  1489. foreach ($this->results as $result) {
  1490. $item_results = [];
  1491. foreach ($result as $ID => $rel) {
  1492. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  1493. $row = DB::getPDO()->fetchFirst($query);
  1494. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  1495. $obj = DB::fetch(DB::query($query));
  1496. $item_result = [$row['REMOTE_TABLE'] => (array) $obj];
  1497. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  1498. $item_results['object'][] = $item_result;
  1499. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  1500. $kontrahenci[] = $row['REMOTE_ID'];
  1501. $query = "select umowy.* from BI_audit_ENERGA_RUM_UMOWY umowy join `{$refUmowyToKontrahenci}` ref on umowy.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
  1502. $res = DB::query($query);
  1503. if (mysql_num_rows($res)) {
  1504. $umowy = [];
  1505. while ($obj = DB::fetch($res)) $umowy[] = (array) $obj;
  1506. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  1507. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  1508. $items_kontrahenci[] = $item_kontrahenci;
  1509. }
  1510. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  1511. $kw_person[] = $row['REMOTE_ID'];
  1512. $query = "select kw.* from BI_audit_KW_requested kw join `{$refKwRequestedToKwRequestedPerson}` ref on kw.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
  1513. $res = DB::query($query);
  1514. if (mysql_num_rows($res)) {
  1515. $kw = [];
  1516. while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
  1517. $item_kw_person['ID'] = $row['REMOTE_ID'];
  1518. $item_kw_person['BI_audit_KW_requested'] = $kw;
  1519. $items_kw_person[] = $item_kw_person;
  1520. }
  1521. }
  1522. }
  1523. $this->items_results[$xmlRoot2][$xmlElements][] = $item_results;
  1524. }
  1525. $this->items_results[$xmlRoot2]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  1526. $this->items_results[$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;
  1527. }
  1528. public function saveToDb() {
  1529. if (!$this->results) return null;
  1530. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  1531. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  1532. $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
  1533. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  1534. foreach ($this->results as $result) {
  1535. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  1536. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  1537. foreach ($result as $ID => $rel) {
  1538. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  1539. $object = DB::getPDO()->fetchFirst($query);
  1540. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relations[$rel]]);
  1541. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  1542. $ref = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
  1543. "default_db__x3A__{$object['REMOTE_TABLE']}:{$object['REMOTE_TABLE']}");
  1544. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  1545. }
  1546. }
  1547. }
  1548. public function asXml() {
  1549. if (!$this->results) return null;
  1550. if (!$this->items_results) $this->generateItemsResults();
  1551. $xmlRoot = "RelatedFeatureRoot";
  1552. return V::arrayToXML($this->items_results, true, $xmlRoot);
  1553. }
  1554. public function asArray($subArray = null) {
  1555. if (!$this->results) return null;
  1556. if (!$this->items_results) $this->generateItemsResults();
  1557. if ($subArray) {
  1558. if (isset($this->items_results[$subArray])) return $this->items_results[$subArray];
  1559. else return [];
  1560. } else return $this->items_results;
  1561. }
  1562. public function powiazaniaFound() {
  1563. if ($this->results) return true;
  1564. else return false;
  1565. }
  1566. public function generatePdfAndHtml($tasksDirLocation) {
  1567. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
  1568. $pdfDestFile = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.pdf";
  1569. $htmlDestDir = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.html";
  1570. $htmlZipDestFile = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.zip";
  1571. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  1572. $antXmlFilename = "relations-{$this->ID}.out_task.dita.final_with_RelatedFeatureLoop.xml";
  1573. $antXmlFile = $antDir . "/" . $antXmlFilename;
  1574. $pdfFile = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$this->ID}/pdf/relations-{$this->ID}.pdf";
  1575. $htmlDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$this->ID}/html";
  1576. if (!file_exists($antDir)) mkdir($antDir, 0755, true);
  1577. if (!is_dir($antDir)) $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć pliku PDF";
  1578. else {
  1579. copy($xmlFile, $antXmlFile);
  1580. shell_exec("cd /Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree && /opt/local/bin/ant -f build_CRM_PROCES_tree.xml default_db:PROCES_INIT:tree:dita -Duuid=relations-{$this->ID}");
  1581. shell_exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$this->ID}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o pdf -i relations-{$this->ID}.ditamap -f pdf");
  1582. if (file_exists($pdfFile)) rename($pdfFile, $pdfDestFile);
  1583. shell_exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$this->ID}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o html -i relations-{$this->ID}.ditamap -f tocjs");
  1584. if (file_exists($htmlDir) && is_dir($htmlDir)) {
  1585. shell_exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$this->ID}\" && zip -r \"{$htmlZipDestFile}\" html");
  1586. if (file_exists($htmlDestDir)) shell_exec("rm -rf \"{$htmlDestDir}\"");
  1587. shell_exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
  1588. }
  1589. }
  1590. }
  1591. }