BiAuditGenerate.php 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945
  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 jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>
  112. Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów (w zależności od ilości rekordów może trwać znacznie dłużej)
  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 (!($BiAnalizaMinDepth = V::get('minDepth', false, $_POST))) throw new Exception("Błąd formularza!");
  168. if (!($BiAnalizaMaxDepth = V::get('maxDepth', false, $_POST))) throw new Exception("Błąd formularza!");
  169. if (!($BiAnalizaOnlyTargets = V::get('onlyTargets', false, $_POST))) throw new Exception("Błąd formularza!");
  170. $query = "select * from BI_audit_ENERGA_PRACOWNICY where ID='{$prID[0]}'";
  171. $result = DB::getPDO()->fetchFirst($query);
  172. if (!$result) throw new Exception("Błąd formularza!");
  173. $sqlInsert = [
  174. 'L_APPOITMENT_INFO' => $lAppoitmentInfo,
  175. 'A_STATUS' => 'NORMAL',
  176. 'A_STATUS_INFO' => 'Dodane przez BiAuditGenerate z poziomu tabeli BI_audit_ENERGA_PRACOWNICY',
  177. 'A_ADM_COMPANY' => $result['A_ADM_COMPANY'],
  178. 'A_CLASSIFIED' => $result['A_CLASSIFIED'],
  179. 'FILE_STATUS' => 'NONE',
  180. 'FILE_STATUS_info' => 'Oczekuję na zdefiniowanie danych wejściowych',
  181. 'BI_analiza_reloadCache' => $sqlUpdate['BI_analiza_reloadCache'],
  182. 'BI_analiza_minDepth' => $BiAnalizaMinDepth,
  183. 'BI_analiza_maxDepth' => $BiAnalizaMaxDepth,
  184. 'BI_analiza_onlyTargets' => $BiAnalizaOnlyTargets,
  185. ];
  186. $powiazanieID = DB::getDB()->ADD_NEW_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', (object)$sqlInsert);
  187. if ($powiazanieID) SE_Layout::alert('success','Dodano rekord do wygenerowania powiązań');
  188. else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  189. }
  190. $sqlUpdate['ID'] = $powiazanieID;
  191. $this->truncatePowiazaniaFromDB($powiazanieID);
  192. $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  193. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
  194. foreach ($prID as $v) DB::getPDO()->insert($refPowiazaniaToPracownicy, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $v]);
  195. $refPowiazaniaToKontrahenci = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  196. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI');
  197. foreach ($kontrahenci as $kontrahent) DB::getPDO()->insert($refPowiazaniaToKontrahenci, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $kontrahent['ID']]);
  198. $refPowiazaniaToKwRequestedPreson = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  199. 'default_db__x3A__BI_audit_KW_requested_person:BI_audit_KW_requested_person');
  200. foreach ($requestedPersons as $requestedPerson) DB::getPDO()->insert($refPowiazaniaToKwRequestedPreson, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $requestedPerson['ID']]);
  201. $affected = DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlUpdate);
  202. if ($affected) {
  203. if ($this->powiazanie) {
  204. SE_Layout::alert('success','Oznaczono rekord do wygenerowania powiązań');
  205. ?>
  206. <div class="container" style="text-align:center">
  207. <a href="<?=$this->REFERER?>" class="btn btn-primary">Powrót</a>
  208. </div>
  209. <?php
  210. }
  211. } else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  212. }
  213. private function initializePowiazania() {
  214. switch (V::get('action', '', $_POST)) {
  215. case "initialize":
  216. $this->initializePowiazaniaSave();
  217. break;
  218. default:
  219. $this->initializePowiazaniaForm();
  220. }
  221. }
  222. private function showPowiazania() {
  223. // echo "Statystyki znalezionych powiązań [TODO]";
  224. $dir = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  225. $pdfFile = "{$dir}/relations.pdf";
  226. $htmlFile = "{$dir}/html/relations-{$this->powiazanie['ID']}.html";
  227. $htmlZipFile = "{$dir}/html.zip";
  228. $url = $this->getUrl('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  229. $pdfUrl = "{$url}/relations.pdf";
  230. $htmlUrl = "{$url}/html/relations-{$this->powiazanie['ID']}.html";
  231. $htmlZipUrl = "{$url}/html.zip";
  232. ?>
  233. <div class="container" style="margin-top:20px">
  234. <legend>
  235. Wygenerowany raport nr <?=$this->powiazanie['ID']?>
  236. </legend>
  237. <div class="form-group">
  238. <div class="col-sm-12">
  239. <?php
  240. if (file_exists($pdfFile)) {
  241. ?>
  242. <a href="<?=$pdfUrl?>" target="_blank" class="btn btn-primary">Pokaż raport PDF</a>
  243. <?php
  244. }
  245. if (file_exists($htmlFile)) {
  246. ?>
  247. <a href="<?=$htmlUrl?>" target="_blank" class="btn btn-primary">Pokaż raport HTML</a>
  248. <?php
  249. }
  250. if (file_exists($htmlZipFile)) {
  251. ?>
  252. <a href="<?=$htmlZipUrl?>" target="_blank" download="Raport <?=$this->powiazanie['ID']?>.zip" class="btn btn-primary">Pobierz raport HTML</a>
  253. <?php
  254. }
  255. ?>
  256. <br/><br/><a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  257. </div>
  258. </div>
  259. </div>
  260. <?php
  261. }
  262. private function showPowiazaniaList() {
  263. switch (V::get('action', '', $_POST)) {
  264. case "initialize":
  265. $this->initializePowiazaniaSave();
  266. break;
  267. }
  268. $this->showPowiazaniaListForm();
  269. }
  270. private function showPowiazaniaListForm() {
  271. if (!$this->SOURCE['ID']) throw new Exception("Błąd danych");
  272. elseif ($this->SOURCE['TABLE'] != 'BI_audit_ENERGA_PRACOWNICY') throw new Exception("Błąd danych");
  273. $query = "select * from `{$this->SOURCE['TABLE']}` where ID = '{$this->SOURCE['ID']}'";
  274. $pracownik = DB::getPDO()->fetchFirst($query);
  275. if (!$pracownik) throw new Exception("Błąd danych");
  276. ?>
  277. <div class="container" style="margin-top:20px">
  278. <legend>
  279. Lista wygenerowanych powiązań :: <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>
  280. <span class="pull-right"># <?=$pracownik['ID']?></span>
  281. </legend>
  282. <div class="form-group">
  283. <div class="col-sm-12">
  284. <h4>Lista wygenerowanych powiązań, w których znajduje się pracownik</h4>
  285. <table class="table table-bordered table-hover table-striped" height=5>
  286. <thead>
  287. <tr style="text-align:center; background-color:lightgray">
  288. <td width=1>ID</td>
  289. <td>Adnotacje</td>
  290. <td>Minimalna głębokość analizy</td>
  291. <td>Maksymalna głębokość analizy</td>
  292. <td>Powiązania tylko do celów</td>
  293. <td>Status raportu</td>
  294. <td>Status raportu - informacje</td>
  295. <td>Indywidualny raport</td>
  296. <td width=1></td>
  297. </tr>
  298. </thead>
  299. <tbody>
  300. <?php
  301. $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  302. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
  303. $query = "select `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.*
  304. from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  305. join `{$refPowiazaniaToPracownicy}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPracownicy}`.`PRIMARY_KEY`
  306. where `REMOTE_PRIMARY_KEY` = '{$this->SOURCE['ID']}'";
  307. $result = DB::getPDO()->fetchAll($query);
  308. if (!$result) echo '<tr><td align="center" colspan="9">Brak znalezionych powiązań</td></tr>';
  309. else {
  310. foreach ($result as $row) {
  311. $query = "select count(*) from `{$refPowiazaniaToPracownicy}` where `PRIMARY_KEY` = '{$row['ID']}'";
  312. $count = DB::getPDO()->fetchValue($query);
  313. ?>
  314. <tr>
  315. <td align="right"><?=$row['ID']?></td>
  316. <td><?=$row['L_APPOITMENT_INFO']?></td>
  317. <td><?=$row['BI_analiza_minDepth']?></td>
  318. <td><?=$row['BI_analiza_maxDepth']?></td>
  319. <td><?=($row['BI_analiza_onlyTargets'] == 'N' ? "Nie" : "Tak")?></td>
  320. <td><?=$row['FILE_STATUS']?></td>
  321. <td><?=$row['FILE_STATUS_info']?></td>
  322. <td><?=($count > 1 ? 'Nie' : 'Tak')?></td>
  323. <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>
  324. </tr>
  325. <?php
  326. }
  327. }
  328. ?>
  329. </tbody>
  330. </table>
  331. </div>
  332. </div>
  333. <div class="form-group">
  334. <div class="col-sm-12">
  335. <h4>Dodaj nowe zadanie generowania powiazań dla tego pracownika</h4>
  336. </div>
  337. </div>
  338. <form class="form-horizontal" method="post">
  339. <div class="form-group">
  340. <label class="col-sm-4 control-label">Minimalna głębokość poszukiwań (liczba rekurencji)</label>
  341. <div class="col-sm-1">
  342. <input type="number" class="form-control" name="minDepth" id="minDepth" data-bind="value:replyNumber" min="1" max="9" value="1" required/>
  343. </div>
  344. </div>
  345. <div class="form-group">
  346. <label class="col-sm-4 control-label">Maksymalna głębokość poszukiwań (liczba rekurencji)</label>
  347. <div class="col-sm-1">
  348. <input type="number" class="form-control" name="maxDepth" id="maxDepth" data-bind="value:replyNumber" min="1" max="9" value="6" required/>
  349. </div>
  350. </div>
  351. <div class="form-group">
  352. <label class="col-sm-4 control-label">Czy zwracać tylko wyniki ze znalezionymi obiektami docelowymi (z tabeli kontrahentów)?</label>
  353. <div class="col-sm-1">
  354. <select name="onlyTargets" class="form-control">
  355. <option value="Y" selected>Tak</option>
  356. <option value="N">Nie</option>
  357. </select>
  358. </div>
  359. </div>
  360. <div class="form-group">
  361. <label class="col-sm-4 control-label">Adnotacje</label>
  362. <div class="col-sm-4">
  363. <input type="text" class="form-control" name="info" value="Indywidualnie dla <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>" required/>
  364. </div>
  365. </div>
  366. <div class="form-group">
  367. <label class="col-sm-4 control-label">
  368. Odśwież cache
  369. </label>
  370. <div class="col-sm-2">
  371. <select name="reloadCache" class="form-control">
  372. <option value="No" selected>Nie</option>
  373. <option value="Part">Częściowe</option>
  374. <option value="Full">Pełne</option>
  375. </select>
  376. </div>
  377. </div>
  378. <div class="form-group">
  379. <div class="col-sm-offset-4 col-sm-8">
  380. Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>
  381. Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów (w zależności od ilości rekordów może trwać znacznie dłużej)
  382. </div>
  383. </div>
  384. <div class="form-group">
  385. <div class="col-sm-12">
  386. <div class="containter" style="text-align:center">
  387. <button type="submit" class="btn btn-primary" name="action" value="initialize" onClick="return validate()">Generuj</button>
  388. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  389. </div>
  390. </div>
  391. </div>
  392. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  393. <input type="hidden" name="prID[]" value="<?=$pracownik['ID']?>">
  394. </form>
  395. </div>
  396. <script language="JavaScript">
  397. <!--
  398. function validate() {
  399. result = (document.getElementById('minDepth').value <= document.getElementById('maxDepth').value);
  400. if (!result) alert('Wartość minimalnej głębokości analizy nie może być większa od wartości maksymalnej głębokości analizy!');
  401. return result;
  402. }
  403. -->
  404. </script>
  405. <?php
  406. }
  407. private function powiazania() {
  408. try {
  409. if (!$this->SOURCE) throw new Exception("Błąd danych");
  410. elseif (!(isset($this->SOURCE['TABLE']) && isset($this->SOURCE['ID']))) throw new Exception("Błąd danych");
  411. switch ($this->SOURCE['TABLE']) {
  412. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  413. $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->SOURCE['ID']}'");
  414. if (!$powiazania) throw new Exception("Błąd danych");
  415. $this->powiazanie = $powiazania[0];
  416. switch ($this->powiazanie['FILE_STATUS']) {
  417. case "NONE":
  418. $this->initializePowiazania();
  419. break;
  420. case "GENERATED":
  421. $this->showPowiazania();
  422. break;
  423. default: throw new Exception("Błędny status rekordu");
  424. }
  425. break;
  426. case "BI_audit_ENERGA_PRACOWNICY":
  427. $this->showPowiazaniaList();
  428. break;
  429. case "BI_audit_KRS":
  430. $this->importKrsToPracownicySearch($this->SOURCE['ID']);
  431. break;
  432. case "BI_audit_KRS_person":
  433. $this->showKrsForKrsPerson();
  434. break;
  435. default: throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate");
  436. }
  437. } catch (Exception $e) {
  438. SE_Layout::alert('danger',$e->getMessage());
  439. $_SESSION['REFERER'] = $this->REFERER;
  440. ?>
  441. <div class="container" style="text-align:center">
  442. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
  443. </div>
  444. <?php
  445. }
  446. }
  447. private function importKrsToPracownicy() {
  448. $action = V::get('action', '', $_POST);
  449. switch ($action) {
  450. case "search":
  451. $this->importKrsToPracownicySearch();
  452. break;
  453. default: $this->importKrsToPracownicyForm();
  454. }
  455. }
  456. private function importKrsToPracownicyForm() {
  457. ?>
  458. <div class="container" style="margin-top:20px">
  459. <legend>
  460. Importowanie podmiotów z KRS do tabel kontrahentów i pracowników
  461. </legend>
  462. <div class="form-group">
  463. <div class="col-sm-12">
  464. <h4>Znajdź podmiot</h4>
  465. </div>
  466. </div>
  467. <form class="form-horizontal" method="post">
  468. <div class="form-group">
  469. <label class="col-sm-1 control-label">Nazwa</label>
  470. <div class="col-sm-4">
  471. <input type="text" class="form-control" name="nazwa" title="Podaj nazwę podmiotu">
  472. </div>
  473. </div>
  474. <div class="form-group">
  475. <label class="col-sm-1 control-label">KRS</label>
  476. <div class="col-sm-2">
  477. <input type="text" class="form-control" name="krs" pattern="^[0-9]{0,10}$" title="Podaj KRS"/>
  478. </div>
  479. </div>
  480. <div class="form-group">
  481. <label class="col-sm-1 control-label">NIP</label>
  482. <div class="col-sm-2">
  483. <input type="text" class="form-control" name="nip" pattern="^[0-9]{0,10}$" title="Podaj NIP (bez kresek i bez oznaczenia kraju)"/>
  484. </div>
  485. </div>
  486. <div class="form-group">
  487. <label class="col-sm-1 control-label">Regon</label>
  488. <div class="col-sm-2">
  489. <input type="text" class="form-control" name="regon" pattern="^[0-9]{0,9}$" title="Podaj regon"/>
  490. </div>
  491. </div>
  492. <div class="form-group">
  493. <div class="col-sm-offset-1 col-sm-11">
  494. <button type="submit" class="btn btn-primary" name="action" value="search">Szukaj</button>
  495. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  496. </div>
  497. </div>
  498. </form>
  499. </div>
  500. <?php
  501. }
  502. private function importKrsToPracownicySearch($krsId = null) {
  503. $formItems = [
  504. "nazwa" => 'like',
  505. "krs" => '=',
  506. "nip" => '=',
  507. "regon" => '=',
  508. ];
  509. try {
  510. $subaction = V::get('subaction', '', $_POST);
  511. switch ($subaction) {
  512. case "listKrsPerson":
  513. $krsId = V::get('krsId', 0, $_POST, int);
  514. break;
  515. case "addKrsPersonToPracownicy":
  516. $krsId = V::get('krsId', 0, $_POST, int);
  517. $personId = V::get('personId', [], $_POST);
  518. if (!$personId) throw new Exception("Błąd formularza");
  519. $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) . ")";
  520. DB::getPDO()->query($query);
  521. SE_Layout::alert('success', "Pomyślnie zaimportowano " . count($personId) . " pracownik" . ((count($personId) == 1) ? "a" : "ów"));
  522. break;
  523. case "addKrsToKontrahenci":
  524. $krsId = V::get('krsId', 0, $_POST, int);
  525. if (!$krsId) throw new Exception("Błąd formularza");
  526. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI kh join BI_audit_KRS krs on (kh.NIP = krs.nip or kh.REGON = krs.regon or kh.KRS = krs.krs) where krs.ID = '{$krsId}'";
  527. $kontrahentExists = DB::getPDO()->fetchValue($query);
  528. if ($kontrahentExists) throw new Exception("Podmiot znajduje się już w tabeli kontrahentów");
  529. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (Tytul_dokumentu, Pelna_nazwa_kontrahenta, REGON, NIP, KRS) select 'ZaImportowano z KRS', nazwa, regon, nip, krs from BI_audit_KRS where ID = ".$krsId." ";
  530. DB::getPDO()->query($query);
  531. SE_Layout::alert('success', "Pomyślnie zaimportowano kontrahenta");
  532. break;
  533. }
  534. if ($krsId) {
  535. $where = ["ID = '{$krsId}'"];
  536. } else {
  537. $form = [];
  538. foreach ($formItems as $item => $type) {
  539. if ($param = V::get($item, '', $_POST)) {
  540. if ($type == 'like') $param = "%{$param}%";
  541. $form[$item] = DB::getPDO()->quote($param);
  542. }
  543. }
  544. if (!$form) throw new Exception("Nie wypełniono żadnego pola wyszukiwania!");
  545. $where = [];
  546. foreach ($form as $name => $value) $where[] = "`{$name}` {$formItems[$name]} {$value}";
  547. }
  548. } catch (Exception $e) {
  549. SE_Layout::alert('danger', $e->getMessage());
  550. $this->importKrsToPracownicyForm();
  551. return;
  552. }
  553. $query = "select * from `BI_audit_KRS` where " . implode(" and ", $where) . "order by ID limit 1001";
  554. $result = DB::getPDO()->fetchAll($query);
  555. if (count($result) == 1001) {
  556. SE_Layout::alert('danger', 'Znaleziono zbyt wiele wyników. Doprecyzuj parametry wyszukiwania.');
  557. $this->importKrsToPracownicyForm();
  558. return;
  559. } elseif (count($result) == 1) {
  560. $krsId = $result[0]['ID'];
  561. }
  562. ?>
  563. <div class="container" style="margin-top:20px">
  564. <form method="post">
  565. <legend>
  566. Importowanie podmiotów z KRS do tabel kontrahentów i pracowników
  567. </legend>
  568. <div class="form-group">
  569. <div class="col-sm-12">
  570. <h4>Znalezione podmioty:</h4>
  571. </div>
  572. </div>
  573. <div class="form-group">
  574. <div class="col-sm-12">
  575. <table class="table table-bordered table-hover table-striped" height=5>
  576. <thead>
  577. <tr style="text-align:center; background-color:lightgray">
  578. <td width=1>Lp.</td>
  579. <td>Nazwa</td>
  580. <td>Adres</td>
  581. <td>KRS</td>
  582. <td>NIP</td>
  583. <td>Regon</td>
  584. <?php
  585. if (count($result) > 1) {
  586. ?>
  587. <td width=1>Wybierz</td>
  588. <?php
  589. }
  590. ?>
  591. </tr>
  592. </thead>
  593. <tbody>
  594. <?php
  595. if (!$result) echo '<tr><td align="center" colspan="6">Nie znaleziono podmiotu</td></tr>';
  596. else {
  597. $lp = 1;
  598. foreach ($result as $row) {
  599. $adres = $row['A_miejscowosc'];
  600. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  601. if ($row['A_nrDomu']) {
  602. $adres .= " {$row['A_nrDomu']}";
  603. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  604. }
  605. ?>
  606. <tr>
  607. <td align="right"><?=$lp++?></td>
  608. <td><?=htmlspecialchars($row['nazwa'])?></td>
  609. <td><?=htmlspecialchars($adres)?></td>
  610. <td><?=$row['krs']?></td>
  611. <td><?=$row['nip']?></td>
  612. <td><?=$row['regon']?></td>
  613. <?php
  614. if (count($result) > 1) {
  615. ?>
  616. <td align="center">
  617. <input type="radio" name="krsId" value="<?=$row['ID']?>"/>
  618. </td>
  619. <?php
  620. }
  621. ?>
  622. </tr>
  623. <?php
  624. }
  625. }
  626. ?>
  627. </tbody>
  628. </table>
  629. </div>
  630. </div>
  631. <?php
  632. if (count($result) > 1) {
  633. ?>
  634. <div class="form-group">
  635. <div class="col-sm-12">
  636. <?php
  637. foreach (array_keys($formItems) as $item) {
  638. ?>
  639. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  640. <?php
  641. }
  642. ?>
  643. <input type="hidden" name="back" value="search"/>
  644. <div class="containter" style="text-align:center">
  645. <button type="submit" class="btn btn-primary" name="subaction" value="listKrsPerson" onClick="return validateCompany(this)">Wybierz zaznaczony podmiot</button>
  646. <a href="" class="btn btn-default">Powrót</a>
  647. </div>
  648. </div>
  649. </div>
  650. <?php
  651. } elseif ($krsId) {
  652. ?>
  653. <div class="form-group">
  654. <div class="col-sm-12">
  655. <h4>Znalezione osoby:</h4>
  656. </div>
  657. </div>
  658. <div class="form-group">
  659. <div class="col-sm-12">
  660. <table class="table table-bordered table-hover table-striped" height=5>
  661. <thead>
  662. <tr style="text-align:center; background-color:lightgray">
  663. <td width=1>Lp.</td>
  664. <td>Nazwisko</td>
  665. <td>Imiona</td>
  666. <td>Pesel</td>
  667. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  668. </tr>
  669. </thead>
  670. <tbody>
  671. <?php
  672. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI kh join BI_audit_KRS krs on (kh.NIP = krs.nip or kh.REGON = krs.regon or kh.KRS = krs.krs) where krs.ID = '{$krsId}'";
  673. $kontrahentExists = DB::getPDO()->fetchValue($query);
  674. $refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
  675. $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}'";
  676. $result = DB::getPDO()->fetchAll($query);
  677. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono osób powiązanych z podmiotem</td></tr>';
  678. else {
  679. $lp = 1;
  680. foreach ($result as $row) {
  681. ?>
  682. <tr<?=($row['pracownicyId'] ? ' style="color:darkgrey"' : '')?>>
  683. <td align="right"><?=$lp++?></td>
  684. <td><?=$row['nazwisko']?></td>
  685. <td><?=$row['imiona']?></td>
  686. <td><?=$row['pesel']?></td>
  687. <td><input type="checkbox" name="personId[]" value="<?=$row['ID']?>" onClick="toggle(this)" <?=($row['pracownicyId'] ? "disabled" : "")?>/></td>
  688. </tr>
  689. <?php
  690. }
  691. }
  692. ?>
  693. </tbody>
  694. </table>
  695. <div class="containter" style="text-align:center">
  696. <button type="submit" class="btn btn-primary" name="subaction" value="addKrsToKontrahenci"<?=($kontrahentExists ? " disabled" : "")?>>Dodaj firmę do tabeli kontrahentów</button>
  697. <button type="submit" class="btn btn-primary" name="subaction" value="addKrsPersonToPracownicy" onClick="return validatePerson(this)">Dodaj zaznaczone osoby do tabeli pracowników</button>
  698. <input type="hidden" name="krsId" value="<?=$krsId?>"/>
  699. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  700. <?php
  701. if (V::get('back', '', $_POST) == 'search') {
  702. foreach (array_keys($formItems) as $item) {
  703. ?>
  704. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  705. <?php
  706. }
  707. ?>
  708. <button type="submit" class="btn btn-default" name="action" value="search">Powrót</button>
  709. <?php
  710. } else {
  711. ?>
  712. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  713. <?php
  714. }
  715. ?>
  716. </div>
  717. </div>
  718. </div>
  719. <?php
  720. }
  721. ?>
  722. <input type="hidden" name="action" value="search">
  723. </form>
  724. </div>
  725. <script language="JavaScript">
  726. <!--
  727. function toggleAll(source) {
  728. checkboxes = document.getElementsByName('personId[]');
  729. checked = false;
  730. for(var i=0, n=checkboxes.length;i<n;i++) {
  731. if (!checkboxes[i].disabled) {
  732. checkboxes[i].checked = source.checked;
  733. checked = true;
  734. }
  735. }
  736. if (source.checked && (!checked)) source.checked = false;
  737. }
  738. function toggle(source) {
  739. checkboxes = document.getElementsByName('personId[]');
  740. all = true;
  741. for(var i=0, n=checkboxes.length;i<n;i++) if(!checkboxes[i].disabled && checkboxes[i].checked == false) all = false;
  742. source.form['checkAll'].checked = all;
  743. }
  744. function validatePerson(source) {
  745. checkboxes = document.getElementsByName('personId[]');
  746. checked = false;
  747. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked) checked = true;
  748. if (!checked) alert('Nie wybrano żadnej osoby!');
  749. return checked;
  750. }
  751. function validateCompany(source) {
  752. radios = document.getElementsByName('krsId');
  753. checked = false;
  754. for(var i=0, n=radios.length;i<n;i++) if(radios[i].checked) checked = true;
  755. if (!checked) alert('Nie wybrano żadnej firmy!');
  756. return checked;
  757. }
  758. -->
  759. </script>
  760. <?php
  761. }
  762. private function showKrsForKrsPerson() {
  763. $query = "select * from BI_audit_KRS_person where ID = '{$this->SOURCE['ID']}'";
  764. $result = DB::getPDO()->fetchFirst($query);
  765. ?>
  766. <div class="container" style="margin-top:20px">
  767. <legend>
  768. Lista podmiotów, w których występuje <?="{$result['nazwisko']} {$result['imiona']}" . ($result['pesel'] ? " (PESEL: {$result['pesel']})" : "")?>
  769. </legend>
  770. <div class="form-group">
  771. <div class="col-sm-12">
  772. <table class="table table-bordered table-hover table-striped" height=5>
  773. <thead>
  774. <tr style="text-align:center; background-color:lightgray">
  775. <td width=1>Lp.</td>
  776. <td>Nazwa</td>
  777. <td>Adres</td>
  778. <td>KRS</td>
  779. <td>NIP</td>
  780. <td>Regon</td>
  781. <td width=1></td>
  782. </tr>
  783. </thead>
  784. <tbody>
  785. <?php
  786. $refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
  787. $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']}'";
  788. $result = DB::getPDO()->fetchAll($query);
  789. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono powiązanych podmiotów</td></tr>';
  790. else {
  791. $lp = 1;
  792. foreach ($result as $row) {
  793. $adres = $row['A_miejscowosc'];
  794. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  795. if ($row['A_nrDomu']) {
  796. $adres .= " {$row['A_nrDomu']}";
  797. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  798. }
  799. ?>
  800. <tr>
  801. <td align="right"><?=$lp++?></td>
  802. <td><?=htmlspecialchars($row['nazwa'])?></td>
  803. <td><?=htmlspecialchars($adres)?></td>
  804. <td><?=$row['krs']?></td>
  805. <td><?=$row['nip']?></td>
  806. <td><?=$row['regon']?></td>
  807. <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>
  808. </tr>
  809. <?php
  810. }
  811. }
  812. ?>
  813. </tbody>
  814. </table>
  815. </div>
  816. </div>
  817. <div class="form-group">
  818. <div class="col-sm-12">
  819. <div class="containter" style="text-align:center">
  820. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-default">Powrót</a>
  821. </div>
  822. </div>
  823. </div>
  824. </div>
  825. <?php
  826. }
  827. public function defaultAction() {
  828. SE_Layout::gora();
  829. SE_Layout::menu();
  830. if (isset($_SESSION['REFERER'])) {
  831. $this->REFERER = $_SESSION['REFERER'];
  832. unset($_SESSION['REFERER']);
  833. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  834. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  835. if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
  836. elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
  837. elseif (($ID = V::get('ID_BI_audit_KRS', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  838. elseif (($ID = V::get('ID_BI_audit_KRS_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS_person';
  839. if ($this->SOURCE) {
  840. $this->SOURCE['ID'] = $ID;
  841. $this->powiazania();
  842. }
  843. elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
  844. switch ($TABLE) {
  845. case "default_db/BI_audit_ENERGA_PRACOWNICY":
  846. $this->importKrsToPracownicy();
  847. break;
  848. default: SE_Layout::alert('danger', 'Błąd parametru');
  849. }
  850. }
  851. else SE_Layout::alert('danger', 'Błąd parametru');
  852. SE_Layout::dol();
  853. }
  854. private function getRefsTables($namespace) {
  855. try {
  856. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  857. if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
  858. $fields = $item['field'];
  859. $refsTables = [];
  860. foreach ($fields as $field) {
  861. list($type, $child) = explode(":", $field['xsdType'], 2);
  862. if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) $refsTables[] = ACL::getRefTable($namespace, $child);
  863. }
  864. return $refsTables;
  865. } catch (Exception $e) {
  866. // echo "{$namespace} - {$e->getMessage}";
  867. return [];
  868. }
  869. }
  870. private function truncatePowiazaniaFromDB($ID) {
  871. $refsTables = $this->getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  872. if (!$refsTables) return null;
  873. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  874. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  875. $refsTables = array_diff($refsTables, [$refPowiazaniaToPowiazaniaRow]);
  876. $query = "delete from `" . implode("`, `", $refsTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  877. foreach ($refsTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  878. $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  879. DB::getPDO()->query($query);
  880. }
  881. private function deleteResultsFromDB($ID) {
  882. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  883. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  884. $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
  885. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  886. $refsTables = $this->getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  887. $sqlDeleteFrom = "delete from
  888. `{$refPowiazaniaToPowiazaniaRow}`,
  889. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
  890. `{$refPowiazaniaRowToPowiazaniaRowObject}`,
  891. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
  892. $sqlUsing = "
  893. using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  894. join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
  895. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
  896. join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
  897. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
  898. $sqlWhere = "
  899. where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  900. foreach ($refsTables as $refTable) {
  901. $sqlDeleteFrom .= ",\n`{$refTable}`";
  902. $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  903. }
  904. $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
  905. DB::getPDO()->query($query);
  906. }
  907. public function doGenerate() {
  908. function generatePhpScript($function) {
  909. return '<?php
  910. ini_set("memory_limit", "4G");
  911. define("DS", DIRECTORY_SEPARATOR);
  912. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  913. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  914. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  915. ini_set("display_startup_errors", "0");
  916. ini_set("log_errors", "1");
  917. ini_set("error_log", "/var/log/apache2/error_log");
  918. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  919. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  920. Lib::loadClass("Router");
  921. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  922. ';
  923. }
  924. try {
  925. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  926. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  927. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  928. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  929. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  930. ### Ustawienie zmiennych
  931. $powiazaniaDirLocation = $this->getMainDirectory();
  932. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  933. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  934. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  935. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  936. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  937. ### Utworzenie niezbędnych katalogów i plików
  938. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0755, true);
  939. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  940. ### Wymuszenie częsciowego odświezenia cache
  941. $sqlArr = [
  942. 'BI_analiza_reloadCache' => 'Part',
  943. 'FILE_STATUS_info' => 'Automatycznie wymuszono częściowe odświeżenie cache',
  944. ];
  945. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache not in ('Full', 'Part') and FILE_STATUS = 'TO_GENERATE'";
  946. $result = DB::getPDO()->fetchAll($query);
  947. foreach ($result as $row) {
  948. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  949. }
  950. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  951. $doGenerate = true;
  952. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part') and FILE_STATUS = 'TO_GENERATE'";
  953. $result = DB::getPDO()->fetchAll($query);
  954. if ($result) {
  955. $doGenerate = false;
  956. $sqlArr = [];
  957. if (file_exists($reloadCachePhpFile)) {
  958. if (file_exists($reloadCacheResultFile)) {
  959. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  960. if ($reloadCacheResult == "ok") {
  961. $sqlArr = [
  962. 'FILE_STATUS_info' => 'Odświeżono cache, oczekiwanie na wygenerowanie powiązań',
  963. 'BI_analiza_reloadCache' => 'No',
  964. ];
  965. $doGenerate = true;
  966. } else {
  967. $sqlArr = [
  968. 'FILE_STATUS' => 'ERROR',
  969. 'FILE_STATUS_info' => "Wystąpił błąd podczas odświeżania cache ({$reloadCacheResult})",
  970. ];
  971. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  972. $result = DB::getPDO()->fetchAll($query);
  973. }
  974. unlink($reloadCachePhpFile);
  975. unlink($reloadCachePidFile);
  976. unlink($reloadCacheResultFile);
  977. } elseif (file_exists($reloadCachePidFile)) {
  978. $pid = file_get_contents($reloadCachePidFile);
  979. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  980. $processShouldBeRunning = "php {$reloadCachePhpFile}";
  981. if ($processRunning != $processShouldBeRunning) {
  982. if (!file_exists($reloadCacheResultFile)) {
  983. $sqlArr = [
  984. 'FILE_STATUS' => 'ERROR',
  985. 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas odświeżania cache - nie znaleziono procesu potomnego",
  986. ];
  987. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  988. $result = DB::getPDO()->fetchAll($query);
  989. unlink($reloadCachePhpFile);
  990. unlink($reloadCachePidFile);
  991. unlink($reloadCacheResultFile);
  992. }
  993. }
  994. }
  995. } else {
  996. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  997. $result2 = DB::getPDO()->fetchValue($query);
  998. if ($result2) {
  999. $sqlArr = [
  1000. 'FILE_STATUS_info' => 'Wstrzymano odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  1001. ];
  1002. } else {
  1003. $sqlArr = [
  1004. 'FILE_STATUS_info' => 'W trakcie odświeżania cache',
  1005. ];
  1006. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
  1007. $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
  1008. file_put_contents($reloadCachePhpFile, generatePhpScript("doReloadCache({$fullReloadCache})"));
  1009. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  1010. }
  1011. }
  1012. if ($sqlArr) {
  1013. foreach ($result as $row) {
  1014. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  1015. }
  1016. }
  1017. }
  1018. ### Generowanie powiązań
  1019. if ($doGenerate) {
  1020. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
  1021. $result = DB::getPDO()->fetchAll($query);
  1022. foreach ($result as $row) {
  1023. $sqlArr = [
  1024. 'ID' => $row['ID'],
  1025. 'FILE_STATUS' => 'IN_PROGRESS',
  1026. 'FILE_STATUS_info' => 'W trakcie generowania powiązań',
  1027. ];
  1028. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1029. $this->deleteResultsFromDB($row['ID']);
  1030. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1031. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1032. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  1033. file_put_contents($generatePowiazaniaPhpFile, generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  1034. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  1035. }
  1036. }
  1037. ### Weryfikacja świeżo wygenerowanych powiązań
  1038. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1039. $result = DB::getPDO()->fetchAll($query);
  1040. foreach ($result as $row) {
  1041. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1042. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  1043. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1044. $generatePowiazaniaPdfFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pdf";
  1045. $generatePowiazaniaHtmlDir = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.html";
  1046. $generatePowiazaniaHtmlZipFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.zip";
  1047. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.xml";
  1048. $error = false;
  1049. $success = false;
  1050. $sqlArr = [];
  1051. if (file_exists($generatePowiazaniaResultFile)) {
  1052. $generatePowiazaniaResult = file_get_contents($generatePowiazaniaResultFile);
  1053. if ($generatePowiazaniaResult == "ok") {
  1054. if (file_exists($xmlFile)) {
  1055. if (filesize($xmlFile)) {
  1056. $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  1057. if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0777, false);
  1058. if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
  1059. else $success = true;
  1060. } else $error = "Wystąpił nieznany błąd - plk xml został wygenerowany niepoprawnie";
  1061. } else $error = "Wystąpił nienzany błąd - nie znaleziono pliku xml";
  1062. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult})";
  1063. } elseif (file_exists($generatePowiazaniaPidFile)) {
  1064. $pid = file_get_contents($generatePowiazaniaPidFile);
  1065. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1066. $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
  1067. if ($processRunning != $processShouldBeRunning) {
  1068. if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
  1069. }
  1070. }
  1071. if ($error) {
  1072. $sqlArr = [
  1073. 'FILE_STATUS' => 'ERROR',
  1074. 'FILE_STATUS_info' => $error,
  1075. ];
  1076. $this->deleteResultsFromDB($row['ID']);
  1077. if (file_exists($xmlFile)) unlink($xmlFile);
  1078. } elseif ($success) {
  1079. $sqlArr = [
  1080. 'FILE_STATUS' => 'GENERATED',
  1081. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  1082. ];
  1083. $destXmlFile = "{$powiazanieDirLocation}/relations.xml";
  1084. $destPdfFile = "{$powiazanieDirLocation}/relations.pdf";
  1085. $destHtmlDir = "{$powiazanieDirLocation}/html";
  1086. $destHtmlZipFile = "{$powiazanieDirLocation}/html.zip";
  1087. rename($xmlFile, $destXmlFile);
  1088. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1089. if (file_exists($generatePowiazaniaHtmlDir)) {
  1090. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1091. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1092. }
  1093. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1094. }
  1095. if ($sqlArr) {
  1096. $sqlArr['ID'] = $row['ID'];
  1097. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1098. if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
  1099. if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
  1100. if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
  1101. }
  1102. }
  1103. } catch (Exception $e) {
  1104. echo $e->getMessage()."\n";
  1105. }
  1106. }
  1107. private function reloadCache_reTeryt($full = false) {
  1108. Lib::loadClass('Teryt');
  1109. $tables = [
  1110. 'BI_audit_CEIDG' => [
  1111. 'fields' => [
  1112. 'wojewodztwo' => 'wojewodztwo',
  1113. 'powiat' => 'powiat',
  1114. 'gmina' => 'gmina',
  1115. 'miejscowosc' => 'miejscowosc',
  1116. 'ulica' => 'ulica',
  1117. 'kodPocztowy' => 'kodPocztowy',
  1118. ],
  1119. 'full' => false,
  1120. ],
  1121. 'BI_audit_CEIDG_pelnomocnicy' => [
  1122. 'fields' => [
  1123. 'wojewodztwo' => 'wojewodztwo',
  1124. 'powiat' => 'powiat',
  1125. 'gmina' => 'gmina',
  1126. 'miejscowosc' => 'miejscowosc',
  1127. 'ulica' => 'ulica',
  1128. 'kodPocztowy' => 'kodPocztowy',
  1129. ],
  1130. 'full' => false,
  1131. ],
  1132. 'BI_audit_ENERGA_PRACOWNICY' => [
  1133. 'fields' => [
  1134. 'miejscowosc' => 'miejscowosc',
  1135. 'kodPocztowy' => 'kodPocztowy',
  1136. 'ulica' => 'ulica',
  1137. ],
  1138. 'full' => true,
  1139. ],
  1140. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1141. 'fields' => [
  1142. 'kodPocztowy' => 'kodPocztowy',
  1143. 'miejscowosc' => 'miejscowosc',
  1144. 'ulica' => 'ulica',
  1145. ],
  1146. 'full' => true,
  1147. ],
  1148. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1149. 'fields' => [
  1150. 'kodPocztowy' => 'Kod_pocztowy',
  1151. 'miejscowosc' => 'Miejscowosc',
  1152. 'ulica' => 'Ulica',
  1153. ],
  1154. 'full' => true,
  1155. ],
  1156. 'BI_audit_KRS' => [
  1157. 'fields' => [
  1158. 'wojewodztwo' => 'S_wojewodztwo',
  1159. 'powiat' => 'S_powiat',
  1160. 'gmina' => 'S_gmina',
  1161. 'miejscowosc' => 'A_miejscowosc',
  1162. 'ulica' => 'A_ulica',
  1163. 'kodPocztowy' => 'A_kod',
  1164. ],
  1165. 'full' => false,
  1166. ],
  1167. 'BI_audit_KRS_address' => [
  1168. 'fields' => [
  1169. 'wojewodztwo' => 'S_wojewodztwo',
  1170. 'powiat' => 'S_powiat',
  1171. 'gmina' => 'S_gmina',
  1172. 'miejscowosc' => 'A_miejscowosc',
  1173. 'ulica' => 'A_ulica',
  1174. 'kodPocztowy' => 'A_kod',
  1175. ],
  1176. 'full' => false,
  1177. ],
  1178. 'BI_audit_MSIG_address' => [
  1179. 'fields' => [
  1180. 'wojewodztwo' => 'S_wojewodztwo',
  1181. 'powiat' => 'S_powiat',
  1182. 'gmina' => 'S_gmina',
  1183. 'miejscowosc' => 'A_miejscowosc',
  1184. 'ulica' => 'A_ulica',
  1185. 'kodPocztowy' => 'A_kod',
  1186. ],
  1187. 'full' => false,
  1188. ],
  1189. ];
  1190. foreach ($tables as $table => $tableConf) {
  1191. $where = ($full && $tableConf['full']) ? "" : "where `TERYT_SYM` is null and `cached` = 0";
  1192. $query = "select * from `{$table}` {$where}";
  1193. try {
  1194. $adresy = DB::getPDO()->query($query);
  1195. while ($adres = $adresy->fetch()) {
  1196. $search = [];
  1197. foreach ($tableConf['fields'] as $field => $param) if (!empty($adres[$param])) $search[$field] = $adres[$param];
  1198. try {
  1199. $teryt = Teryt::search($search);
  1200. if (!empty($teryt['SYM'])) {
  1201. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  1202. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  1203. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  1204. }
  1205. } catch (Exception $e) {
  1206. }
  1207. }
  1208. } catch (Exception $e) {
  1209. }
  1210. }
  1211. }
  1212. private function reloadCache_updateAll($full, $onlyBase) {
  1213. $tablesConf = [
  1214. 'BI_audit_CEIDG' => [
  1215. 'fields' => [
  1216. 'nip' => 'nip',
  1217. 'regon' => 'regon',
  1218. 'TERYT_SYM' => 'TERYT_SYM',
  1219. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1220. 'nrDomu' => 'budynek',
  1221. 'nrLokalu' => 'lokal',
  1222. ],
  1223. 'base' => '1',
  1224. ],
  1225. 'BI_audit_CEIDG_pelnomocnicy' => [
  1226. 'fields' => [
  1227. 'nip' => 'nip',
  1228. 'TERYT_SYM' => 'TERYT_SYM',
  1229. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1230. 'nrDomu' => 'budynek',
  1231. 'nrLokalu' => 'lokal',
  1232. ],
  1233. 'base' => '1',
  1234. ],
  1235. 'BI_audit_CEIDG_powiazania' => [
  1236. 'fields' => [
  1237. 'nip' => 'nip',
  1238. 'regon' => 'regon',
  1239. ],
  1240. 'base' => '1',
  1241. ],
  1242. 'BI_audit_ENERGA_PRACOWNICY' => [
  1243. 'fields' => [
  1244. 'nip' => 'nip',
  1245. 'regon' => 'regon',
  1246. 'pesel' => 'pesel',
  1247. 'TERYT_SYM' => 'TERYT_SYM',
  1248. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1249. 'nrDomu' => 'nr',
  1250. 'nrLokalu' => 'nrLokalu',
  1251. ],
  1252. 'base' => '0',
  1253. //'where' => '',
  1254. ],
  1255. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1256. 'fields' => [
  1257. 'TERYT_SYM' => 'TERYT_SYM',
  1258. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1259. 'nrDomu' => 'nrBudynku',
  1260. 'nrLokalu' => 'nrLokalu',
  1261. ],
  1262. 'base' => '0',
  1263. //'where' => '',
  1264. ],
  1265. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1266. 'fields' => [
  1267. 'krs' => 'KRS',
  1268. 'nip' => 'NIP',
  1269. 'regon' => 'REGON',
  1270. 'pesel' => 'PESEL',
  1271. 'TERYT_SYM' => 'TERYT_SYM',
  1272. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1273. 'nrDomu' => 'Numer_budynku',
  1274. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  1275. ],
  1276. 'base' => '0',
  1277. 'where' => "and ownCompany != 'Y'",
  1278. ],
  1279. 'BI_audit_KRS' => [
  1280. 'fields' => [
  1281. 'krs' => 'krs',
  1282. 'nip' => 'nip',
  1283. 'regon' => 'regon',
  1284. 'TERYT_SYM' => 'TERYT_SYM',
  1285. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1286. 'nrDomu' => 'A_nrDomu',
  1287. 'nrLokalu' => 'A_nrLokalu',
  1288. ],
  1289. 'base' => '1',
  1290. ],
  1291. 'BI_audit_KRS_address' => [
  1292. 'fields' => [
  1293. 'TERYT_SYM' => 'TERYT_SYM',
  1294. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1295. 'nrDomu' => 'A_nrDomu',
  1296. 'nrLokalu' => 'A_nrLokalu',
  1297. ],
  1298. 'base' => '1',
  1299. ],
  1300. 'BI_audit_KRS_company' => [
  1301. 'fields' => [
  1302. 'regon' => 'regon',
  1303. 'krs' => 'krs',
  1304. ],
  1305. 'base' => '1',
  1306. ],
  1307. 'BI_audit_KRS_person' => [
  1308. 'fields' => [
  1309. 'pesel' => 'pesel',
  1310. ],
  1311. 'base' => '1',
  1312. ],
  1313. 'BI_audit_MSIG' => [
  1314. 'fields' => [
  1315. 'krs' => 'krs',
  1316. 'nip' => 'nip',
  1317. 'regon' => 'regon',
  1318. ],
  1319. 'base' => '1',
  1320. ],
  1321. 'BI_audit_MSIG_address' => [
  1322. 'fields' => [
  1323. 'TERYT_SYM' => 'TERYT_SYM',
  1324. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1325. 'nrDomu' => 'A_nrDomu',
  1326. 'nrLokalu' => 'A_nrLokalu',
  1327. ],
  1328. 'base' => '1',
  1329. ],
  1330. 'BI_audit_MSIG_company' => [
  1331. 'fields' => [
  1332. 'regon' => 'regon',
  1333. 'krs' => 'krs',
  1334. ],
  1335. 'base' => '1',
  1336. ],
  1337. 'BI_audit_MSIG_person' => [
  1338. 'fields' => [
  1339. 'pesel' => 'pesel',
  1340. ],
  1341. 'base' => '1',
  1342. ],
  1343. // 'BI_audit_KW_requested_person' => [
  1344. // 'fields' => [
  1345. // 'pesel' => 'Seller_person_pesel',
  1346. // 'krs' => 'Seller_person_KRS',
  1347. // 'nip' => 'Seller_person_NIP',
  1348. // 'regon' => 'Seller_person_REGON',
  1349. // ],
  1350. // 'base' => '0',
  1351. // //'where' => '',
  1352. // ],
  1353. ];
  1354. $refTablesConf = [
  1355. 'BI_audit_CEIDG' => [
  1356. 'refTablesTo' => [
  1357. 'BI_audit_CEIDG_pelnomocnicy',
  1358. 'BI_audit_CEIDG_powiazania',
  1359. ],
  1360. 'base' => 1,
  1361. ],
  1362. 'BI_audit_ENERGA_PRACOWNICY' => [
  1363. 'refTablesTo' => [
  1364. 'BI_audit_ENERGA_PRACOWNICY_adresy',
  1365. ],
  1366. 'base' => 0,
  1367. ],
  1368. 'BI_audit_KRS' => [
  1369. 'refTablesTo' => [
  1370. 'BI_audit_KRS_address',
  1371. 'BI_audit_KRS_company',
  1372. 'BI_audit_KRS_person',
  1373. ],
  1374. 'base' => 1,
  1375. ],
  1376. 'BI_audit_MSIG' => [
  1377. 'refTablesTo' => [
  1378. 'BI_audit_MSIG_address',
  1379. 'BI_audit_MSIG_company',
  1380. 'BI_audit_MSIG_person',
  1381. ],
  1382. 'base' => 1,
  1383. ],
  1384. ];
  1385. if ($full) {
  1386. foreach ($tablesConf as $table => $tableConf) if (!$tableConf['base']) $queries[] = "update `{$table}` set `cached` = 0";
  1387. $queries[] = "delete from BI_audit_ALL where BASE = 0";
  1388. $queries[] = "delete from BI_audit_ALL_ref where BASE = 0";
  1389. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  1390. if ($refTableConf['base']) continue;
  1391. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  1392. $refTable = ACL::getRefTable("default_db/{$refTableFrom}/{$refTableFrom}", "default_db__x3A__{$refTableTo}:{$refTableTo}");
  1393. $queries[] = "update `{$refTable}` set `A_STATUS` = 'WAITNG' where `A_STATUS` = 'NORMAL'";
  1394. }
  1395. }
  1396. }
  1397. foreach ($tablesConf as $table => $tableConf) {
  1398. if ($onlyBase && (!$tableConf['base'])) continue;
  1399. $where = "where `cached` = 0";
  1400. if (!empty($tableConf['where'])) $where .= " {$tableConf['where']}";
  1401. // $queries[] = "lock tables `{$table}` write";
  1402. $queries[] = "insert into `BI_audit_ALL` (`REMOTE_TABLE`, `REMOTE_ID`, `BASE`, " . implode(", ", array_keys($tableConf['fields'])) .
  1403. ") select '{$table}', ID, '{$tableConf['base']}', " . implode(", ", $tableConf['fields']) . " from `{$table}` {$where}";
  1404. $queries[] = "update `{$table}` set `cached` = 1 {$where}";
  1405. // $queries[] = "unlock tables";
  1406. }
  1407. $queries[] = "update `BI_audit_ALL` set `nip` = null where `nip` = 0";
  1408. $queries[] = "update `BI_audit_ALL` set `regon` = null where `regon` = 0";
  1409. $queries[] = "update `BI_audit_ALL` set `krs` = null where `krs` = 0";
  1410. $queries[] = "update `BI_audit_ALL` set `pesel` = null where `pesel` = 0";
  1411. $queries[] = "update `BI_audit_ALL` set `TERYT_SYM` = null where `TERYT_SYM` = 0";
  1412. $queries[] = "update `BI_audit_ALL` set `TERYT_SYM_UL` = null where `TERYT_SYM_UL` = 0";
  1413. $queries[] = "update `BI_audit_ALL` set `nrDomu` = null where trim(`nrDomu`) = ''";
  1414. $queries[] = "update `BI_audit_ALL` set `nrLokalu` = null where trim(`nrLokalu`) = ''";
  1415. $queries[] = "update `BI_audit_ALL` set `nrDomu` = substring(`nrDomu`, 1, position('/' in `nrDomu`) - 1), `nrLokalu` = substring(`nrDomu`, position('/' in `nrDomu`) + 1) where `reffed` = 0 and `nrDomu` rlike '^[[:digit:]]+.*/[[:digit:]]+.*$' and `nrLokalu` is null";
  1416. $queries[] = "set @var = (select round(coalesce(max(`ID`), '0.5'), 1) from `BI_audit_ALL_ref_RELATIONS`)";
  1417. $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";
  1418. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  1419. if ($onlyBase && (!$tableConf['base'])) continue;
  1420. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  1421. $refTable = ACL::getRefTable("default_db/{$refTableFrom}/{$refTableFrom}", "default_db__x3A__{$refTableTo}:{$refTableTo}");
  1422. // $queries[] = "lock tables `{$refTable}` write";
  1423. $joins = "`BI_audit_ALL` as `all1` join `{$refTable}` as `ref` on `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all1`.`REMOTE_ID` = `ref`.`PRIMARY_KEY` and `ref`.`A_STATUS` = 'WAITING' join `BI_audit_ALL` as `all2` on `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref`.`REMOTE_PRIMARY_KEY` = `all2`.`REMOTE_ID` join `BI_audit_ALL_ref_RELATIONS` `rel` on `all1`.`REMOTE_TABLE` = `rel`.`RELATION`";
  1424. $queries[] = "insert ignore into `BI_audit_ALL_ref` (`ID1`, `ID2`, `RELATION_ID`, `BASE`) select `all1`.`ID`, `all2`.`ID`, `rel`.`ID`, {$refTableConf['base']} from {$joins}";
  1425. $queries[] = "insert ignore into `BI_audit_ALL_ref` (`ID1`, `ID2`, `RELATION_ID`, `BASE`) select `all2`.`ID`, `all1`.`ID`, `rel`.`ID`, {$refTableConf['base']} from {$joins}";
  1426. $queries[] = "update {$joins} set `ref`.`A_STATUS` = 'NORMAL'";
  1427. // $queries[] = "unlock tables";
  1428. }
  1429. }
  1430. // echo implode(";\n", $queries) . ";\n";
  1431. foreach ($queries as $query) {
  1432. echo "SQL: {$query}\n";
  1433. DB::getPDO()->query($query);
  1434. }
  1435. $BiAuditRelations = new BiAuditRelations();
  1436. // DB::getPDO()->query("lock tables `BI_audit_ALL` write");
  1437. $result = DB::getPDO()->query("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
  1438. while ($row = $result->fetch()) $BiAuditRelations->findRelations($row['ID']);
  1439. DB::getPDO()->query("update `BI_audit_ALL` set `reffed` = 1");
  1440. // DB::getPDO()->query("unlock tables");
  1441. }
  1442. public function doReloadCache($full = false) {
  1443. if ($full == 'base') {
  1444. $onlyBase = true;
  1445. $full = false;
  1446. } else {
  1447. $onlyBase = false;
  1448. }
  1449. $powiazaniaDirLocation = $this->getMainDirectory();
  1450. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1451. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1452. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1453. file_put_contents($reloadCachePidFile, getmypid());
  1454. try {
  1455. $this->reloadCache_reTeryt($full);
  1456. $this->reloadCache_updateAll($full, $onlyBase);
  1457. file_put_contents($reloadCacheResultFile, "ok");
  1458. } catch (Exception $e) {
  1459. file_put_contents($reloadCacheResultFile, $e->getMessage());
  1460. }
  1461. }
  1462. public function doGeneratePowiazania($ID) {
  1463. $powiazaniaDirLocation = $this->getMainDirectory();
  1464. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1465. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  1466. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  1467. $pdfFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pdf";
  1468. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  1469. file_put_contents($pidFile, getmypid());
  1470. $tablesConf = [
  1471. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  1472. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  1473. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  1474. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  1475. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  1476. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  1477. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  1478. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  1479. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  1480. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  1481. ];
  1482. try {
  1483. $BiAuditPowiazania = new BiAuditPowiazania($ID);
  1484. if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  1485. file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  1486. $BiAuditPowiazania->saveToDb();
  1487. $BiAuditPowiazania->generatePdfAndHtml($tasksDirLocation);
  1488. file_put_contents($resultFile, "ok");
  1489. } catch (Exception $e) {
  1490. file_put_contents($resultFile, $e->getMessage());
  1491. }
  1492. }
  1493. public function reinstallAction() {
  1494. $this->reinstall();
  1495. die('OK');
  1496. }
  1497. public function reinstall() {
  1498. $sqlList = array();
  1499. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  1500. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  1501. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  1502. SQL;
  1503. $sqlList['ChangeStructure1'] = <<<SQL
  1504. 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';
  1505. SQL;
  1506. $sqlList['ChangeStructure2'] = <<<SQL
  1507. UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
  1508. SQL;
  1509. $sqlList['ChangeStructure3'] = <<<SQL
  1510. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
  1511. SQL;
  1512. $sqlList['ChangeStructure4'] = <<<SQL
  1513. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_depth` `BI_analiza_maxDepth` INT(2) NULL DEFAULT '9';
  1514. SQL;
  1515. $sqlList['ChangeStructure5'] = <<<SQL
  1516. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_minDepth` INT(2) NOT NULL DEFAULT '0' AFTER `FILE_STATUS_info`;
  1517. SQL;
  1518. $sqlList['ChangeStructure6'] = <<<SQL
  1519. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_onlyTargets` ENUM('Y','N') NOT NULL DEFAULT 'Y' AFTER `BI_analiza_maxDepth`;
  1520. SQL;
  1521. $db = DB::getDB();
  1522. if ($db->has_errors()) {
  1523. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  1524. }
  1525. foreach ($sqlList as $sqlName => $sql) {
  1526. $res = $db->query($sql);
  1527. if ($db->has_errors()) {
  1528. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  1529. }
  1530. }
  1531. }
  1532. }
  1533. class BiAuditRelations {
  1534. private $RELATIONS_ID = [];
  1535. private $relations = [
  1536. 'nip' => ['nip'],
  1537. 'regon' => ['regon'],
  1538. 'krs' => ['krs'],
  1539. 'pesel' => ['pesel'],
  1540. 'adres' => ['TERYT_SYM', 'TERYT_SYM_UL', 'nrDomu', 'nrLokalu'],
  1541. ];
  1542. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1543. private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  1544. public function __construct() {
  1545. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  1546. $result = DB::getPDO()->fetchAll($query);
  1547. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  1548. }
  1549. private function getRelationID($name) {
  1550. if (!isset($this->RELATIONS_ID[$name])) {
  1551. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  1552. $newID = DB::getPDO()->fetchValue($query);
  1553. $this->RELATIONS_ID[$name] = $newID;
  1554. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  1555. DB::getPDO()->query($query);
  1556. }
  1557. return $this->RELATIONS_ID[$name];
  1558. }
  1559. public function findRelations($ID) {
  1560. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  1561. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  1562. $row = $result[0];
  1563. $joins = [];
  1564. $items = '';
  1565. foreach ($this->relations as $name => $columns) {
  1566. $ok = 0;
  1567. $join = [];
  1568. foreach ($columns as $column) {
  1569. $join[] = "t1.{$column} = t2.{$column}";
  1570. if ($row[$column]) $ok++;
  1571. }
  1572. if ($ok / count($columns) > 0.5) {
  1573. $joins[] = "(" . implode(" and ", $join) . ")";
  1574. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  1575. }
  1576. }
  1577. if (!$joins) return false;
  1578. $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 " .
  1579. "from BI_audit_ALL t1 join BI_audit_ALL t2 on " . implode(" or ", $joins) . " where t1.ID = {$ID} and (t2.reffed = 1 or t2.ID > {$ID})";
  1580. $result = DB::getPDO()->fetchAll($query);
  1581. foreach ($result as $row) {
  1582. $relationID = 0;
  1583. foreach ($this->relations as $name => $v) {
  1584. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  1585. }
  1586. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  1587. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  1588. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  1589. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  1590. if (!($start2 || $end1)) {
  1591. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
  1592. DB::getPDO()->query($query);
  1593. }
  1594. if (!($start1 || $end2)) {
  1595. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
  1596. DB::getPDO()->query($query);
  1597. }
  1598. }
  1599. }
  1600. }
  1601. class BiAuditPowiazania {
  1602. private $minDepth;
  1603. private $maxDepth;
  1604. private $onlyTargets;
  1605. private $ID;
  1606. private $endNodes;
  1607. private $path = [];
  1608. private $results = [];
  1609. private $items_results = [];
  1610. private $relations = [];
  1611. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1612. private $refTables = [];
  1613. private function getRefTable($tableFrom, $tableTo, $returnException = true) {
  1614. if (!isset($this->refTables[$tableFrom][$tableTo])) {
  1615. try {
  1616. $this->refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
  1617. } catch (Exception $e) {
  1618. if ($returnException) throw new Exception($e->getMessage());
  1619. $this->refTables[$tableFrom][$tableTo] = false;
  1620. }
  1621. }
  1622. return $this->refTables[$tableFrom][$tableTo];
  1623. }
  1624. public function __construct($ID = 0) {
  1625. if (!$ID) throw new Exception("Wrong ID parameter");
  1626. $query = "select BI_analiza_minDepth, BI_analiza_maxDepth, BI_analiza_onlyTargets from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$ID}' and FILE_STATUS = 'IN_PROGRESS' and BI_analiza_reloadCache not in ('Full', 'Part')";
  1627. $result = DB::getPDO()->fetchAll($query);
  1628. if (!$result) throw new Exception("Błąd danych");
  1629. $this->minDepth = (int) $result[0]['BI_analiza_minDepth'];
  1630. $this->maxDepth = (int) $result[0]['BI_analiza_maxDepth'];
  1631. $this->onlyTargets = ($result[0]['BI_analiza_onlyTargets'] != 'N');
  1632. if (!$this->minDepth) $this->minDepth = 1;
  1633. if (!$this->maxDepth) throw new Exception("Błąd danych - nieokreślono maksymalnej głębokości analizy");
  1634. if ($this->minDepth > $this->maxDepth) throw new Exception("Wartość minimalnej głębokości analizy jest większa od wartości maksymalnej głębokości analizy");
  1635. $this->ID = $ID;
  1636. $subQueries = [];
  1637. foreach ($this->destTables as $destTable) {
  1638. $refTable = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $destTable);
  1639. $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}'";
  1640. }
  1641. $query = implode(" union ", $subQueries);
  1642. $result = DB::getPDO()->fetchAll($query);
  1643. if (!$result) throw new Exception("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  1644. $this->endNodes = array_map('reset', $result);
  1645. $refPowiazaniaToPracownicy = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY');
  1646. $query = "select `all`.ID as ID from BI_audit_ALL `all` join `{$refPowiazaniaToPracownicy}` ref
  1647. on `all`.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and `all`.REMOTE_ID = ref.REMOTE_PRIMARY_KEY and ref.PRIMARY_KEY = '{$ID}'";
  1648. $result = DB::getPDO()->fetchAll($query);
  1649. foreach ($result as $row) $this->findPowiazania($row['ID']);
  1650. }
  1651. public function findPowiazania($ID, $relation = "", $end = 0) {
  1652. if (isset($this->path[$ID])) return false;
  1653. $this->path[$ID] = $relation;
  1654. if (!$relation) $relation = 0;
  1655. if ($end) {
  1656. if (in_array($ID, $this->endNodes) && count($this->path) > $this->minDepth) $this->results[] = $this->path;
  1657. array_pop($this->path);
  1658. return true;
  1659. }
  1660. if (count($this->path) > $this->maxDepth) {
  1661. if (!$this->onlyTargets) $this->results[] = $this->path;
  1662. array_pop($this->path);
  1663. return false;
  1664. }
  1665. $nodes = [];
  1666. if ($relation) $where = "and ({$relation} & ref.RELATION_ID) != {$relation}";
  1667. else $where = "";
  1668. $query = "select ref.ID2, RELATION_ID, END from BI_audit_ALL_ref ref where ref.ID1 = '{$ID}' {$where}";
  1669. $result = DB::query($query);
  1670. while ($row = DB::fetch($result)) $nodes[$row->ID2] = ['relation' => (int) $row->RELATION_ID, 'end' => $row->END];
  1671. foreach ($nodes as $node => $data) $this->findPowiazania($node, $data['relation'], $data['end']);
  1672. array_pop($this->path);
  1673. }
  1674. private function relationName($ID) {
  1675. if (!isset($this->relations[$ID])) {
  1676. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  1677. $result = DB::getPDO()->fetchAll($query);
  1678. $rels = array_map('reset', $result);
  1679. $this->relations[$ID] = implode(", ", $rels);
  1680. }
  1681. return $this->relations[$ID];
  1682. }
  1683. private function generateItemsResults() {
  1684. $xmlRoot2 = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  1685. $xmlElements = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  1686. $this->items_results = [];
  1687. $items_kontrahenci = [];
  1688. $items_kw_person = [];
  1689. $kontrahenci = [];
  1690. $kw_person = [];
  1691. $refUmowyToKontrahenci = $this->getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI');
  1692. $refKwRequestedToKwRequestedPerson = $this->getRefTable('BI_audit_KW_requested', 'BI_audit_KW_requested_person');
  1693. foreach ($this->results as $result) {
  1694. $item_results = [];
  1695. foreach ($result as $ID => $rel) {
  1696. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  1697. $row = DB::getPDO()->fetchFirst($query);
  1698. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  1699. $obj = DB::fetch(DB::query($query));
  1700. $item_result = [$row['REMOTE_TABLE'] => (array) $obj];
  1701. if ($refTable = $this->getRefTable('BI_audit_operational_raport_note', $row['REMOTE_TABLE'], false)) {
  1702. $query = "select `note`.* from `BI_audit_operational_raport_note` `note` join `{$refTable}` `ref` on `note`.`ID` = `ref`.`PRIMARY_KEY` where `ref`.`REMOTE_PRIMARY_KEY` = '{$row['REMOTE_ID']}'";
  1703. if ($notes = DB::getPDO()->fetchAll($query)) $item_result[$row['REMOTE_TABLE']]['BI_audit_operational_raport_note'] = $notes;
  1704. }
  1705. if ($refTable = $this->getRefTable($row['REMOTE_TABLE'], 'BI_audit_taxpayer', false)) {
  1706. $query = "select `taxpayer`.* from `{$refTable}` `ref` join `BI_audit_taxpayer` `taxpayer` on `ref`.`REMOTE_PRIMARY_KEY` = `taxpayer`.`ID` where `ref`.`PRIMARY_KEY` = '{$row['REMOTE_ID']}'";
  1707. if ($taxpayer = DB::getPDO()->fetchFirst($query)) $item_result[$row['REMOTE_TABLE']]['BI_audit_taxpayer'] = $taxpayer;
  1708. }
  1709. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  1710. $item_results['object'][] = $item_result;
  1711. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  1712. $kontrahenci[] = $row['REMOTE_ID'];
  1713. $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']}'";
  1714. $res = DB::query($query);
  1715. if (mysql_num_rows($res)) {
  1716. $umowy = [];
  1717. while ($obj = DB::fetch($res)) $umowy[] = (array) $obj;
  1718. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  1719. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  1720. $items_kontrahenci[] = $item_kontrahenci;
  1721. }
  1722. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  1723. $kw_person[] = $row['REMOTE_ID'];
  1724. $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']}'";
  1725. $res = DB::query($query);
  1726. if (mysql_num_rows($res)) {
  1727. $kw = [];
  1728. while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
  1729. $item_kw_person['ID'] = $row['REMOTE_ID'];
  1730. $item_kw_person['BI_audit_KW_requested'] = $kw;
  1731. $items_kw_person[] = $item_kw_person;
  1732. }
  1733. }
  1734. }
  1735. $this->items_results[$xmlRoot2][$xmlElements][] = $item_results;
  1736. }
  1737. $this->items_results[$xmlRoot2]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  1738. $this->items_results[$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;
  1739. }
  1740. public function saveToDb() {
  1741. if (!$this->results) return null;
  1742. $refPowiazaniaToPowiazaniaRow = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  1743. $refPowiazaniaRowToPowiazaniaRowObject = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  1744. foreach ($this->results as $result) {
  1745. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  1746. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  1747. foreach ($result as $ID => $rel) {
  1748. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  1749. $object = DB::getPDO()->fetchFirst($query);
  1750. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relations[$rel]]);
  1751. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  1752. $ref = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', $object['REMOTE_TABLE']);
  1753. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  1754. }
  1755. }
  1756. }
  1757. public function asXml() {
  1758. if (!$this->results) return null;
  1759. if (!$this->items_results) $this->generateItemsResults();
  1760. $xmlRoot = "RelatedFeatureRoot";
  1761. return V::arrayToXML($this->items_results, true, $xmlRoot);
  1762. }
  1763. public function asArray($subArray = null) {
  1764. if (!$this->results) return null;
  1765. if (!$this->items_results) $this->generateItemsResults();
  1766. if ($subArray) {
  1767. if (isset($this->items_results[$subArray])) return $this->items_results[$subArray];
  1768. else return [];
  1769. } else return $this->items_results;
  1770. }
  1771. public function powiazaniaFound() {
  1772. if ($this->results) return true;
  1773. else return false;
  1774. }
  1775. public function generatePdfAndHtml($tasksDirLocation) {
  1776. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
  1777. $pdfDestFile = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.pdf";
  1778. $htmlDestDir = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.html";
  1779. $htmlZipDestFile = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.zip";
  1780. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  1781. $antXmlFilename = "relations-{$this->ID}.out_task.dita.final_with_RelatedFeatureLoop.xml";
  1782. $antXmlFile = $antDir . "/" . $antXmlFilename;
  1783. $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";
  1784. $htmlDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$this->ID}/html";
  1785. if (!file_exists($antDir)) mkdir($antDir, 0755, true);
  1786. if (!is_dir($antDir)) $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć pliku PDF";
  1787. else {
  1788. copy($xmlFile, $antXmlFile);
  1789. 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}");
  1790. 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");
  1791. if (file_exists($pdfFile)) rename($pdfFile, $pdfDestFile);
  1792. 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");
  1793. if (file_exists($htmlDir) && is_dir($htmlDir)) {
  1794. 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");
  1795. if (file_exists($htmlDestDir)) shell_exec("rm -rf \"{$htmlDestDir}\"");
  1796. shell_exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
  1797. }
  1798. }
  1799. }
  1800. }