BiAuditGenerate.php 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808
  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. 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 dokonano dowolnych zmian w tabelach pracowników/kontrahentów.<br/>
  381. Pełne odświeżenie wymagane w przypadku modyfikacji baz KRS lub CEiDG (UWAGA - trwa to wiele godzin)
  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. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  941. $doGenerate = true;
  942. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part') and FILE_STATUS = 'TO_GENERATE'";
  943. $result = DB::getPDO()->fetchAll($query);
  944. if ($result) {
  945. $doGenerate = false;
  946. $sqlArr = [];
  947. if (file_exists($reloadCachePhpFile)) {
  948. if (file_exists($reloadCacheResultFile)) {
  949. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  950. if ($reloadCacheResult == "ok") {
  951. $sqlArr = [
  952. 'FILE_STATUS_info' => 'Odświeżono cache, oczekiwanie na wygenerowanie powiązań',
  953. 'BI_analiza_reloadCache' => 'No',
  954. ];
  955. $doGenerate = true;
  956. } else {
  957. $sqlArr = [
  958. 'FILE_STATUS' => 'ERROR',
  959. 'FILE_STATUS_info' => "Wystąpił błąd podczas odświeżania cache ({$reloadCacheResult})",
  960. ];
  961. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  962. $result = DB::getPDO()->fetchAll($query);
  963. }
  964. unlink($reloadCachePhpFile);
  965. unlink($reloadCachePidFile);
  966. unlink($reloadCacheResultFile);
  967. } elseif (file_exists($reloadCachePidFile)) {
  968. $pid = file_get_contents($reloadCachePidFile);
  969. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  970. $processShouldBeRunning = "php {$reloadCachePhpFile}";
  971. if ($processRunning != $processShouldBeRunning) {
  972. if (!file_exists($reloadCacheResultFile)) {
  973. $sqlArr = [
  974. 'FILE_STATUS' => 'ERROR',
  975. 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas odświeżania cache - nie znaleziono procesu potomnego",
  976. ];
  977. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  978. $result = DB::getPDO()->fetchAll($query);
  979. unlink($reloadCachePhpFile);
  980. unlink($reloadCachePidFile);
  981. unlink($reloadCacheResultFile);
  982. }
  983. }
  984. }
  985. } else {
  986. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  987. $result2 = DB::getPDO()->fetchValue($query);
  988. if ($result2) {
  989. $sqlArr = [
  990. 'FILE_STATUS_info' => 'Wstrzymano odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  991. ];
  992. } else {
  993. $sqlArr = [
  994. 'FILE_STATUS_info' => 'W trakcie odświeżania cache',
  995. ];
  996. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
  997. $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
  998. file_put_contents($reloadCachePhpFile, generatePhpScript("doReloadCache({$fullReloadCache})"));
  999. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  1000. }
  1001. }
  1002. if ($sqlArr) {
  1003. foreach ($result as $row) {
  1004. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  1005. }
  1006. }
  1007. }
  1008. ### Generowanie powiązań
  1009. if ($doGenerate) {
  1010. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
  1011. $result = DB::getPDO()->fetchAll($query);
  1012. foreach ($result as $row) {
  1013. $sqlArr = [
  1014. 'ID' => $row['ID'],
  1015. 'FILE_STATUS' => 'IN_PROGRESS',
  1016. 'FILE_STATUS_info' => 'W trakcie generowania powiązań',
  1017. ];
  1018. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1019. $this->deleteResultsFromDB($row['ID']);
  1020. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1021. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1022. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  1023. file_put_contents($generatePowiazaniaPhpFile, generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  1024. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  1025. }
  1026. }
  1027. ### Weryfikacja świeżo wygenerowanych powiązań
  1028. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1029. $result = DB::getPDO()->fetchAll($query);
  1030. foreach ($result as $row) {
  1031. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1032. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  1033. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1034. $generatePowiazaniaPdfFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pdf";
  1035. $generatePowiazaniaHtmlDir = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.html";
  1036. $generatePowiazaniaHtmlZipFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.zip";
  1037. $error = false;
  1038. $success = false;
  1039. $sqlArr = [];
  1040. if (file_exists($generatePowiazaniaResultFile)) {
  1041. $generatePowiazaniaResult = file_get_contents($generatePowiazaniaResultFile);
  1042. if ($generatePowiazaniaResult == "ok") {
  1043. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.xml";
  1044. if (file_exists($xmlFile)) {
  1045. if (filesize($xmlFile)) {
  1046. $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  1047. if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0777, false);
  1048. if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
  1049. else $success = true;
  1050. } else $error = "Wystąpił nieznany błąd - plk xml został wygenerowany niepoprawnie";
  1051. } else $error = "Wystąpił nienzany błąd - nie znaleziono pliku xml";
  1052. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult})";
  1053. } elseif (file_exists($generatePowiazaniaPidFile)) {
  1054. $pid = file_get_contents($generatePowiazaniaPidFile);
  1055. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1056. $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
  1057. if ($processRunning != $processShouldBeRunning) {
  1058. if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
  1059. }
  1060. }
  1061. if ($error) {
  1062. $sqlArr = [
  1063. 'FILE_STATUS' => 'ERROR',
  1064. 'FILE_STATUS_info' => $error,
  1065. ];
  1066. $this->deleteResultsFromDB($row['ID']);
  1067. if (file_exists($xmlFile)) unlink($xmlFile);
  1068. } elseif ($success) {
  1069. $sqlArr = [
  1070. 'FILE_STATUS' => 'GENERATED',
  1071. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  1072. ];
  1073. $destXmlFile = "{$powiazanieDirLocation}/relations.xml";
  1074. $destPdfFile = "{$powiazanieDirLocation}/relations.pdf";
  1075. $destHtmlDir = "{$powiazanieDirLocation}/html";
  1076. $destHtmlZipFile = "{$powiazanieDirLocation}/html.zip";
  1077. rename($xmlFile, $destXmlFile);
  1078. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1079. if (file_exists($generatePowiazaniaHtmlDir)) {
  1080. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1081. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1082. }
  1083. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1084. }
  1085. if ($sqlArr) {
  1086. $sqlArr['ID'] = $row['ID'];
  1087. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1088. if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
  1089. if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
  1090. if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
  1091. }
  1092. }
  1093. } catch (Exception $e) {
  1094. echo $e->getMessage()."\n";
  1095. }
  1096. }
  1097. private function reloadCache_reTeryt($full = false) {
  1098. Lib::loadClass('Teryt');
  1099. function reTeryt($table) {
  1100. $tableConf = [
  1101. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1102. 'kodPocztowy' => 'Kod_pocztowy',
  1103. 'miejscowosc' => 'Miejscowosc',
  1104. 'ulica' => 'Ulica',
  1105. ],
  1106. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1107. 'kodPocztowy' => 'kodPocztowy',
  1108. 'miejscowosc' => 'miejscowosc',
  1109. 'ulica' => 'ulica',
  1110. ],
  1111. 'BI_audit_KRS' => [
  1112. 'wojewodztwo' => 'S_wojewodztwo',
  1113. 'powiat' => 'S_powiat',
  1114. 'gmina' => 'S_gmina',
  1115. 'miejscowosc' => 'A_miejscowosc',
  1116. 'ulica' => 'A_ulica',
  1117. 'kodPocztowy' => 'A_kod',
  1118. ],
  1119. 'BI_audit_CEIDG' => [
  1120. 'wojewodztwo' => 'wojewodztwo',
  1121. 'powiat' => 'powiat',
  1122. 'gmina' => 'gmina',
  1123. 'miejscowosc' => 'miejscowosc',
  1124. 'ulica' => 'ulica',
  1125. 'kodPocztowy' => 'kodPocztowy',
  1126. ],
  1127. ];
  1128. $columns = ['kodPocztowy', 'miejscowosc', 'ulica'];
  1129. $query = "select * from `{$table}` where TERYT_SYM is null";
  1130. try {
  1131. $adresy = DB::getPDO()->fetchall($query);
  1132. foreach ($adresy as $adres) {
  1133. $search = [];
  1134. foreach ($columns as $column) $search[$column] = $adres[$tableConf[$table][$column]];
  1135. try {
  1136. $teryt = Teryt::search($search);
  1137. if ($teryt) {
  1138. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  1139. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  1140. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  1141. }
  1142. } catch (Exception $e) {
  1143. }
  1144. }
  1145. } catch (Exception $e) {
  1146. }
  1147. }
  1148. if ($full) {
  1149. reTeryt('BI_audit_KRS');
  1150. reTeryt('BI_audit_CEIDG');
  1151. }
  1152. reTeryt('BI_audit_ENERGA_RUM_KONTRAHENCI');
  1153. reTeryt('BI_audit_ENERGA_PRACOWNICY_adresy');
  1154. }
  1155. private function reloadCache_updateAll($full = false) {
  1156. $tables = [
  1157. 'BI_audit_ENERGA_PRACOWNICY' => [
  1158. 'fields' => [
  1159. 'nip' => 'nip',
  1160. 'regon' => 'regon',
  1161. 'pesel' => 'pesel',
  1162. ],
  1163. 'base' => '0',
  1164. //'where' => '',
  1165. ],
  1166. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1167. 'fields' => [
  1168. 'TERYT_SYM' => 'TERYT_SYM',
  1169. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1170. 'nrDomu' => 'nrBudynku',
  1171. 'nrLokalu' => 'nrLokalu',
  1172. ],
  1173. 'base' => '0',
  1174. //'where' => '',
  1175. ],
  1176. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1177. 'fields' => [
  1178. 'krs' => 'KRS',
  1179. 'nip' => 'NIP',
  1180. 'regon' => 'REGON',
  1181. 'pesel' => 'PESEL',
  1182. 'TERYT_SYM' => 'TERYT_SYM',
  1183. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1184. 'nrDomu' => 'Numer_budynku',
  1185. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  1186. ],
  1187. 'base' => '0',
  1188. 'where' => "ownCompany != 'Y'",
  1189. ],
  1190. 'BI_audit_KW_requested_person' => [
  1191. 'fields' => [
  1192. 'pesel' => 'Seller_person_pesel',
  1193. 'krs' => 'Seller_person_KRS',
  1194. 'nip' => 'Seller_person_NIP',
  1195. 'regon' => 'Seller_person_REGON',
  1196. ],
  1197. 'base' => '0',
  1198. //'where' => '',
  1199. ],
  1200. ];
  1201. $tables_full = [
  1202. 'BI_audit_CEIDG' => [
  1203. 'fields' => [
  1204. 'nip' => 'nip',
  1205. 'regon' => 'regon',
  1206. 'TERYT_SYM' => 'TERYT_SYM',
  1207. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1208. 'nrDomu' => 'budynek',
  1209. 'nrLokalu' => 'lokal',
  1210. ],
  1211. 'base' => '1',
  1212. ],
  1213. 'BI_audit_CEIDG_pelnomocnicy' => [
  1214. 'fields' => [
  1215. 'nip' => 'nip',
  1216. 'TERYT_SYM' => 'TERYT_SYM',
  1217. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1218. 'nrDomu' => 'budynek',
  1219. 'nrLokalu' => 'lokal',
  1220. ],
  1221. 'base' => '1',
  1222. ],
  1223. 'BI_audit_CEIDG_powiazania' => [
  1224. 'fields' => [
  1225. 'nip' => 'nip',
  1226. 'regon' => 'regon',
  1227. ],
  1228. 'base' => '1',
  1229. ],
  1230. 'BI_audit_KRS' => [
  1231. 'fields' => [
  1232. 'krs' => 'krs',
  1233. 'nip' => 'nip',
  1234. 'regon' => 'regon',
  1235. 'TERYT_SYM' => 'TERYT_SYM',
  1236. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1237. 'nrDomu' => 'A_nrDomu',
  1238. 'nrLokalu' => 'A_nrLokalu',
  1239. ],
  1240. 'base' => '1',
  1241. ],
  1242. 'BI_audit_KRS_company' => [
  1243. 'fields' => [
  1244. 'regon' => 'regon',
  1245. 'krs' => 'krs',
  1246. ],
  1247. 'base' => '1',
  1248. ],
  1249. 'BI_audit_KRS_person' => [
  1250. 'fields' => [
  1251. 'pesel' => 'pesel',
  1252. ],
  1253. 'base' => '1',
  1254. ],
  1255. ];
  1256. if ($full) {
  1257. $tables = array_merge($tables_full, $tables);
  1258. $fullWhere = '1 = 1';
  1259. } else {
  1260. $fullWhere = 'BASE = 0';
  1261. }
  1262. $queries[] = "delete from BI_audit_ALL where {$fullWhere}";
  1263. $queries[] = "delete from BI_audit_ALL_ref where {$fullWhere}";
  1264. //$queries[] = "delete from BI_audit_ALL_ref_RELATIONS where {$fullWhere}"; // niepotrzebne
  1265. foreach ($tables as $name => $table) {
  1266. if (isset($table['where']) && $table['where']) $where = "where {$table['where']}";
  1267. else $where = '';
  1268. $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}";
  1269. }
  1270. $queries[] = "update BI_audit_ALL set nip = null where nip = 0";
  1271. $queries[] = "update BI_audit_ALL set regon = null where regon = 0";
  1272. $queries[] = "update BI_audit_ALL set krs = null where krs = 0";
  1273. $queries[] = "update BI_audit_ALL set pesel = null where pesel = 0";
  1274. $queries[] = "update BI_audit_ALL set TERYT_SYM = null where TERYT_SYM = 0";
  1275. $queries[] = "update BI_audit_ALL set TERYT_SYM_UL = null where TERYT_SYM_UL = 0";
  1276. $queries[] = "update BI_audit_ALL set nrDomu = null where trim(nrDomu) = ''";
  1277. $queries[] = "update BI_audit_ALL set nrLokalu = null where trim(nrLokalu) = ''";
  1278. $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}";
  1279. $queries[] = "set @var = (select round(coalesce(max(ID), '0.5'), 1) from BI_audit_ALL_ref_RELATIONS)";
  1280. $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";
  1281. if ($full) {
  1282. $refCeidgToCeidgPelnomocnicy = ACL::getRefTable('default_db/BI_audit_CEIDG/BI_audit_CEIDG', "default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy");
  1283. $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";
  1284. $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";
  1285. $refCeidgToCeidgPowiazania = ACL::getRefTable('default_db/BI_audit_CEIDG/BI_audit_CEIDG', "default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania");
  1286. $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";
  1287. $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";
  1288. $refKrsToKrsCompany = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company");
  1289. $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";
  1290. $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";
  1291. $refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
  1292. $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";
  1293. $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";
  1294. }
  1295. $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");
  1296. $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";
  1297. foreach ($queries as $query) DB::getPDO()->query($query);
  1298. $BiAuditRelations = new BiAuditRelations($full);
  1299. $query = "select ID from BI_audit_ALL where {$fullWhere} order by ID";
  1300. $result = DB::query($query);
  1301. while ($row = DB::fetch($result)) $BiAuditRelations->findRelations($row->ID);
  1302. }
  1303. public function doReloadCache($full = false) {
  1304. $powiazaniaDirLocation = $this->getMainDirectory();
  1305. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1306. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1307. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1308. file_put_contents($reloadCachePidFile, getmypid());
  1309. try {
  1310. $this->reloadCache_reTeryt($full);
  1311. $this->reloadCache_updateAll($full);
  1312. file_put_contents($reloadCacheResultFile, "ok");
  1313. } catch (Exception $e) {
  1314. file_put_contents($reloadCacheResultFile, $e->getMessage());
  1315. }
  1316. }
  1317. public function doGeneratePowiazania($ID) {
  1318. $powiazaniaDirLocation = $this->getMainDirectory();
  1319. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1320. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  1321. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  1322. $pdfFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pdf";
  1323. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  1324. file_put_contents($pidFile, getmypid());
  1325. $tablesConf = [
  1326. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  1327. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  1328. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  1329. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  1330. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  1331. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  1332. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  1333. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  1334. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  1335. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  1336. ];
  1337. try {
  1338. $BiAuditPowiazania = new BiAuditPowiazania($ID);
  1339. if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  1340. file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  1341. $BiAuditPowiazania->saveToDb();
  1342. $BiAuditPowiazania->generatePdfAndHtml($tasksDirLocation);
  1343. /* $powiazania = $BiAuditPowiazania->asArray('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  1344. if (!$powiazania) return false;
  1345. DB::getPDO()->query($query);
  1346. foreach ($powiazania['BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row'] as $row) {
  1347. $powiazaniaRowSqlArr = [];
  1348. $string_concat_path = [];
  1349. foreach ($row['object'] as $i => $object) {
  1350. $powiazaniaRowObjectSqlArr = [];
  1351. $table = array_keys($object)[0];
  1352. if (!isset($tablesConf[$table])) throw new Exception("Błąd danych konfiguracyjnych");
  1353. $concat = "table='{$table}'";
  1354. if (isset($object['relation_from'])) $concat .= ";relation_from='{$object['relation_from']}'";
  1355. foreach ($tablesConf[$table] as $field) {
  1356. if ($object[$table][$field]) $concat .= ";{$field}='{$object[$table][$field]}'";
  1357. }
  1358. if ($i == 0) $powiazaniaRowSqlArr['string_concat_from'] = $concat;
  1359. elseif ($i == count($row['object']) - 1) $powiazaniaRowSqlArr['string_concat_to'] = $concat;
  1360. else $string_concat_path[] = $concat;
  1361. }
  1362. $powiazaniaRowSqlArr['string_concat_path'] = implode(' / ', $string_concat_path);
  1363. $id_row = DB::getPDO()->insert("BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row", $powiazaniaRowSqlArr);
  1364. if (!$id_row) throw new Exception("Błąd bazy danych");
  1365. DB::getPDO()->insert('CRM__#REF_TABLE__25', ["PRIMARY_KEY" => $ID, "REMOTE_PRIMARY_KEY" => $id_row]);
  1366. }
  1367. */
  1368. file_put_contents($resultFile, "ok");
  1369. } catch (Exception $e) {
  1370. file_put_contents($resultFile, $e->getMessage());
  1371. }
  1372. }
  1373. public function reinstallAction() {
  1374. $this->reinstall();
  1375. die('OK');
  1376. }
  1377. public function reinstall() {
  1378. $sqlList = array();
  1379. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  1380. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  1381. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  1382. SQL;
  1383. $sqlList['ChangeStructure1'] = <<<SQL
  1384. 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';
  1385. SQL;
  1386. $sqlList['ChangeStructure2'] = <<<SQL
  1387. UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
  1388. SQL;
  1389. $sqlList['ChangeStructure3'] = <<<SQL
  1390. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
  1391. SQL;
  1392. $sqlList['ChangeStructure4'] = <<<SQL
  1393. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_depth` `BI_analiza_maxDepth` INT(2) NULL DEFAULT '9';
  1394. SQL;
  1395. $sqlList['ChangeStructure5'] = <<<SQL
  1396. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_minDepth` INT(2) NOT NULL DEFAULT '0' AFTER `FILE_STATUS_info`;
  1397. SQL;
  1398. $sqlList['ChangeStructure6'] = <<<SQL
  1399. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_onlyTargets` ENUM('Y','N') NOT NULL DEFAULT 'Y' AFTER `BI_analiza_maxDepth`;
  1400. SQL;
  1401. $db = DB::getDB();
  1402. if ($db->has_errors()) {
  1403. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  1404. }
  1405. foreach ($sqlList as $sqlName => $sql) {
  1406. $res = $db->query($sql);
  1407. if ($db->has_errors()) {
  1408. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  1409. }
  1410. }
  1411. }
  1412. }
  1413. class BiAuditRelations {
  1414. private $RELATIONS_ID = [];
  1415. private $full;
  1416. private $relations = [
  1417. 'nip' => ['nip'],
  1418. 'regon' => ['regon'],
  1419. 'krs' => ['krs'],
  1420. 'pesel' => ['pesel'],
  1421. 'adres' => ['TERYT_SYM', 'TERYT_SYM_UL', 'nrDomu', 'nrLokalu'],
  1422. ];
  1423. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1424. private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  1425. public function __construct($full = false) {
  1426. $this->full = $full;
  1427. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  1428. $result = DB::getPDO()->fetchAll($query);
  1429. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  1430. }
  1431. private function getRelationID($name) {
  1432. if (!isset($this->RELATIONS_ID[$name])) {
  1433. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  1434. $newID = DB::getPDO()->fetchValue($query);
  1435. $this->RELATIONS_ID[$name] = $newID;
  1436. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  1437. DB::getPDO()->query($query);
  1438. }
  1439. return $this->RELATIONS_ID[$name];
  1440. }
  1441. public function findRelations($ID) {
  1442. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  1443. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  1444. $row = $result[0];
  1445. $joins = [];
  1446. $items = '';
  1447. foreach ($this->relations as $name => $columns) {
  1448. $ok = 0;
  1449. $join = [];
  1450. foreach ($columns as $column) {
  1451. $join[] = "t1.{$column} = t2.{$column}";
  1452. if ($row[$column]) $ok++;
  1453. }
  1454. if ($ok / count($columns) > 0.5) {
  1455. $joins[] = "(" . implode(" and ", $join) . ")";
  1456. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  1457. }
  1458. }
  1459. if (!$joins) return false;
  1460. if ($this->full) $where = "where t1.ID = {$ID} and t2.ID > {$ID}";
  1461. else $where = "where t1.ID = {$ID} and (t2.BASE = 1 or t2.ID > {$ID})";
  1462. $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 " .
  1463. "from BI_audit_ALL t1 join BI_audit_ALL t2 on " . implode(" or ", $joins) . " {$where}";
  1464. $result = DB::getPDO()->fetchAll($query);
  1465. foreach ($result as $row) {
  1466. $relationID = 0;
  1467. foreach ($this->relations as $name => $v) {
  1468. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  1469. }
  1470. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  1471. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  1472. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  1473. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  1474. if (!($start2 || $end1)) {
  1475. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
  1476. DB::getPDO()->query($query);
  1477. }
  1478. if (!($start1 || $end2)) {
  1479. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
  1480. DB::getPDO()->query($query);
  1481. }
  1482. }
  1483. }
  1484. }
  1485. class BiAuditPowiazania {
  1486. private $minDepth;
  1487. private $maxDepth;
  1488. private $onlyTargets;
  1489. private $ID;
  1490. private $endNodes;
  1491. private $path = [];
  1492. private $results = [];
  1493. private $items_results = [];
  1494. private $relations = [];
  1495. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1496. public function __construct($ID = 0) {
  1497. if (!$ID) throw new Exception("Wrong ID parameter");
  1498. $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')";
  1499. $result = DB::getPDO()->fetchAll($query);
  1500. if (!$result) throw new Exception("Błąd danych");
  1501. $this->minDepth = (int) $result[0]['BI_analiza_minDepth'];
  1502. $this->maxDepth = (int) $result[0]['BI_analiza_maxDepth'];
  1503. $this->onlyTargets = ($result[0]['BI_analiza_onlyTargets'] != 'N');
  1504. if (!$this->minDepth) $this->minDepth = 1;
  1505. if (!$this->maxDepth) throw new Exception("Błąd danych - nieokreślono maksymalnej głębokości analizy");
  1506. 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");
  1507. $this->ID = $ID;
  1508. $subQueries = [];
  1509. foreach ($this->destTables as $destTable) {
  1510. $refTable = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "default_db__x3A__{$destTable}:{$destTable}");
  1511. $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}'";
  1512. }
  1513. $query = implode(" union ", $subQueries);
  1514. $result = DB::getPDO()->fetchAll($query);
  1515. if (!$result) throw new Exception("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  1516. $this->endNodes = array_map('reset', $result);
  1517. $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  1518. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
  1519. $query = "select `all`.ID as ID from BI_audit_ALL `all` join `{$refPowiazaniaToPracownicy}` ref
  1520. on `all`.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and `all`.REMOTE_ID = ref.REMOTE_PRIMARY_KEY and ref.PRIMARY_KEY = '{$ID}'";
  1521. $result = DB::getPDO()->fetchAll($query);
  1522. foreach ($result as $row) $this->findPowiazania($row['ID']);
  1523. }
  1524. public function findPowiazania($ID, $relation = "", $end = 0) {
  1525. if (isset($this->path[$ID])) return false;
  1526. $this->path[$ID] = $relation;
  1527. if (!$relation) $relation = 0;
  1528. if ($end) {
  1529. if (in_array($ID, $this->endNodes) && count($this->path) > $this->minDepth) $this->results[] = $this->path;
  1530. array_pop($this->path);
  1531. return true;
  1532. }
  1533. if (count($this->path) > $this->maxDepth) {
  1534. if (!$this->onlyTargets) $this->results[] = $this->path;
  1535. array_pop($this->path);
  1536. return false;
  1537. }
  1538. $nodes = [];
  1539. if ($relation) $where = "and ({$relation} & ref.RELATION_ID) != {$relation}";
  1540. else $where = "";
  1541. $query = "select ref.ID2, RELATION_ID, END from BI_audit_ALL_ref ref where ref.ID1 = '{$ID}' {$where}";
  1542. $result = DB::query($query);
  1543. while ($row = DB::fetch($result)) $nodes[$row->ID2] = ['relation' => (int) $row->RELATION_ID, 'end' => $row->END];
  1544. foreach ($nodes as $node => $data) $this->findPowiazania($node, $data['relation'], $data['end']);
  1545. array_pop($this->path);
  1546. }
  1547. private function relationName($ID) {
  1548. if (!isset($this->relations[$ID])) {
  1549. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  1550. $result = DB::getPDO()->fetchAll($query);
  1551. $rels = array_map('reset', $result);
  1552. $this->relations[$ID] = implode(", ", $rels);
  1553. }
  1554. return $this->relations[$ID];
  1555. }
  1556. private function generateItemsResults() {
  1557. $xmlRoot2 = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  1558. $xmlElements = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  1559. $this->items_results = [];
  1560. $items_kontrahenci = [];
  1561. $items_kw_person = [];
  1562. $kontrahenci = [];
  1563. $kw_person = [];
  1564. $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');
  1565. $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');
  1566. foreach ($this->results as $result) {
  1567. $item_results = [];
  1568. foreach ($result as $ID => $rel) {
  1569. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  1570. $row = DB::getPDO()->fetchFirst($query);
  1571. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  1572. $obj = DB::fetch(DB::query($query));
  1573. $item_result = [$row['REMOTE_TABLE'] => (array) $obj];
  1574. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  1575. $item_results['object'][] = $item_result;
  1576. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  1577. $kontrahenci[] = $row['REMOTE_ID'];
  1578. $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']}'";
  1579. $res = DB::query($query);
  1580. if (mysql_num_rows($res)) {
  1581. $umowy = [];
  1582. while ($obj = DB::fetch($res)) $umowy[] = (array) $obj;
  1583. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  1584. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  1585. $items_kontrahenci[] = $item_kontrahenci;
  1586. }
  1587. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  1588. $kw_person[] = $row['REMOTE_ID'];
  1589. $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']}'";
  1590. $res = DB::query($query);
  1591. if (mysql_num_rows($res)) {
  1592. $kw = [];
  1593. while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
  1594. $item_kw_person['ID'] = $row['REMOTE_ID'];
  1595. $item_kw_person['BI_audit_KW_requested'] = $kw;
  1596. $items_kw_person[] = $item_kw_person;
  1597. }
  1598. }
  1599. }
  1600. $this->items_results[$xmlRoot2][$xmlElements][] = $item_results;
  1601. }
  1602. $this->items_results[$xmlRoot2]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  1603. $this->items_results[$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;
  1604. }
  1605. public function saveToDb() {
  1606. if (!$this->results) return null;
  1607. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  1608. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  1609. $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
  1610. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  1611. foreach ($this->results as $result) {
  1612. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  1613. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  1614. foreach ($result as $ID => $rel) {
  1615. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  1616. $object = DB::getPDO()->fetchFirst($query);
  1617. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relations[$rel]]);
  1618. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  1619. $ref = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
  1620. "default_db__x3A__{$object['REMOTE_TABLE']}:{$object['REMOTE_TABLE']}");
  1621. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  1622. }
  1623. }
  1624. }
  1625. public function asXml() {
  1626. if (!$this->results) return null;
  1627. if (!$this->items_results) $this->generateItemsResults();
  1628. $xmlRoot = "RelatedFeatureRoot";
  1629. return V::arrayToXML($this->items_results, true, $xmlRoot);
  1630. }
  1631. public function asArray($subArray = null) {
  1632. if (!$this->results) return null;
  1633. if (!$this->items_results) $this->generateItemsResults();
  1634. if ($subArray) {
  1635. if (isset($this->items_results[$subArray])) return $this->items_results[$subArray];
  1636. else return [];
  1637. } else return $this->items_results;
  1638. }
  1639. public function powiazaniaFound() {
  1640. if ($this->results) return true;
  1641. else return false;
  1642. }
  1643. public function generatePdfAndHtml($tasksDirLocation) {
  1644. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
  1645. $pdfDestFile = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.pdf";
  1646. $htmlDestDir = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.html";
  1647. $htmlZipDestFile = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.zip";
  1648. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  1649. $antXmlFilename = "relations-{$this->ID}.out_task.dita.final_with_RelatedFeatureLoop.xml";
  1650. $antXmlFile = $antDir . "/" . $antXmlFilename;
  1651. $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";
  1652. $htmlDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$this->ID}/html";
  1653. if (!file_exists($antDir)) mkdir($antDir, 0755, true);
  1654. if (!is_dir($antDir)) $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć pliku PDF";
  1655. else {
  1656. copy($xmlFile, $antXmlFile);
  1657. 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}");
  1658. 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");
  1659. if (file_exists($pdfFile)) rename($pdfFile, $pdfDestFile);
  1660. 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");
  1661. if (file_exists($htmlDir) && is_dir($htmlDir)) {
  1662. 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");
  1663. if (file_exists($htmlDestDir)) shell_exec("rm -rf \"{$htmlDestDir}\"");
  1664. shell_exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
  1665. }
  1666. }
  1667. }
  1668. }