BiAuditGenerate.php 77 KB

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