BiAuditGenerate.php 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402
  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 static 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 static 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 static 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 static function parseNipRegon($string) {
  50. $nip = null; $regon = null;
  51. preg_match('/^(.*[^[:digit:]])?([[:digit:]]{10})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
  52. if (!empty($matches[2])) $nip = trim($matches[2]);
  53. if ($nip && !V::isNip($nip)) $nip = null;
  54. preg_match('/^(.*[^[:digit:]])?([[:digit:]]{9})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
  55. if (!empty($matches[2])) $regon = trim($matches[2]);
  56. if ($regon && !V::isRegon($regon)) $regon = null;
  57. return [$nip, $regon];
  58. }
  59. private function initializePowiazaniaForm() {
  60. ?>
  61. <div class="container" style="margin-top:20px">
  62. <form class="form-horizontal" method="post">
  63. <legend>
  64. Generowanie powiązań :: <?=$this->powiazanie['L_APPOITMENT_INFO']?>
  65. <span class="pull-right"># <?=$this->powiazanie['ID']?></span>
  66. </legend>
  67. <div class="form-group">
  68. <div class="col-sm-12">
  69. <h4>Wybierz pracowników, dla których mają zostać wyszukane powiązania</h4>
  70. <table class="table table-bordered table-hover table-striped" height=5>
  71. <thead>
  72. <tr style="text-align:center; background-color:lightgray">
  73. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  74. <td width=1>ID</td>
  75. <td>Imiona</td>
  76. <td>Nazwisko</td>
  77. <td>Pesel</td>
  78. <td>NIP</td>
  79. <td>Regon</td>
  80. <td>source</td>
  81. </tr>
  82. </thead>
  83. <tbody>
  84. <?php
  85. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
  86. $queryFeatures = $acl->buildQuery(['limit' => 0]);
  87. $pracownicy = $queryFeatures->getItems();
  88. foreach ($pracownicy as $pracownik) {
  89. ?>
  90. <tr>
  91. <td><input type="checkbox" name="prID[]" value="<?=$pracownik['ID']?>" onClick="toggle(this)"/></td>
  92. <td align="right"><?=$pracownik['ID']?></td>
  93. <td><?=$pracownik['imiona']?></td>
  94. <td><?=$pracownik['nazwisko']?></td>
  95. <td><?=$pracownik['pesel']?></td>
  96. <td><?=$pracownik['nip']?></td>
  97. <td><?=$pracownik['regon']?></td>
  98. <td><?=$pracownik['source']?></td>
  99. </tr>
  100. <?php
  101. }
  102. ?>
  103. </tbody>
  104. </table>
  105. </div>
  106. </div>
  107. <div class="form-group">
  108. <label class="col-sm-2 control-label">
  109. Odśwież cache
  110. </label>
  111. <div class="col-sm-2">
  112. <select name="reloadCache" class="form-control">
  113. <option value="No" selected>Nie</option>
  114. <!-- <option value="Part">Częściowe</option>-->
  115. <option value="Full">Pełne</option>
  116. </select>
  117. </div>
  118. </div>
  119. <div class="form-group">
  120. <div class="col-sm-offset-2 col-sm-10">
  121. <!-- Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>-->
  122. Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów.<br/>
  123. Uwaga! Jeżeli aktywne są inne zadania, te zadanie zostanie wstrzymane do momentu ich ukończenia.
  124. </div>
  125. </div>
  126. <div class="form-group">
  127. <div class="col-sm-12">
  128. <div class="containter" style="text-align:center">
  129. <button type="submit" class="btn btn-primary" name="action" value="initialize">Generuj</button>
  130. <a href="<?=$this->REFERER?>" class="btn btn-default">Anuluj</a>
  131. </div>
  132. </div>
  133. </div>
  134. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  135. </form>
  136. </div>
  137. <script language="JavaScript">
  138. <!--
  139. function toggleAll(source) {
  140. checkboxes = document.getElementsByName('prID[]');
  141. for(var i=0, n=checkboxes.length;i<n;i++) checkboxes[i].checked = source.checked;
  142. }
  143. function toggle(source) {
  144. checkboxes = document.getElementsByName('prID[]');
  145. all = true;
  146. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked == false) all = false;
  147. source.form['checkAll'].checked = all;
  148. }
  149. -->
  150. </script>
  151. <?php
  152. }
  153. private function initializePowiazaniaSave() {
  154. $prID = V::get('prID', array(), $_POST);
  155. if (!$prID) throw new Exception("Nie wybrano żadnego pracownika!");
  156. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
  157. $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
  158. $kontrahenci = $queryFeatures->getItems();
  159. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_KW_requested_person/BI_audit_KW_requested_person');
  160. $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
  161. $requestedPersons = $queryFeatures->getItems();
  162. if (!($kontrahenci || $requestedPersons)) throw new Exception("Nie znaleziono żadnego obiektu końcowego");
  163. $sqlUpdate = ['FILE_STATUS' => 'TO_GENERATE'];
  164. $reloadCache = V::get('reloadCache', 'No', $_POST);
  165. $reloadCacheAvailable = ['Full', 'Part', 'No'];
  166. if (!in_array($reloadCache, $reloadCacheAvailable)) throw new Exception("Błąd formularza!");
  167. $sqlUpdate['BI_analiza_reloadCache'] = $reloadCache;
  168. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part')";
  169. $result = DB::getPDO()->fetchValue($query);
  170. if ($result) $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache (wymagane dla innego rekordu)';
  171. elseif ($reloadCache != 'No') $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache';
  172. else $sqlUpdate['FILE_STATUS_info'] = "Oczekuje na wygenerowanie powiązań";
  173. if ($this->powiazanie) { // wyzwolone z poziomu tabeli BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA - aktualizujemy istniejący rekord
  174. $powiazanieID = $this->powiazanie['ID'];
  175. } else { // wyzwolone z poziomu tabeli BI_audit_ENERGA_PRACOWNICY - dodajemy nowy rekord
  176. if (count($prID) != 1) throw new Exception("Błąd formularza!");
  177. if (!($lAppoitmentInfo = V::get('info', false, $_POST))) throw new Exception("Błąd formularza!");
  178. if (!($BiAnalizaMinDepth = V::get('minDepth', false, $_POST))) throw new Exception("Błąd formularza!");
  179. if (!($BiAnalizaMaxDepth = V::get('maxDepth', false, $_POST))) throw new Exception("Błąd formularza!");
  180. if (!($BiAnalizaOnlyTargets = V::get('onlyTargets', false, $_POST))) throw new Exception("Błąd formularza!");
  181. $query = "select * from BI_audit_ENERGA_PRACOWNICY where ID='{$prID[0]}'";
  182. $result = DB::getPDO()->fetchFirst($query);
  183. if (!$result) throw new Exception("Błąd formularza!");
  184. $sqlInsert = [
  185. 'L_APPOITMENT_INFO' => $lAppoitmentInfo,
  186. 'A_STATUS' => 'NORMAL',
  187. 'A_STATUS_INFO' => 'Dodane przez BiAuditGenerate z poziomu tabeli BI_audit_ENERGA_PRACOWNICY',
  188. 'A_ADM_COMPANY' => $result['A_ADM_COMPANY'],
  189. 'A_CLASSIFIED' => $result['A_CLASSIFIED'],
  190. 'FILE_STATUS' => 'NONE',
  191. 'FILE_STATUS_info' => 'Oczekuję na zdefiniowanie danych wejściowych',
  192. 'BI_analiza_reloadCache' => $sqlUpdate['BI_analiza_reloadCache'],
  193. 'BI_analiza_minDepth' => $BiAnalizaMinDepth,
  194. 'BI_analiza_maxDepth' => $BiAnalizaMaxDepth,
  195. 'BI_analiza_onlyTargets' => $BiAnalizaOnlyTargets,
  196. ];
  197. $powiazanieID = DB::getDB()->ADD_NEW_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', (object)$sqlInsert);
  198. if ($powiazanieID) SE_Layout::alert('success','Dodano rekord do wygenerowania powiązań');
  199. else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  200. }
  201. $sqlUpdate['ID'] = $powiazanieID;
  202. self::truncatePowiazaniaFromDB($powiazanieID);
  203. $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  204. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
  205. foreach ($prID as $v) DB::getPDO()->insert($refPowiazaniaToPracownicy, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $v]);
  206. $refPowiazaniaToKontrahenci = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  207. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI');
  208. foreach ($kontrahenci as $kontrahent) DB::getPDO()->insert($refPowiazaniaToKontrahenci, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $kontrahent['ID']]);
  209. $refPowiazaniaToKwRequestedPreson = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  210. 'default_db__x3A__BI_audit_KW_requested_person:BI_audit_KW_requested_person');
  211. foreach ($requestedPersons as $requestedPerson) DB::getPDO()->insert($refPowiazaniaToKwRequestedPreson, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $requestedPerson['ID']]);
  212. $affected = DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlUpdate);
  213. if ($affected) {
  214. if ($this->powiazanie) {
  215. SE_Layout::alert('success','Oznaczono rekord do wygenerowania powiązań');
  216. ?>
  217. <div class="container" style="text-align:center">
  218. <a href="<?=$this->REFERER?>" class="btn btn-primary">Powrót</a>
  219. </div>
  220. <?php
  221. }
  222. } else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  223. }
  224. private function initializePowiazania() {
  225. switch (V::get('action', '', $_POST)) {
  226. case "initialize":
  227. $this->initializePowiazaniaSave();
  228. break;
  229. default:
  230. $this->initializePowiazaniaForm();
  231. }
  232. }
  233. private function showPowiazania() {
  234. // echo "Statystyki znalezionych powiązań [TODO]";
  235. $dir = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  236. $pdfFile = "{$dir}/relations.pdf";
  237. $htmlFile = "{$dir}/html/relations-{$this->powiazanie['ID']}.html";
  238. $htmlZipFile = "{$dir}/html.zip";
  239. $url = self::getUrl('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  240. $pdfUrl = "{$url}/relations.pdf";
  241. $htmlUrl = "{$url}/html/relations-{$this->powiazanie['ID']}.html";
  242. $htmlZipUrl = "{$url}/html.zip";
  243. ?>
  244. <div class="container" style="margin-top:20px">
  245. <legend>
  246. Wygenerowany raport nr <?=$this->powiazanie['ID']?>
  247. </legend>
  248. <div class="form-group">
  249. <div class="col-sm-12">
  250. <?php
  251. if (file_exists($pdfFile)) {
  252. ?>
  253. <a href="<?=$pdfUrl?>" target="_blank" class="btn btn-primary">Pokaż raport PDF</a>
  254. <?php
  255. }
  256. if (file_exists($htmlFile)) {
  257. ?>
  258. <a href="<?=$htmlUrl?>" target="_blank" class="btn btn-primary">Pokaż raport HTML</a>
  259. <?php
  260. }
  261. if (file_exists($htmlZipFile)) {
  262. ?>
  263. <a href="<?=$htmlZipUrl?>" target="_blank" download="Raport <?=$this->powiazanie['ID']?>.zip" class="btn btn-primary">Pobierz raport HTML</a>
  264. <?php
  265. }
  266. ?>
  267. <br/><br/><a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  268. </div>
  269. </div>
  270. </div>
  271. <?php
  272. }
  273. private function showPowiazaniaList() {
  274. switch (V::get('action', '', $_POST)) {
  275. case "initialize":
  276. $this->initializePowiazaniaSave();
  277. break;
  278. }
  279. $this->showPowiazaniaListForm();
  280. }
  281. private function showPowiazaniaListForm() {
  282. if (!$this->SOURCE['ID']) throw new Exception("Błąd danych");
  283. elseif ($this->SOURCE['TABLE'] != 'BI_audit_ENERGA_PRACOWNICY') throw new Exception("Błąd danych");
  284. $query = "select * from `{$this->SOURCE['TABLE']}` where ID = '{$this->SOURCE['ID']}'";
  285. $pracownik = DB::getPDO()->fetchFirst($query);
  286. if (!$pracownik) throw new Exception("Błąd danych");
  287. ?>
  288. <div class="container" style="margin-top:20px">
  289. <legend>
  290. Lista wygenerowanych powiązań :: <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>
  291. <span class="pull-right"># <?=$pracownik['ID']?></span>
  292. </legend>
  293. <div class="form-group">
  294. <div class="col-sm-12">
  295. <h4>Lista wygenerowanych powiązań, w których znajduje się pracownik</h4>
  296. <table class="table table-bordered table-hover table-striped" height=5>
  297. <thead>
  298. <tr style="text-align:center; background-color:lightgray">
  299. <td width=1>ID</td>
  300. <td>Adnotacje</td>
  301. <td>Minimalna głębokość analizy</td>
  302. <td>Maksymalna głębokość analizy</td>
  303. <td>Powiązania tylko do celów</td>
  304. <td>Status raportu</td>
  305. <td>Status raportu - informacje</td>
  306. <td>Indywidualny raport</td>
  307. <td width=1></td>
  308. </tr>
  309. </thead>
  310. <tbody>
  311. <?php
  312. $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  313. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
  314. $query = "select `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.*
  315. from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  316. join `{$refPowiazaniaToPracownicy}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPracownicy}`.`PRIMARY_KEY`
  317. where `REMOTE_PRIMARY_KEY` = '{$this->SOURCE['ID']}'";
  318. $result = DB::getPDO()->fetchAll($query);
  319. if (!$result) echo '<tr><td align="center" colspan="9">Brak znalezionych powiązań</td></tr>';
  320. else {
  321. foreach ($result as $row) {
  322. $query = "select count(*) from `{$refPowiazaniaToPracownicy}` where `PRIMARY_KEY` = '{$row['ID']}'";
  323. $count = DB::getPDO()->fetchValue($query);
  324. ?>
  325. <tr>
  326. <td align="right"><?=$row['ID']?></td>
  327. <td><?=$row['L_APPOITMENT_INFO']?></td>
  328. <td><?=$row['BI_analiza_minDepth']?></td>
  329. <td><?=$row['BI_analiza_maxDepth']?></td>
  330. <td><?=($row['BI_analiza_onlyTargets'] == 'N' ? "Nie" : "Tak")?></td>
  331. <td><?=$row['FILE_STATUS']?></td>
  332. <td><?=$row['FILE_STATUS_info']?></td>
  333. <td><?=($count > 1 ? 'Nie' : 'Tak')?></td>
  334. <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>
  335. </tr>
  336. <?php
  337. }
  338. }
  339. ?>
  340. </tbody>
  341. </table>
  342. </div>
  343. </div>
  344. <div class="form-group">
  345. <div class="col-sm-12">
  346. <h4>Dodaj nowe zadanie generowania powiazań dla tego pracownika</h4>
  347. </div>
  348. </div>
  349. <form class="form-horizontal" method="post">
  350. <div class="form-group">
  351. <label class="col-sm-4 control-label">Minimalna głębokość poszukiwań (liczba rekurencji)</label>
  352. <div class="col-sm-1">
  353. <input type="number" class="form-control" name="minDepth" id="minDepth" data-bind="value:replyNumber" min="1" max="9" value="1" required/>
  354. </div>
  355. </div>
  356. <div class="form-group">
  357. <label class="col-sm-4 control-label">Maksymalna głębokość poszukiwań (liczba rekurencji)</label>
  358. <div class="col-sm-1">
  359. <input type="number" class="form-control" name="maxDepth" id="maxDepth" data-bind="value:replyNumber" min="1" max="9" value="6" required/>
  360. </div>
  361. </div>
  362. <div class="form-group">
  363. <label class="col-sm-4 control-label">Czy zwracać tylko wyniki ze znalezionymi obiektami docelowymi (z tabeli kontrahentów)?</label>
  364. <div class="col-sm-1">
  365. <select name="onlyTargets" class="form-control">
  366. <option value="Y" selected>Tak</option>
  367. <option value="N">Nie</option>
  368. </select>
  369. </div>
  370. </div>
  371. <div class="form-group">
  372. <label class="col-sm-4 control-label">Adnotacje</label>
  373. <div class="col-sm-4">
  374. <input type="text" class="form-control" name="info" value="Indywidualnie dla <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>" required/>
  375. </div>
  376. </div>
  377. <div class="form-group">
  378. <label class="col-sm-4 control-label">
  379. Odśwież cache
  380. </label>
  381. <div class="col-sm-2">
  382. <select name="reloadCache" class="form-control">
  383. <option value="No" selected>Nie</option>
  384. <!-- <option value="Part">Częściowe</option>-->
  385. <option value="Full">Pełne</option>
  386. </select>
  387. </div>
  388. </div>
  389. <div class="form-group">
  390. <div class="col-sm-offset-4 col-sm-8">
  391. <!-- Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>-->
  392. Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów.<br/>
  393. Uwaga! Jeżeli aktywne są inne zadania, te zadanie zostanie wstrzymane do momentu ich ukończenia.
  394. </div>
  395. </div>
  396. <div class="form-group">
  397. <div class="col-sm-12">
  398. <div class="containter" style="text-align:center">
  399. <button type="submit" class="btn btn-primary" name="action" value="initialize" onClick="return validate()">Generuj</button>
  400. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  401. </div>
  402. </div>
  403. </div>
  404. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  405. <input type="hidden" name="prID[]" value="<?=$pracownik['ID']?>">
  406. </form>
  407. </div>
  408. <script language="JavaScript">
  409. <!--
  410. function validate() {
  411. result = (document.getElementById('minDepth').value <= document.getElementById('maxDepth').value);
  412. if (!result) alert('Wartość minimalnej głębokości analizy nie może być większa od wartości maksymalnej głębokości analizy!');
  413. return result;
  414. }
  415. -->
  416. </script>
  417. <?php
  418. }
  419. private function powiazania() {
  420. try {
  421. if (!$this->SOURCE) throw new Exception("Błąd danych");
  422. elseif (!(isset($this->SOURCE['TABLE']) && isset($this->SOURCE['ID']))) throw new Exception("Błąd danych");
  423. switch ($this->SOURCE['TABLE']) {
  424. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  425. $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->SOURCE['ID']}'");
  426. if (!$powiazania) throw new Exception("Błąd danych");
  427. $this->powiazanie = $powiazania[0];
  428. switch ($this->powiazanie['FILE_STATUS']) {
  429. case "NONE":
  430. $this->initializePowiazania();
  431. break;
  432. case "GENERATED":
  433. $this->showPowiazania();
  434. break;
  435. default: throw new Exception("Błędny status rekordu");
  436. }
  437. break;
  438. case "BI_audit_ENERGA_PRACOWNICY":
  439. $this->showPowiazaniaList();
  440. break;
  441. case "BI_audit_KRS":
  442. $this->importKrsToPracownicySearch($this->SOURCE['ID']);
  443. break;
  444. case "BI_audit_KRS_person":
  445. $this->showKrsForKrsPerson();
  446. break;
  447. default: throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate");
  448. }
  449. } catch (Exception $e) {
  450. SE_Layout::alert('danger',$e->getMessage());
  451. $_SESSION['REFERER'] = $this->REFERER;
  452. ?>
  453. <div class="container" style="text-align:center">
  454. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
  455. </div>
  456. <?php
  457. }
  458. }
  459. private function importKrsToPracownicy() {
  460. $action = V::get('action', '', $_POST);
  461. switch ($action) {
  462. case "search":
  463. $this->importKrsToPracownicySearch();
  464. break;
  465. default: $this->importKrsToPracownicyForm();
  466. }
  467. }
  468. private function importKrsToPracownicyForm() {
  469. ?>
  470. <div class="container" style="margin-top:20px">
  471. <legend>
  472. Importowanie podmiotów z KRS do tabel kontrahentów i pracowników
  473. </legend>
  474. <div class="form-group">
  475. <div class="col-sm-12">
  476. <h4>Znajdź podmiot</h4>
  477. </div>
  478. </div>
  479. <form class="form-horizontal" method="post">
  480. <div class="form-group">
  481. <label class="col-sm-1 control-label">Nazwa</label>
  482. <div class="col-sm-4">
  483. <input type="text" class="form-control" name="nazwa" title="Podaj nazwę podmiotu">
  484. </div>
  485. </div>
  486. <div class="form-group">
  487. <label class="col-sm-1 control-label">KRS</label>
  488. <div class="col-sm-2">
  489. <input type="text" class="form-control" name="krs" pattern="^[0-9]{0,10}$" title="Podaj KRS"/>
  490. </div>
  491. </div>
  492. <div class="form-group">
  493. <label class="col-sm-1 control-label">NIP</label>
  494. <div class="col-sm-2">
  495. <input type="text" class="form-control" name="nip" pattern="^[0-9]{0,10}$" title="Podaj NIP (bez kresek i bez oznaczenia kraju)"/>
  496. </div>
  497. </div>
  498. <div class="form-group">
  499. <label class="col-sm-1 control-label">Regon</label>
  500. <div class="col-sm-2">
  501. <input type="text" class="form-control" name="regon" pattern="^[0-9]{0,9}$" title="Podaj regon"/>
  502. </div>
  503. </div>
  504. <div class="form-group">
  505. <div class="col-sm-offset-1 col-sm-11">
  506. <button type="submit" class="btn btn-primary" name="action" value="search">Szukaj</button>
  507. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  508. </div>
  509. </div>
  510. </form>
  511. </div>
  512. <?php
  513. }
  514. private function importKrsToPracownicySearch($krsId = null) {
  515. $formItems = [
  516. "nazwa" => 'like',
  517. "krs" => '=',
  518. "nip" => '=',
  519. "regon" => '=',
  520. ];
  521. try {
  522. $subaction = V::get('subaction', '', $_POST);
  523. switch ($subaction) {
  524. case "listKrsPerson":
  525. $krsId = V::get('krsId', 0, $_POST, int);
  526. break;
  527. case "addKrsPersonToPracownicy":
  528. $krsId = V::get('krsId', 0, $_POST, int);
  529. $personId = V::get('personId', [], $_POST);
  530. if (!$personId) throw new Exception("Błąd formularza");
  531. $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) . ")";
  532. DB::getPDO()->query($query);
  533. SE_Layout::alert('success', "Pomyślnie zaimportowano " . count($personId) . " pracownik" . ((count($personId) == 1) ? "a" : "ów"));
  534. break;
  535. case "addKrsToKontrahenci":
  536. $krsId = V::get('krsId', 0, $_POST, int);
  537. if (!$krsId) throw new Exception("Błąd formularza");
  538. $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}'";
  539. $kontrahentExists = DB::getPDO()->fetchValue($query);
  540. if ($kontrahentExists) throw new Exception("Podmiot znajduje się już w tabeli kontrahentów");
  541. $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." ";
  542. DB::getPDO()->query($query);
  543. SE_Layout::alert('success', "Pomyślnie zaimportowano kontrahenta");
  544. break;
  545. }
  546. if ($krsId) {
  547. $where = ["ID = '{$krsId}'"];
  548. } else {
  549. $form = [];
  550. foreach ($formItems as $item => $type) {
  551. if ($param = V::get($item, '', $_POST)) {
  552. if ($type == 'like') $param = "%{$param}%";
  553. $form[$item] = DB::getPDO()->quote($param);
  554. }
  555. }
  556. if (!$form) throw new Exception("Nie wypełniono żadnego pola wyszukiwania!");
  557. $where = [];
  558. foreach ($form as $name => $value) $where[] = "`{$name}` {$formItems[$name]} {$value}";
  559. }
  560. } catch (Exception $e) {
  561. SE_Layout::alert('danger', $e->getMessage());
  562. $this->importKrsToPracownicyForm();
  563. return;
  564. }
  565. $query = "select * from `BI_audit_KRS` where " . implode(" and ", $where) . "order by ID limit 1001";
  566. $result = DB::getPDO()->fetchAll($query);
  567. if (count($result) == 1001) {
  568. SE_Layout::alert('danger', 'Znaleziono zbyt wiele wyników. Doprecyzuj parametry wyszukiwania.');
  569. $this->importKrsToPracownicyForm();
  570. return;
  571. } elseif (count($result) == 1) {
  572. $krsId = $result[0]['ID'];
  573. }
  574. ?>
  575. <div class="container" style="margin-top:20px">
  576. <form method="post">
  577. <legend>
  578. Importowanie podmiotów z KRS do tabel kontrahentów i pracowników
  579. </legend>
  580. <div class="form-group">
  581. <div class="col-sm-12">
  582. <h4>Znalezione podmioty:</h4>
  583. </div>
  584. </div>
  585. <div class="form-group">
  586. <div class="col-sm-12">
  587. <table class="table table-bordered table-hover table-striped" height=5>
  588. <thead>
  589. <tr style="text-align:center; background-color:lightgray">
  590. <td width=1>Lp.</td>
  591. <td>Nazwa</td>
  592. <td>Adres</td>
  593. <td>KRS</td>
  594. <td>NIP</td>
  595. <td>Regon</td>
  596. <?php
  597. if (count($result) > 1) {
  598. ?>
  599. <td width=1>Wybierz</td>
  600. <?php
  601. }
  602. ?>
  603. </tr>
  604. </thead>
  605. <tbody>
  606. <?php
  607. if (!$result) echo '<tr><td align="center" colspan="6">Nie znaleziono podmiotu</td></tr>';
  608. else {
  609. $lp = 1;
  610. foreach ($result as $row) {
  611. $adres = $row['A_miejscowosc'];
  612. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  613. if ($row['A_nrDomu']) {
  614. $adres .= " {$row['A_nrDomu']}";
  615. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  616. }
  617. ?>
  618. <tr>
  619. <td align="right"><?=$lp++?></td>
  620. <td><?=htmlspecialchars($row['nazwa'])?></td>
  621. <td><?=htmlspecialchars($adres)?></td>
  622. <td><?=$row['krs']?></td>
  623. <td><?=$row['nip']?></td>
  624. <td><?=$row['regon']?></td>
  625. <?php
  626. if (count($result) > 1) {
  627. ?>
  628. <td align="center">
  629. <input type="radio" name="krsId" value="<?=$row['ID']?>"/>
  630. </td>
  631. <?php
  632. }
  633. ?>
  634. </tr>
  635. <?php
  636. }
  637. }
  638. ?>
  639. </tbody>
  640. </table>
  641. </div>
  642. </div>
  643. <?php
  644. if (count($result) > 1) {
  645. ?>
  646. <div class="form-group">
  647. <div class="col-sm-12">
  648. <?php
  649. foreach (array_keys($formItems) as $item) {
  650. ?>
  651. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  652. <?php
  653. }
  654. ?>
  655. <input type="hidden" name="back" value="search"/>
  656. <div class="containter" style="text-align:center">
  657. <button type="submit" class="btn btn-primary" name="subaction" value="listKrsPerson" onClick="return validateCompany(this)">Wybierz zaznaczony podmiot</button>
  658. <a href="" class="btn btn-default">Powrót</a>
  659. </div>
  660. </div>
  661. </div>
  662. <?php
  663. } elseif ($krsId) {
  664. ?>
  665. <div class="form-group">
  666. <div class="col-sm-12">
  667. <h4>Znalezione osoby:</h4>
  668. </div>
  669. </div>
  670. <div class="form-group">
  671. <div class="col-sm-12">
  672. <table class="table table-bordered table-hover table-striped" height=5>
  673. <thead>
  674. <tr style="text-align:center; background-color:lightgray">
  675. <td width=1>Lp.</td>
  676. <td>Nazwisko</td>
  677. <td>Imiona</td>
  678. <td>Pesel</td>
  679. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  680. </tr>
  681. </thead>
  682. <tbody>
  683. <?php
  684. $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}'";
  685. $kontrahentExists = DB::getPDO()->fetchValue($query);
  686. $refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
  687. $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}'";
  688. $result = DB::getPDO()->fetchAll($query);
  689. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono osób powiązanych z podmiotem</td></tr>';
  690. else {
  691. $lp = 1;
  692. foreach ($result as $row) {
  693. ?>
  694. <tr<?=($row['pracownicyId'] ? ' style="color:darkgrey"' : '')?>>
  695. <td align="right"><?=$lp++?></td>
  696. <td><?=$row['nazwisko']?></td>
  697. <td><?=$row['imiona']?></td>
  698. <td><?=$row['pesel']?></td>
  699. <td><input type="checkbox" name="personId[]" value="<?=$row['ID']?>" onClick="toggle(this)" <?=($row['pracownicyId'] ? "disabled" : "")?>/></td>
  700. </tr>
  701. <?php
  702. }
  703. }
  704. ?>
  705. </tbody>
  706. </table>
  707. </div>
  708. </div>
  709. <!-- <div class="form-group">
  710. <div class="col-sm-12">
  711. <label class="col-sm-4 control-label">Opis/źródło</label>
  712. <div class="col-sm-4">
  713. <input type="text" class="form-control" name="source" placeholder="KRS"/>
  714. </div>
  715. </div>
  716. </div>-->
  717. <div class="form-group">
  718. <div class="col-sm-12" style="text-align: center;">
  719. <button type="submit" class="btn btn-primary" name="subaction" value="addKrsToKontrahenci"<?=($kontrahentExists ? " disabled" : "")?>>Dodaj firmę do tabeli kontrahentów</button>
  720. <button type="submit" class="btn btn-primary" name="subaction" value="addKrsPersonToPracownicy" onClick="return validatePerson(this)">Dodaj zaznaczone osoby do tabeli pracowników</button>
  721. <input type="hidden" name="krsId" value="<?=$krsId?>"/>
  722. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  723. <?php
  724. if (V::get('back', '', $_POST) == 'search') {
  725. foreach (array_keys($formItems) as $item) {
  726. ?>
  727. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  728. <?php
  729. }
  730. ?>
  731. <button type="submit" class="btn btn-default" name="action" value="search">Powrót</button>
  732. <?php
  733. } else {
  734. ?>
  735. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  736. <?php
  737. }
  738. ?>
  739. </div>
  740. </div>
  741. <?php
  742. }
  743. ?>
  744. <input type="hidden" name="action" value="search">
  745. </form>
  746. </div>
  747. <script language="JavaScript">
  748. <!--
  749. function toggleAll(source) {
  750. checkboxes = document.getElementsByName('personId[]');
  751. checked = false;
  752. for(var i=0, n=checkboxes.length;i<n;i++) {
  753. if (!checkboxes[i].disabled) {
  754. checkboxes[i].checked = source.checked;
  755. checked = true;
  756. }
  757. }
  758. if (source.checked && (!checked)) source.checked = false;
  759. }
  760. function toggle(source) {
  761. checkboxes = document.getElementsByName('personId[]');
  762. all = true;
  763. for(var i=0, n=checkboxes.length;i<n;i++) if(!checkboxes[i].disabled && checkboxes[i].checked == false) all = false;
  764. source.form['checkAll'].checked = all;
  765. }
  766. function validatePerson(source) {
  767. checkboxes = document.getElementsByName('personId[]');
  768. checked = false;
  769. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked) checked = true;
  770. if (!checked) alert('Nie wybrano żadnej osoby!');
  771. return checked;
  772. }
  773. function validateCompany(source) {
  774. radios = document.getElementsByName('krsId');
  775. checked = false;
  776. for(var i=0, n=radios.length;i<n;i++) if(radios[i].checked) checked = true;
  777. if (!checked) alert('Nie wybrano żadnej firmy!');
  778. return checked;
  779. }
  780. -->
  781. </script>
  782. <?php
  783. }
  784. private function showKrsForKrsPerson() {
  785. $query = "select * from BI_audit_KRS_person where ID = '{$this->SOURCE['ID']}'";
  786. $result = DB::getPDO()->fetchFirst($query);
  787. ?>
  788. <div class="container" style="margin-top:20px">
  789. <legend>
  790. Lista podmiotów, w których występuje <?="{$result['nazwisko']} {$result['imiona']}" . ($result['pesel'] ? " (PESEL: {$result['pesel']})" : "")?>
  791. </legend>
  792. <div class="form-group">
  793. <div class="col-sm-12">
  794. <table class="table table-bordered table-hover table-striped" height=5>
  795. <thead>
  796. <tr style="text-align:center; background-color:lightgray">
  797. <td width=1>Lp.</td>
  798. <td>Nazwa</td>
  799. <td>Adres</td>
  800. <td>KRS</td>
  801. <td>NIP</td>
  802. <td>Regon</td>
  803. <td width=1></td>
  804. </tr>
  805. </thead>
  806. <tbody>
  807. <?php
  808. $refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
  809. $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']}'";
  810. $result = DB::getPDO()->fetchAll($query);
  811. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono powiązanych podmiotów</td></tr>';
  812. else {
  813. $lp = 1;
  814. foreach ($result as $row) {
  815. $adres = $row['A_miejscowosc'];
  816. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  817. if ($row['A_nrDomu']) {
  818. $adres .= " {$row['A_nrDomu']}";
  819. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  820. }
  821. ?>
  822. <tr>
  823. <td align="right"><?=$lp++?></td>
  824. <td><?=htmlspecialchars($row['nazwa'])?></td>
  825. <td><?=htmlspecialchars($adres)?></td>
  826. <td><?=$row['krs']?></td>
  827. <td><?=$row['nip']?></td>
  828. <td><?=$row['regon']?></td>
  829. <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>
  830. </tr>
  831. <?php
  832. }
  833. }
  834. ?>
  835. </tbody>
  836. </table>
  837. </div>
  838. </div>
  839. <div class="form-group">
  840. <div class="col-sm-12">
  841. <div class="containter" style="text-align:center">
  842. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-default">Powrót</a>
  843. </div>
  844. </div>
  845. </div>
  846. </div>
  847. <?php
  848. }
  849. public function defaultAction() {
  850. SE_Layout::gora();
  851. SE_Layout::menu();
  852. if (isset($_SESSION['REFERER'])) {
  853. $this->REFERER = $_SESSION['REFERER'];
  854. unset($_SESSION['REFERER']);
  855. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  856. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  857. if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
  858. elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
  859. elseif (($ID = V::get('ID_BI_audit_KRS', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  860. elseif (($ID = V::get('ID_BI_audit_KRS_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS_person';
  861. if ($this->SOURCE) {
  862. $this->SOURCE['ID'] = $ID;
  863. $this->powiazania();
  864. }
  865. elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
  866. switch ($TABLE) {
  867. case "default_db/BI_audit_ENERGA_PRACOWNICY":
  868. $this->importKrsToPracownicy();
  869. break;
  870. default: SE_Layout::alert('danger', 'Błąd parametru');
  871. }
  872. }
  873. else SE_Layout::alert('danger', 'Błąd parametru');
  874. SE_Layout::dol();
  875. }
  876. private static function getRefsTables($namespace) {
  877. try {
  878. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  879. if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
  880. $fields = $item['field'];
  881. $refsTables = [];
  882. foreach ($fields as $field) {
  883. list($type, $child) = explode(":", $field['xsdType'], 2);
  884. if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) $refsTables[] = ACL::getRefTable($namespace, $child);
  885. }
  886. return $refsTables;
  887. } catch (Exception $e) {
  888. // echo "{$namespace} - {$e->getMessage}";
  889. return [];
  890. }
  891. }
  892. private static function truncatePowiazaniaFromDB($ID) {
  893. $refsTables = self::getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  894. if (!$refsTables) return null;
  895. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  896. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  897. $refsTables = array_diff($refsTables, [$refPowiazaniaToPowiazaniaRow]);
  898. $query = "delete from `" . implode("`, `", $refsTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  899. foreach ($refsTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  900. $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  901. DB::getPDO()->query($query);
  902. }
  903. private static function deleteResultsFromDB($ID) {
  904. $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
  905. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  906. $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
  907. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  908. $refsTables = self::getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  909. $sqlDeleteFrom = "delete from
  910. `{$refPowiazaniaToPowiazaniaRow}`,
  911. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
  912. `{$refPowiazaniaRowToPowiazaniaRowObject}`,
  913. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
  914. $sqlUsing = "
  915. using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  916. join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
  917. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
  918. join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
  919. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
  920. $sqlWhere = "
  921. where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  922. foreach ($refsTables as $refTable) {
  923. $sqlDeleteFrom .= ",\n`{$refTable}`";
  924. $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  925. }
  926. $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
  927. DB::getPDO()->query($query);
  928. }
  929. public function doGenerate() {
  930. $generatePhpScript = function($function) {
  931. return '<?php
  932. ini_set("memory_limit", "4G");
  933. define("DS", DIRECTORY_SEPARATOR);
  934. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  935. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  936. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  937. ini_set("display_startup_errors", "0");
  938. ini_set("log_errors", "1");
  939. ini_set("error_log", "/var/log/apache2/error_log");
  940. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  941. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  942. Lib::loadClass("Router");
  943. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  944. ';
  945. };
  946. try {
  947. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  948. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  949. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  950. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  951. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  952. ### Ustawienie zmiennych
  953. $powiazaniaDirLocation = self::getMainDirectory();
  954. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  955. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  956. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  957. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  958. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  959. ### Utworzenie niezbędnych katalogów i plików
  960. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0755, true);
  961. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  962. ### Wyłączenie wcześniej używanego mechanizmu wymuszania częściowego odświeżania cache - teraz działa to z automatu
  963. $sqlArr = [
  964. 'BI_analiza_reloadCache' => 'No',
  965. ];
  966. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Part') and FILE_STATUS = 'TO_GENERATE'";
  967. $result = DB::getPDO()->fetchAll($query);
  968. foreach ($result as $row) {
  969. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  970. }
  971. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  972. $doGenerate = true;
  973. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full') and FILE_STATUS = 'TO_GENERATE'";
  974. $result = DB::getPDO()->fetchAll($query);
  975. if ($result) {
  976. $doGenerate = false;
  977. $sqlArr = [];
  978. if (file_exists($reloadCachePhpFile)) {
  979. if (file_exists($reloadCacheResultFile)) {
  980. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  981. if ($reloadCacheResult == "ok") {
  982. $sqlArr = [
  983. 'FILE_STATUS_info' => 'Ukończono pełne Odświeżenie cache, oczekiwanie na wygenerowanie powiązań',
  984. 'BI_analiza_reloadCache' => 'No',
  985. ];
  986. $doGenerate = true;
  987. } else {
  988. $sqlArr = [
  989. 'FILE_STATUS' => 'ERROR',
  990. 'FILE_STATUS_info' => "Wystąpił błąd podczas pełnego odświeżania cache ({$reloadCacheResult})",
  991. ];
  992. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  993. $result = DB::getPDO()->fetchAll($query);
  994. }
  995. unlink($reloadCachePhpFile);
  996. unlink($reloadCachePidFile);
  997. unlink($reloadCacheResultFile);
  998. } elseif (file_exists($reloadCachePidFile)) {
  999. $pid = file_get_contents($reloadCachePidFile);
  1000. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1001. $processShouldBeRunning = "php {$reloadCachePhpFile}";
  1002. if ($processRunning != $processShouldBeRunning) {
  1003. if (!file_exists($reloadCacheResultFile)) {
  1004. $sqlArr = [
  1005. 'FILE_STATUS' => 'ERROR',
  1006. 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas pełnego odświeżania cache - nie znaleziono procesu potomnego",
  1007. ];
  1008. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  1009. $result = DB::getPDO()->fetchAll($query);
  1010. unlink($reloadCachePhpFile);
  1011. unlink($reloadCachePidFile);
  1012. unlink($reloadCacheResultFile);
  1013. }
  1014. }
  1015. }
  1016. } else {
  1017. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1018. $result2 = DB::getPDO()->fetchValue($query);
  1019. if ($result2) {
  1020. $sqlArr = [
  1021. 'FILE_STATUS_info' => 'Wstrzymano pełne odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  1022. ];
  1023. } else {
  1024. $sqlArr = [
  1025. 'FILE_STATUS_info' => 'W trakcie pełnego odświeżania cache',
  1026. ];
  1027. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
  1028. $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
  1029. file_put_contents($reloadCachePhpFile, $generatePhpScript("doReloadCache({$fullReloadCache})"));
  1030. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  1031. }
  1032. }
  1033. if ($sqlArr) {
  1034. foreach ($result as $row) {
  1035. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  1036. }
  1037. }
  1038. }
  1039. ### Generowanie powiązań
  1040. if ($doGenerate) {
  1041. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
  1042. $result = DB::getPDO()->fetchAll($query);
  1043. foreach ($result as $row) {
  1044. $sqlArr = [
  1045. 'ID' => $row['ID'],
  1046. 'FILE_STATUS' => 'IN_PROGRESS',
  1047. 'FILE_STATUS_info' => 'W trakcie generowania powiązań',
  1048. ];
  1049. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1050. self::deleteResultsFromDB($row['ID']);
  1051. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1052. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1053. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  1054. file_put_contents($generatePowiazaniaPhpFile, $generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  1055. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  1056. }
  1057. }
  1058. ### Weryfikacja świeżo wygenerowanych powiązań
  1059. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1060. $result = DB::getPDO()->fetchAll($query);
  1061. foreach ($result as $row) {
  1062. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1063. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  1064. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1065. $error = false;
  1066. $success = false;
  1067. $sqlArr = [];
  1068. if (file_exists($generatePowiazaniaResultFile)) {
  1069. $generatePowiazaniaResult = json_decode(file_get_contents($generatePowiazaniaResultFile), true);
  1070. if ($generatePowiazaniaResult['result'] == "ok") {
  1071. $powiazanieDirLocation = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  1072. if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0777, false);
  1073. if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
  1074. else $success = true;
  1075. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult['message']})";
  1076. } elseif (file_exists($generatePowiazaniaPidFile)) {
  1077. $pid = file_get_contents($generatePowiazaniaPidFile);
  1078. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1079. $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
  1080. if ($processRunning != $processShouldBeRunning) {
  1081. if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
  1082. }
  1083. }
  1084. if ($error) {
  1085. $sqlArr = [
  1086. 'FILE_STATUS' => 'ERROR',
  1087. 'FILE_STATUS_info' => $error,
  1088. ];
  1089. self::deleteResultsFromDB($row['ID']);
  1090. //if (file_exists($xmlFile)) unlink($xmlFile);
  1091. } elseif ($success) {
  1092. $sqlArr = [
  1093. 'FILE_STATUS' => 'GENERATED',
  1094. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  1095. ];
  1096. if ($generatePowiazaniaResult['parts']) {
  1097. for ($i = 1; $i <= $generatePowiazaniaResult['parts']; $i++) {
  1098. $partNo = str_pad($i, 6, '0', STR_PAD_LEFT);
  1099. $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}_{$partNo}";
  1100. $generatePowiazaniaXmlFile = "{$generateFilesName}.xml";
  1101. $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
  1102. $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
  1103. $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
  1104. $destXmlFile = "{$powiazanieDirLocation}/relations_{$partNo}.xml";
  1105. $destPdfFile = "{$powiazanieDirLocation}/relations_{$partNo}.pdf";
  1106. $destHtmlDir = "{$powiazanieDirLocation}/html_{$partNo}";
  1107. $destHtmlZipFile = "{$powiazanieDirLocation}/html_{$partNo}.zip";
  1108. if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
  1109. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1110. if (file_exists($generatePowiazaniaHtmlDir)) {
  1111. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1112. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1113. }
  1114. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1115. }
  1116. } else {
  1117. $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}";
  1118. $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
  1119. $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
  1120. $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
  1121. $destXmlFile = "{$powiazanieDirLocation}/relations.xml";
  1122. $destPdfFile = "{$powiazanieDirLocation}/relations.pdf";
  1123. $destHtmlDir = "{$powiazanieDirLocation}/html";
  1124. $destHtmlZipFile = "{$powiazanieDirLocation}/html.zip";
  1125. if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
  1126. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1127. if (file_exists($generatePowiazaniaHtmlDir)) {
  1128. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1129. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1130. }
  1131. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1132. }
  1133. }
  1134. if ($sqlArr) {
  1135. $sqlArr['ID'] = $row['ID'];
  1136. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1137. if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
  1138. if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
  1139. if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
  1140. }
  1141. }
  1142. } catch (Exception $e) {
  1143. echo $e->getMessage()."\n";
  1144. }
  1145. }
  1146. private static function reloadCache_parseUmowy($full = false) {
  1147. $fields = [
  1148. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1149. 'Tytul_dokumentu',
  1150. 'Pelna_nazwa_kontrahenta',
  1151. 'NIP',
  1152. 'REGON',
  1153. 'KRS',
  1154. 'Kraj',
  1155. 'Kod_pocztowy',
  1156. 'Miejscowosc',
  1157. 'Ulica',
  1158. 'Numer_budynku',
  1159. 'Numer_mieszkania_lokalu',
  1160. 'TERYT_SYM',
  1161. 'TERYT_SYM_UL',
  1162. ],
  1163. 'BI_audit_KRS' => [
  1164. '"Zaimportowanoz KRS na podstawie umowy"',
  1165. 'nazwa',
  1166. 'nip',
  1167. 'regon',
  1168. 'krs',
  1169. 'A_kraj',
  1170. 'A_kod',
  1171. 'A_miejscowosc',
  1172. 'A_ulica',
  1173. 'A_nrDomu',
  1174. 'A_nrLokalu',
  1175. 'TERYT_SYM',
  1176. 'TERYT_SYM_UL',
  1177. ],
  1178. 'BI_audit_CEIDG' => [
  1179. '"Zaimportowano z CEiDG na podstawie umowy"',
  1180. 'firma',
  1181. 'nip',
  1182. 'regon',
  1183. 'null',
  1184. 'kraj',
  1185. 'kodPocztowy',
  1186. 'miejscowosc',
  1187. 'ulica',
  1188. 'budynek',
  1189. 'lokal',
  1190. 'TERYT_SYM',
  1191. 'TERYT_SYM_UL',
  1192. ],
  1193. ];
  1194. $refTable = 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');
  1195. if ($full) {
  1196. DB::getPDO()->query("truncate table `{$refTable}`");
  1197. DB::getPDO()->query("update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
  1198. }
  1199. $query = <<<SQL
  1200. update `BI_audit_ENERGA_RUM_UMOWY` set `Wartosc` = replace(
  1201. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_`,
  1202. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_`,
  1203. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_`,
  1204. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_`,
  1205. if(`Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_`, 0))))),
  1206. ',', '.') where `A_STATUS` = 'WAITING';
  1207. SQL;
  1208. DB::getPDO()->query($query);
  1209. $query = "select `ID`, `Strony_umowy` from `BI_audit_ENERGA_RUM_UMOWY` where `A_STATUS` = 'WAITING'";
  1210. $result = DB::getPDO()->fetchAll($query);
  1211. foreach ($result as $row) {
  1212. $ID = $row['ID'];
  1213. $strony = array_map('trim', explode("|", $row['Strony_umowy']));
  1214. $K_IDs = [];
  1215. foreach ($strony as $item) {
  1216. $strona = array_map('trim', explode(";", $item));
  1217. $nr = null;
  1218. if (count($strona) == 3) $i = 1;//$nr = $strona[1];
  1219. elseif (count($strona) == 4) $i = 2;//$nr = $strona[2];
  1220. elseif (count($strona) >= 5 && count($strona) <= 6) $i = 3;//$nr = $strona[3];
  1221. else $i = null;
  1222. if ($i) $nr = $strona[$i];
  1223. $notFound = false;
  1224. if (is_numeric($nr)) {
  1225. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Numer_kontrahenta = '{$nr}'";
  1226. if ($K_ID = DB::getPDO()->fetchValue($query)) {
  1227. $K_IDs[] = $K_ID;
  1228. } else {
  1229. $nazwa = $strona[$i+1];
  1230. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Pelna_nazwa_kontrahenta = '" . addslashes($nazwa) . "'";
  1231. if ($result2 = DB::getPDO()->fetchAll($query)) {
  1232. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1233. } else $notFound = true;
  1234. }
  1235. } else $notFound = true;
  1236. if ($notFound) {
  1237. list($nip, $regon) = self::parseNipRegon($item);
  1238. if ($nip || $regon) {
  1239. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where NIP = '{$nip}' or REGON = '{$regon}'";
  1240. if ($result2 = DB::getPDO()->fetchall($query)) {
  1241. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1242. } else {
  1243. $query = "select ID from BI_audit_KRS where nip = '{$nip}' or regon = '{$regon}'";
  1244. if ($result2 = DB::getPDO()->fetchall($query)) {
  1245. foreach ($result2 as $item) {
  1246. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1247. " select " . implode(', ', $fields['BI_audit_KRS']) . " from BI_audit_KRS where ID = '{$item['ID']}'";
  1248. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1249. }
  1250. } else {
  1251. $query = "select ID from BI_audit_CEIDG where nip = '{$nip}' or regon = '{$regon}'";
  1252. if ($result2 = DB::getPDO()->fetchall($query)) {
  1253. foreach ($result2 as $item) {
  1254. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1255. " select " . implode(', ', $fields['BI_audit_CEIDG']) .
  1256. " from BI_audit_CEIDG where ID = '{$item['ID']}'";
  1257. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1258. }
  1259. }
  1260. }
  1261. }
  1262. }
  1263. }
  1264. }
  1265. foreach ($K_IDs as $K_ID) {
  1266. if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
  1267. DB::getPDO()->query("insert into `{$refTable}` (PRIMARY_KEY, REMOTE_PRIMARY_KEY) values ({$ID}, {$K_ID})");
  1268. }
  1269. }
  1270. DB::getPDO()->update('BI_audit_ENERGA_RUM_UMOWY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
  1271. }
  1272. $query = "select ID, NIP, REGON, KRS from BI_audit_ENERGA_RUM_KONTRAHENCI where (NIP is null or REGON is null or KRS is null) and not (NIP is null and REGON is null and KRS is null) and `cached` = 0";
  1273. $result = DB::getPDO()->fetchAll($query);
  1274. foreach ($result as $row) {
  1275. $query = "select nip, regon, krs from BI_audit_KRS where nip = '{$row['NIP']}' or regon = '{$row['REGON']}' or krs = '{$row['KRS']}'";
  1276. if ($items = DB::getPDO()->fetchAll($query)) {
  1277. list($nip, $regon, $krs) = [$items[0]["nip"], $items[0]["regon"], $items[0]["krs"]];
  1278. if (count($items) > 1) {
  1279. for ($i = 1; $i < count($items); $i++) {
  1280. if ($nip != $items[$i]["nip"]) $nip = null;
  1281. if ($regon != $items[$i]["regon"]) $regon = null;
  1282. if ($krs != $items[$i]["krs"]) $krs = null;
  1283. }
  1284. }
  1285. $set = [];
  1286. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  1287. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  1288. if ($krs && $krs != $row['KRS']) $set[] = "KRS = '{$krs}'";
  1289. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row['ID']}'");
  1290. }
  1291. }
  1292. $query = "select ID, NIP, REGON from BI_audit_ENERGA_RUM_KONTRAHENCI where (NIP is null or REGON is null) and not (NIP is null and REGON is null) and `cached` = 0";
  1293. $result = DB::getPDO()->fetchAll($query);
  1294. foreach ($result as $row) {
  1295. $query = "select nip, regon from BI_audit_CEIDG where nip = '{$row['NIP']}' or regon = '{$row['REGON']}'";
  1296. if ($items = DB::getPDO()->fetchAll($query)) {
  1297. list($nip, $regon) = [$items[0]["nip"], $items[0]["regon"]];
  1298. if (count($items) > 1) {
  1299. for ($i = 1; $i < count($items); $i++) {
  1300. if ($nip != $items[$i]["nip"]) $nip = null;
  1301. if ($regon != $items[$i]["regon"]) $regon = null;
  1302. }
  1303. }
  1304. $set = [];
  1305. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  1306. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  1307. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row->ID}'");
  1308. }
  1309. }
  1310. }
  1311. private static function reloadCache_reTeryt($full = false) {
  1312. Lib::loadClass('Teryt');
  1313. $tables = [
  1314. 'BI_audit_CEIDG' => [
  1315. 'fields' => [
  1316. 'wojewodztwo' => 'wojewodztwo',
  1317. 'powiat' => 'powiat',
  1318. 'gmina' => 'gmina',
  1319. 'miejscowosc' => 'miejscowosc',
  1320. 'ulica' => 'ulica',
  1321. 'kodPocztowy' => 'kodPocztowy',
  1322. ],
  1323. 'full' => false,
  1324. ],
  1325. 'BI_audit_CEIDG_pelnomocnicy' => [
  1326. 'fields' => [
  1327. 'wojewodztwo' => 'wojewodztwo',
  1328. 'powiat' => 'powiat',
  1329. 'gmina' => 'gmina',
  1330. 'miejscowosc' => 'miejscowosc',
  1331. 'ulica' => 'ulica',
  1332. 'kodPocztowy' => 'kodPocztowy',
  1333. ],
  1334. 'full' => false,
  1335. ],
  1336. 'BI_audit_ENERGA_PRACOWNICY' => [
  1337. 'fields' => [
  1338. 'miejscowosc' => 'miejscowosc',
  1339. 'kodPocztowy' => 'kodPocztowy',
  1340. 'ulica' => 'ulica',
  1341. ],
  1342. 'full' => true,
  1343. ],
  1344. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1345. 'fields' => [
  1346. 'kodPocztowy' => 'kodPocztowy',
  1347. 'miejscowosc' => 'miejscowosc',
  1348. 'ulica' => 'ulica',
  1349. ],
  1350. 'full' => true,
  1351. ],
  1352. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1353. 'fields' => [
  1354. 'kodPocztowy' => 'Kod_pocztowy',
  1355. 'miejscowosc' => 'Miejscowosc',
  1356. 'ulica' => 'Ulica',
  1357. ],
  1358. 'full' => true,
  1359. ],
  1360. 'BI_audit_KRS' => [
  1361. 'fields' => [
  1362. 'wojewodztwo' => 'S_wojewodztwo',
  1363. 'powiat' => 'S_powiat',
  1364. 'gmina' => 'S_gmina',
  1365. 'miejscowosc' => 'A_miejscowosc',
  1366. 'ulica' => 'A_ulica',
  1367. 'kodPocztowy' => 'A_kod',
  1368. ],
  1369. 'full' => false,
  1370. ],
  1371. 'BI_audit_KRS_address' => [
  1372. 'fields' => [
  1373. 'wojewodztwo' => 'S_wojewodztwo',
  1374. 'powiat' => 'S_powiat',
  1375. 'gmina' => 'S_gmina',
  1376. 'miejscowosc' => 'A_miejscowosc',
  1377. 'ulica' => 'A_ulica',
  1378. 'kodPocztowy' => 'A_kod',
  1379. ],
  1380. 'full' => false,
  1381. ],
  1382. 'BI_audit_MSIG_address' => [
  1383. 'fields' => [
  1384. 'wojewodztwo' => 'S_wojewodztwo',
  1385. 'powiat' => 'S_powiat',
  1386. 'gmina' => 'S_gmina',
  1387. 'miejscowosc' => 'A_miejscowosc',
  1388. 'ulica' => 'A_ulica',
  1389. 'kodPocztowy' => 'A_kod',
  1390. ],
  1391. 'full' => false,
  1392. ],
  1393. ];
  1394. foreach ($tables as $table => $tableConf) {
  1395. $where = ($full && $tableConf['full']) ? "" : "where `TERYT_SYM` is null and `cached` = 0";
  1396. $query = "select * from `{$table}` {$where}";
  1397. try {
  1398. $adresy = DB::getPDO()->query($query);
  1399. while ($adres = $adresy->fetch()) {
  1400. $search = [];
  1401. foreach ($tableConf['fields'] as $field => $param) if (!empty($adres[$param])) $search[$field] = $adres[$param];
  1402. try {
  1403. $teryt = Teryt::search($search);
  1404. if (!empty($teryt['SYM'])) {
  1405. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  1406. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  1407. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  1408. }
  1409. } catch (Exception $e) {
  1410. }
  1411. }
  1412. } catch (Exception $e) {
  1413. }
  1414. }
  1415. }
  1416. private static function reloadCache_updateAll($full, $onlyBase) {
  1417. $tablesConf = [
  1418. 'BI_audit_CEIDG' => [
  1419. 'fields' => [
  1420. 'nip' => 'nip',
  1421. 'regon' => 'regon',
  1422. 'TERYT_SYM' => 'TERYT_SYM',
  1423. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1424. 'nrDomu' => 'budynek',
  1425. 'nrLokalu' => 'lokal',
  1426. ],
  1427. 'base' => '1',
  1428. ],
  1429. 'BI_audit_CEIDG_pelnomocnicy' => [
  1430. 'fields' => [
  1431. 'nip' => 'nip',
  1432. 'TERYT_SYM' => 'TERYT_SYM',
  1433. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1434. 'nrDomu' => 'budynek',
  1435. 'nrLokalu' => 'lokal',
  1436. ],
  1437. 'base' => '1',
  1438. ],
  1439. 'BI_audit_CEIDG_powiazania' => [
  1440. 'fields' => [
  1441. 'nip' => 'nip',
  1442. 'regon' => 'regon',
  1443. ],
  1444. 'base' => '1',
  1445. ],
  1446. 'BI_audit_ENERGA_PRACOWNICY' => [
  1447. 'fields' => [
  1448. 'nip' => 'nip',
  1449. 'regon' => 'regon',
  1450. 'pesel' => 'pesel',
  1451. 'TERYT_SYM' => 'TERYT_SYM',
  1452. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1453. 'nrDomu' => 'nr',
  1454. 'nrLokalu' => 'nrLokalu',
  1455. ],
  1456. 'base' => '0',
  1457. //'where' => '',
  1458. ],
  1459. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1460. 'fields' => [
  1461. 'TERYT_SYM' => 'TERYT_SYM',
  1462. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1463. 'nrDomu' => 'nrBudynku',
  1464. 'nrLokalu' => 'nrLokalu',
  1465. ],
  1466. 'base' => '0',
  1467. //'where' => '',
  1468. ],
  1469. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1470. 'fields' => [
  1471. 'krs' => 'KRS',
  1472. 'nip' => 'NIP',
  1473. 'regon' => 'REGON',
  1474. 'pesel' => 'PESEL',
  1475. 'TERYT_SYM' => 'TERYT_SYM',
  1476. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1477. 'nrDomu' => 'Numer_budynku',
  1478. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  1479. ],
  1480. 'base' => '0',
  1481. 'where' => "and ownCompany != 'Y'",
  1482. ],
  1483. 'BI_audit_KRS' => [
  1484. 'fields' => [
  1485. 'krs' => 'krs',
  1486. 'nip' => 'nip',
  1487. 'regon' => 'regon',
  1488. 'TERYT_SYM' => 'TERYT_SYM',
  1489. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1490. 'nrDomu' => 'A_nrDomu',
  1491. 'nrLokalu' => 'A_nrLokalu',
  1492. ],
  1493. 'base' => '1',
  1494. ],
  1495. 'BI_audit_KRS_address' => [
  1496. 'fields' => [
  1497. 'TERYT_SYM' => 'TERYT_SYM',
  1498. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1499. 'nrDomu' => 'A_nrDomu',
  1500. 'nrLokalu' => 'A_nrLokalu',
  1501. ],
  1502. 'base' => '1',
  1503. ],
  1504. 'BI_audit_KRS_company' => [
  1505. 'fields' => [
  1506. 'regon' => 'regon',
  1507. 'krs' => 'krs',
  1508. ],
  1509. 'base' => '1',
  1510. ],
  1511. 'BI_audit_KRS_person' => [
  1512. 'fields' => [
  1513. 'pesel' => 'pesel',
  1514. ],
  1515. 'base' => '1',
  1516. ],
  1517. 'BI_audit_MSIG' => [
  1518. 'fields' => [
  1519. 'krs' => 'krs',
  1520. 'nip' => 'nip',
  1521. 'regon' => 'regon',
  1522. ],
  1523. 'base' => '1',
  1524. ],
  1525. 'BI_audit_MSIG_address' => [
  1526. 'fields' => [
  1527. 'TERYT_SYM' => 'TERYT_SYM',
  1528. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1529. 'nrDomu' => 'A_nrDomu',
  1530. 'nrLokalu' => 'A_nrLokalu',
  1531. ],
  1532. 'base' => '1',
  1533. ],
  1534. 'BI_audit_MSIG_company' => [
  1535. 'fields' => [
  1536. 'regon' => 'regon',
  1537. 'krs' => 'krs',
  1538. ],
  1539. 'base' => '1',
  1540. ],
  1541. 'BI_audit_MSIG_person' => [
  1542. 'fields' => [
  1543. 'pesel' => 'pesel',
  1544. ],
  1545. 'base' => '1',
  1546. ],
  1547. // 'BI_audit_KW_requested_person' => [
  1548. // 'fields' => [
  1549. // 'pesel' => 'Seller_person_pesel',
  1550. // 'krs' => 'Seller_person_KRS',
  1551. // 'nip' => 'Seller_person_NIP',
  1552. // 'regon' => 'Seller_person_REGON',
  1553. // ],
  1554. // 'base' => '0',
  1555. // //'where' => '',
  1556. // ],
  1557. ];
  1558. $refTablesConf = [
  1559. 'BI_audit_CEIDG' => [
  1560. 'refTablesTo' => [
  1561. 'BI_audit_CEIDG_pelnomocnicy',
  1562. 'BI_audit_CEIDG_powiazania',
  1563. ],
  1564. 'base' => 1,
  1565. ],
  1566. 'BI_audit_ENERGA_PRACOWNICY' => [
  1567. 'refTablesTo' => [
  1568. 'BI_audit_ENERGA_PRACOWNICY_adresy',
  1569. ],
  1570. 'base' => 0,
  1571. ],
  1572. 'BI_audit_KRS' => [
  1573. 'refTablesTo' => [
  1574. 'BI_audit_KRS_address',
  1575. 'BI_audit_KRS_company',
  1576. 'BI_audit_KRS_person',
  1577. ],
  1578. 'base' => 1,
  1579. ],
  1580. 'BI_audit_MSIG' => [
  1581. 'refTablesTo' => [
  1582. 'BI_audit_MSIG_address',
  1583. 'BI_audit_MSIG_company',
  1584. 'BI_audit_MSIG_person',
  1585. ],
  1586. 'base' => 1,
  1587. ],
  1588. ];
  1589. $sourceTables = ['BI_audit_ENERGA_PRACOWNICY'];
  1590. if ($full) {
  1591. foreach ($tablesConf as $table => $tableConf) if (!$tableConf['base']) $queries[] = "update `{$table}` set `cached` = 0";
  1592. $queries[] = "delete from BI_audit_ALL where BASE = 0";
  1593. $queries[] = "delete from BI_audit_ALL_ref where BASE = 0";
  1594. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  1595. if ($refTableConf['base']) continue;
  1596. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  1597. $refTable = ACL::getRefTable("default_db/{$refTableFrom}/{$refTableFrom}", "default_db__x3A__{$refTableTo}:{$refTableTo}");
  1598. $queries[] = "update `{$refTable}` set `A_STATUS` = 'WAITNG' where `A_STATUS` = 'NORMAL'";
  1599. }
  1600. }
  1601. }
  1602. foreach ($tablesConf as $table => $tableConf) {
  1603. if ($onlyBase && (!$tableConf['base'])) continue;
  1604. $where = "where `cached` = 0";
  1605. if (!empty($tableConf['where'])) $where .= " {$tableConf['where']}";
  1606. // $queries[] = "lock tables `{$table}` write";
  1607. $queries[] = "insert into `BI_audit_ALL` (`REMOTE_TABLE`, `REMOTE_ID`, `BASE`, " . implode(", ", array_keys($tableConf['fields'])) .
  1608. ") select '{$table}', ID, '{$tableConf['base']}', " . implode(", ", $tableConf['fields']) . " from `{$table}` {$where}";
  1609. $queries[] = "update `{$table}` set `cached` = 1 {$where}";
  1610. // $queries[] = "unlock tables";
  1611. }
  1612. $queries[] = "update `BI_audit_ALL` set `nip` = null where `nip` = 0";
  1613. $queries[] = "update `BI_audit_ALL` set `regon` = null where `regon` = 0";
  1614. $queries[] = "update `BI_audit_ALL` set `krs` = null where `krs` = 0";
  1615. $queries[] = "update `BI_audit_ALL` set `pesel` = null where `pesel` = 0";
  1616. $queries[] = "update `BI_audit_ALL` set `TERYT_SYM` = null where `TERYT_SYM` = 0";
  1617. $queries[] = "update `BI_audit_ALL` set `TERYT_SYM_UL` = null where `TERYT_SYM_UL` = 0";
  1618. $queries[] = "update `BI_audit_ALL` set `nrDomu` = null where trim(`nrDomu`) = ''";
  1619. $queries[] = "update `BI_audit_ALL` set `nrLokalu` = null where trim(`nrLokalu`) = ''";
  1620. $queries[] = "update `BI_audit_ALL` set `nrDomu` = substring(`nrDomu`, 1, position('/' in `nrDomu`) - 1), `nrLokalu` = substring(`nrDomu`, position('/' in `nrDomu`) + 1) where `reffed` = 0 and `nrDomu` rlike '^[[:digit:]]+.*/[[:digit:]]+.*$' and `nrLokalu` is null";
  1621. $queries[] = "set @var = (select round(coalesce(max(`ID`), '0.5'), 1) from `BI_audit_ALL_ref_RELATIONS`)";
  1622. $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";
  1623. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  1624. if ($onlyBase && (!$tableConf['base'])) continue;
  1625. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  1626. $refTable = ACL::getRefTable("default_db/{$refTableFrom}/{$refTableFrom}", "default_db__x3A__{$refTableTo}:{$refTableTo}");
  1627. // $queries[] = "lock tables `{$refTable}` write";
  1628. $queries[] = "insert into `BI_audit_ALL_ref` (`ID1`, `ID2`, `RELATION_ID`, `BASE`) select `all1`.`ID`, `all2`.`ID`, `rel`.`ID`, {$refTableConf['base']} from `BI_audit_ALL` as `all1` join `{$refTable}` as `ref` on `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all1`.`REMOTE_ID` = `ref`.`PRIMARY_KEY` and `ref`.`A_STATUS` = 'WAITING' join `BI_audit_ALL` as `all2` on `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref`.`REMOTE_PRIMARY_KEY` = `all2`.`REMOTE_ID` join `BI_audit_ALL_ref_RELATIONS` `rel` on `all1`.`REMOTE_TABLE` = `rel`.`RELATION`";
  1629. if (!in_array($refTableFrom, $sourceTables)) $queries[] = "insert into `BI_audit_ALL_ref` (`ID1`, `ID2`, `RELATION_ID`, `BASE`) select `all2`.`ID`, `all1`.`ID`, `rel`.`ID`, {$refTableConf['base']} from `BI_audit_ALL` as `all1` join `{$refTable}` as `ref` on `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all1`.`REMOTE_ID` = `ref`.`PRIMARY_KEY` and `ref`.`A_STATUS` = 'WAITING' join `BI_audit_ALL` as `all2` on `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref`.`REMOTE_PRIMARY_KEY` = `all2`.`REMOTE_ID` join `BI_audit_ALL_ref_RELATIONS` `rel` on `all2`.`REMOTE_TABLE` = `rel`.`RELATION`";
  1630. $queries[] = "update `BI_audit_ALL` as `all1` join `{$refTable}` as `ref` on `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all1`.`REMOTE_ID` = `ref`.`PRIMARY_KEY` and `ref`.`A_STATUS` = 'WAITING' join `BI_audit_ALL` as `all2` on `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref`.`REMOTE_PRIMARY_KEY` = `all2`.`REMOTE_ID` set `ref`.`A_STATUS` = 'NORMAL'";
  1631. // $queries[] = "unlock tables";
  1632. }
  1633. }
  1634. // echo implode(";\n", $queries) . ";\n";
  1635. foreach ($queries as $query) {
  1636. // echo "SQL: {$query}\n";
  1637. DB::getPDO()->query($query);
  1638. }
  1639. $BiAuditRelations = new BiAuditRelations();
  1640. // DB::getPDO()->query("lock tables `BI_audit_ALL` write");
  1641. $result = DB::getPDO()->query("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
  1642. while ($row = $result->fetch()) $BiAuditRelations->findRelations($row['ID']);
  1643. DB::getPDO()->query("update `BI_audit_ALL` set `reffed` = 1");
  1644. // DB::getPDO()->query("unlock tables");
  1645. }
  1646. public static function doReloadCache($full = false) {
  1647. if ($full === 'base') {
  1648. $onlyBase = true;
  1649. $full = false;
  1650. } else {
  1651. $onlyBase = false;
  1652. }
  1653. $powiazaniaDirLocation = self::getMainDirectory();
  1654. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1655. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1656. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1657. file_put_contents($reloadCachePidFile, getmypid());
  1658. try {
  1659. self::reloadCache_reTeryt($full);
  1660. self::reloadCache_parseUmowy($full);
  1661. self::reloadCache_updateAll($full, $onlyBase);
  1662. file_put_contents($reloadCacheResultFile, "ok");
  1663. } catch (Exception $e) {
  1664. var_dump($e);
  1665. file_put_contents($reloadCacheResultFile, $e->getMessage());
  1666. }
  1667. }
  1668. public static function doGeneratePowiazania($ID) {
  1669. $powiazaniaDirLocation = self::getMainDirectory();
  1670. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1671. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  1672. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  1673. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  1674. file_put_contents($pidFile, getmypid());
  1675. $tablesConf = [
  1676. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  1677. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  1678. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  1679. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  1680. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  1681. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  1682. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  1683. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  1684. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  1685. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  1686. ];
  1687. try {
  1688. $query = "select count(*) from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` where `FILE_STATUS` = 'IN_PROGRESS' and `BI_analiza_reloadCache` = 'Part' and ID != ${ID}";
  1689. $sqlArr = [
  1690. 'ID' => $ID,
  1691. 'BI_analiza_reloadCache' => 'Part',
  1692. 'FILE_STATUS_info' => 'Odświeżam częściowo cache',
  1693. ];
  1694. do {
  1695. DB::getPDO()->query("lock tables `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` write");
  1696. $activeReloadingCache = DB::getPDO()->fetchValue($query);
  1697. if (!$activeReloadingCache) DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1698. DB::getPDO()->query("unlock tables");
  1699. if ($activeReloadingCache) {
  1700. BiAuditPowiazania::saveToLog("Czekam na zakończenie częściowego odświeżania cache przez inne zadanie");
  1701. sleep(30);
  1702. }
  1703. } while ($activeReloadingCache);
  1704. BiAuditPowiazania::saveToLog("Uruchamiam częściowe odświeżenie cache");
  1705. self::doReloadCache();
  1706. BiAuditPowiazania::saveToLog("Odświeżono częściowo cache");
  1707. $sqlArr['BI_analiza_reloadCache'] = 'No';
  1708. $sqlArr['FILE_STATUS_info'] = 'Zakończono odświeżanie cache i wyzwolono funkcję szukania powiązań';
  1709. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1710. $BiAuditPowiazania = new BiAuditPowiazania($ID, $tasksDirLocation);
  1711. if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  1712. //file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  1713. $BiAuditPowiazania->saveXml();
  1714. $BiAuditPowiazania->generatePdfAndHtml();
  1715. file_put_contents($resultFile, json_encode(['result' => 'ok', 'parts' => $BiAuditPowiazania->getPartsCount()]));
  1716. } catch (Exception $e) {
  1717. file_put_contents($resultFile, json_encode(['result' => 'error', 'message' => $e->getMessage()]));
  1718. }
  1719. }
  1720. public function reinstallAction() {
  1721. $this->reinstall();
  1722. die('OK');
  1723. }
  1724. public function reinstall() {
  1725. $sqlList = array();
  1726. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  1727. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  1728. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  1729. SQL;
  1730. $sqlList['ChangeStructure1'] = <<<SQL
  1731. 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';
  1732. SQL;
  1733. $sqlList['ChangeStructure2'] = <<<SQL
  1734. UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
  1735. SQL;
  1736. $sqlList['ChangeStructure3'] = <<<SQL
  1737. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
  1738. SQL;
  1739. $sqlList['ChangeStructure4'] = <<<SQL
  1740. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_depth` `BI_analiza_maxDepth` INT(2) NULL DEFAULT '9';
  1741. SQL;
  1742. $sqlList['ChangeStructure5'] = <<<SQL
  1743. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_minDepth` INT(2) NOT NULL DEFAULT '0' AFTER `FILE_STATUS_info`;
  1744. SQL;
  1745. $sqlList['ChangeStructure6'] = <<<SQL
  1746. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_onlyTargets` ENUM('Y','N') NOT NULL DEFAULT 'Y' AFTER `BI_analiza_maxDepth`;
  1747. SQL;
  1748. $db = DB::getDB();
  1749. if ($db->has_errors()) {
  1750. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  1751. }
  1752. foreach ($sqlList as $sqlName => $sql) {
  1753. $res = $db->query($sql);
  1754. if ($db->has_errors()) {
  1755. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  1756. }
  1757. }
  1758. }
  1759. }
  1760. class BiAuditRelations {
  1761. private $RELATIONS_ID = [];
  1762. private $relations = [
  1763. 'nip' => ['nip'],
  1764. 'regon' => ['regon'],
  1765. 'krs' => ['krs'],
  1766. 'pesel' => ['pesel'],
  1767. 'adres' => ['TERYT_SYM', 'TERYT_SYM_UL', 'nrDomu', 'nrLokalu'],
  1768. ];
  1769. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1770. private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  1771. public function __construct() {
  1772. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  1773. $result = DB::getPDO()->fetchAll($query);
  1774. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  1775. }
  1776. private function getRelationID($name) {
  1777. if (!isset($this->RELATIONS_ID[$name])) {
  1778. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  1779. $newID = DB::getPDO()->fetchValue($query);
  1780. $this->RELATIONS_ID[$name] = $newID;
  1781. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  1782. DB::getPDO()->query($query);
  1783. }
  1784. return $this->RELATIONS_ID[$name];
  1785. }
  1786. public function findRelations($ID) {
  1787. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  1788. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  1789. $row = $result[0];
  1790. $joins = [];
  1791. $items = '';
  1792. foreach ($this->relations as $name => $columns) {
  1793. $ok = 0;
  1794. $join = [];
  1795. foreach ($columns as $column) {
  1796. $join[] = "t1.{$column} = t2.{$column}";
  1797. if ($row[$column]) $ok++;
  1798. }
  1799. if ($ok / count($columns) > 0.5) {
  1800. $joins[] = "(" . implode(" and ", $join) . ")";
  1801. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  1802. }
  1803. }
  1804. if (!$joins) return false;
  1805. $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 " .
  1806. "from BI_audit_ALL t1 join BI_audit_ALL t2 on " . implode(" or ", $joins) . " where t1.ID = {$ID} and (t2.reffed = 1 or t2.ID > {$ID})";
  1807. $result = DB::getPDO()->fetchAll($query);
  1808. foreach ($result as $row) {
  1809. $relationID = 0;
  1810. foreach ($this->relations as $name => $v) {
  1811. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  1812. }
  1813. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  1814. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  1815. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  1816. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  1817. if (!($start2 || $end1)) {
  1818. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
  1819. DB::getPDO()->query($query);
  1820. }
  1821. if (!($start1 || $end2)) {
  1822. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
  1823. DB::getPDO()->query($query);
  1824. }
  1825. }
  1826. }
  1827. }
  1828. class BiAuditPowiazania {
  1829. private $minDepth;
  1830. private $maxDepth, $origMaxDepth;
  1831. private $onlyTargets;
  1832. private $ID;
  1833. private $nodes = [];
  1834. private $endNodes;
  1835. private $path = [];
  1836. private $results = [];
  1837. private $items_results = [];
  1838. private $relations = [];
  1839. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1840. private $refTables = [];
  1841. private $step = 0;
  1842. private $tasksDirLocation;
  1843. private $progressFile;
  1844. private $lastProgress = 0;
  1845. private $startTimestamp = null;
  1846. private $lowProgressCount = 0;
  1847. private $count, $i;
  1848. private $splittedResults = [];
  1849. private function getRefTable($tableFrom, $tableTo, $returnException = true) {
  1850. if (!isset($this->refTables[$tableFrom][$tableTo])) {
  1851. try {
  1852. $this->refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
  1853. } catch (Exception $e) {
  1854. if ($returnException) throw new Exception($e->getMessage());
  1855. $this->refTables[$tableFrom][$tableTo] = false;
  1856. }
  1857. }
  1858. return $this->refTables[$tableFrom][$tableTo];
  1859. }
  1860. private static function generateJson($type, $data) {
  1861. return json_encode(['ts' => microtime(true), 'type' => $type, 'data' => $data]);
  1862. }
  1863. public static function saveToLog($message) {
  1864. $messageJson = self::generateJson('message', ['message' => $message]);
  1865. echo $messageJson . "\n";
  1866. }
  1867. private function saveProgress($progress) {
  1868. $this->lastProgress = $progress;
  1869. $timestamp = microtime(true);
  1870. if ($progress) $estimated = ($timestamp - $this->startTimestamp) / $progress;
  1871. else $estimated = "N/A";
  1872. $progressJson = self::generateJson('progress', ['progress' => $progress, 'item' => ($this->i + 1) . "/" . $this->count, 'results' => count($this->results), 'step' => $this->step, 'estimated' => $estimated]);
  1873. echo $progressJson . "\n";
  1874. file_put_contents($this->progressFile, $progressJson);
  1875. }
  1876. private static function throwException($message) {
  1877. self::saveToLog($message);
  1878. throw new Exception($message);
  1879. }
  1880. public function __construct($ID = 0, $tasksDirLocation = null) {
  1881. if (!$ID) self::throwException("Wrong ID parameter");
  1882. if (!$tasksDirLocation) self::throwException("Wrong directory of tasks location");
  1883. $this->tasksDirLocation = $tasksDirLocation;
  1884. $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')";
  1885. $result = DB::getPDO()->fetchAll($query);
  1886. if (!$result) self::throwException("Błąd danych");
  1887. $this->ID = $ID;
  1888. if ($this->loadResults()) {
  1889. $this->splitResults();
  1890. return;
  1891. }
  1892. self::saveToLog("Wczytuję parametry wyszukiwania powiązań");
  1893. $this->minDepth = (int) $result[0]['BI_analiza_minDepth'];
  1894. $this->maxDepth = (int) $result[0]['BI_analiza_maxDepth'];
  1895. $this->onlyTargets = ($result[0]['BI_analiza_onlyTargets'] != 'N');
  1896. if (!$this->minDepth) $this->minDepth = 1;
  1897. if (!$this->maxDepth) self::throwException("Błąd danych - nieokreślono maksymalnej głębokości analizy");
  1898. if ($this->minDepth > $this->maxDepth) self::throwException("Wartość minimalnej głębokości analizy jest większa od wartości maksymalnej głębokości analizy");
  1899. $subQueries = [];
  1900. foreach ($this->destTables as $destTable) {
  1901. $refTable = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $destTable);
  1902. $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 = '{$this->ID}'";
  1903. }
  1904. $query = implode(" union ", $subQueries);
  1905. $result = DB::getPDO()->fetchAll($query);
  1906. if (!$result) self::throwException("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  1907. $this->endNodes = array_map('reset', $result);
  1908. self::saveToLog("Rozpoczynam wyszukiwanie powiązań");
  1909. $this->progressFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.progress";
  1910. $refPowiazaniaToPracownicy = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY');
  1911. $query = "select `all`.ID as ID from BI_audit_ALL `all` join `{$refPowiazaniaToPracownicy}` ref
  1912. on `all`.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and `all`.REMOTE_ID = ref.REMOTE_PRIMARY_KEY and ref.PRIMARY_KEY = '{$this->ID}' order by `all`.`ID` asc";
  1913. $result = DB::getPDO()->fetchAll($query);
  1914. $this->count = count($result);
  1915. $this->saveProgress(0);
  1916. $this->origMaxDepth = $this->maxDepth;
  1917. foreach ($result as $this->i => $row) {
  1918. if ($this->maxDepth != $this->origMaxDepth) {
  1919. $this->maxDepth = $this->origMaxDepth;
  1920. self::saveToLog("Przywrócono oryginalną maksymalną głębokość przeszukiwania ({$this->origMaxDepth})");
  1921. }
  1922. $this->findPowiazania($row['ID']);
  1923. $this->saveProgress(1);
  1924. }
  1925. $this->nodes = [];
  1926. self::saveToLog("Zakończono wyszukiwanie powiązań");
  1927. $this->saveResults();
  1928. $this->saveToDb();
  1929. $this->splitResults();
  1930. }
  1931. public function findPowiazania($ID, $progress = 0, $steps = 1, $relation = "", $end = 0) {
  1932. if (!$progress) {
  1933. $this->startTimestamp = microtime(true);
  1934. $this->lastProgress = 0;
  1935. }
  1936. if (((++$this->step) % 1000000) == 0) {
  1937. $progressDiff = $progress - $this->lastProgress;
  1938. // self::saveToLog("TEST: " . (number_format($progress - $this->lastProgress, 20)));
  1939. if ($progressDiff < 0.00005) {
  1940. $this->lowProgressCount++;
  1941. if ($this->lowProgressCount == 10) {
  1942. $this->maxDepth--;
  1943. self::saveToLog("Zbyt dużo rekurencji, zmniejszono maksymalną głębokość poszukiwań do {$this->maxDepth} dla bieżącego pracownika");
  1944. }
  1945. } else $this->lowProgressCount = 0;
  1946. $this->saveProgress($progress);
  1947. if (memory_get_usage(true) > 4000000000) {
  1948. $this->nodes = [];
  1949. self::saveToLog("Too much memory used, cleaning relations cache");
  1950. }
  1951. }
  1952. if (isset($this->path[$ID])) return false;
  1953. $this->path[$ID] = $relation;
  1954. if (!$relation) $relation = 0;
  1955. if ($end) {
  1956. if (in_array($ID, $this->endNodes) && count($this->path) > $this->minDepth) $this->results[] = $this->path;
  1957. array_pop($this->path);
  1958. return;
  1959. }
  1960. if (count($this->path) > $this->maxDepth) {
  1961. if (!$this->onlyTargets) $this->results[] = $this->path;
  1962. array_pop($this->path);
  1963. return;
  1964. }
  1965. if (!isset($this->nodes[$ID][$relation])) {
  1966. if ($relation) $where = "and ({$relation} & ref.RELATION_ID) != {$relation}";
  1967. $query = "select ref.ID2, RELATION_ID, END from BI_audit_ALL_ref ref where ref.ID1 = {$ID} {$where}";
  1968. $this->nodes[$ID][$relation] = DB::getPDO()->fetchAll($query);
  1969. }
  1970. $nodes = array_values(array_filter($this->nodes[$ID][$relation], function ($node) {
  1971. if (isset($this->path[$node['ID2']])) return false;
  1972. return true;
  1973. }));
  1974. $count = count($nodes);
  1975. foreach ($nodes as $i => $node) $this->findPowiazania($node['ID2'], ($progress + ($i / ($count * $steps))), ($count * $steps), $node['RELATION_ID'], $node['END']);
  1976. array_pop($this->path);
  1977. }
  1978. private function saveResults() {
  1979. self::saveToLog("Zapisuję wyliczone dane do pliku");
  1980. if (!$this->results) {
  1981. self::saveToLog("Brak wyliczonych danych - niczego nie zapisaono");
  1982. return false;
  1983. }
  1984. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  1985. $data = base64_encode(gzcompress(json_encode($this->results)));
  1986. file_put_contents($dataFile, $data);
  1987. self::saveToLog("Zapisano wyliczone dane do pliku");
  1988. return true;
  1989. }
  1990. private function loadResults() {
  1991. self::saveToLog("Próbuję wczytać wcześniej wyliczone dane");
  1992. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  1993. if (!file_exists($dataFile)) {
  1994. self::saveToLog("Nie znaleziono pliku z wyliczonymi danymi");
  1995. return false;
  1996. }
  1997. $data = file_get_contents($dataFile);
  1998. $results = @json_decode(gzuncompress(base64_decode($data)), true);
  1999. if (!$results) {
  2000. self::saveToLog("Wystąpił błąd wczytywania wcześniej wyliczonych danych");
  2001. return false;
  2002. }
  2003. $this->results = $results;
  2004. self::saveToLog("Wczytano wcześniej wyliczone dane");
  2005. return true;
  2006. }
  2007. private function relationName($ID) {
  2008. if (!isset($this->relations[$ID])) {
  2009. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  2010. $result = DB::getPDO()->fetchAll($query);
  2011. $rels = array_map('reset', $result);
  2012. $this->relations[$ID] = implode(", ", $rels);
  2013. }
  2014. return $this->relations[$ID];
  2015. }
  2016. private function splitResults() {
  2017. $MAX = 1000;
  2018. $countBySource = [];
  2019. $resultsKeys = [];
  2020. foreach ($this->results as $resultKey => $result) $countBySource[reset(array_keys($result))][] = $resultKey;
  2021. foreach ($countBySource as $resultKeys) {
  2022. if (count($resultKeys) > $MAX) {
  2023. $countByDest = [];
  2024. foreach ($resultKeys as $resultKey) $countByDest[end(array_keys($this->results[$resultKey]))][] = $resultKey;
  2025. foreach ($countByDest as $resultKeys2) {
  2026. while (count($resultKeys2) > $MAX) $resultsKeys[] = array_splice($resultKeys2, 0, $MAX);
  2027. $resultsKeys[] = $resultKeys2;
  2028. }
  2029. } else $resultsKeys[] = $resultKeys;
  2030. }
  2031. $results = [];
  2032. while ($resultsKeys) {
  2033. $resultKeys = array_shift($resultsKeys);
  2034. while ($next = current($resultsKeys)) {
  2035. if (count($resultKeys) + count($next) <= $MAX) {
  2036. $resultKeys = array_merge($resultKeys, $next);
  2037. unset($resultsKeys[key($resultsKeys)]);
  2038. } else next($resultsKeys);
  2039. }
  2040. $results[] = array_map(function ($resultKey) {return $this->results[$resultKey];}, $resultKeys);
  2041. }
  2042. $this->splittedResults = $results;
  2043. }
  2044. public function getPartsCount() {
  2045. return count($this->splittedResults);
  2046. }
  2047. private function generateItemsResults($resultsPart = null) {
  2048. self::saveToLog("Generuję dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  2049. $xmlRoot2 = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  2050. $xmlElements = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  2051. $this->items_results = [];
  2052. $items_kontrahenci = [];
  2053. $items_kw_person = [];
  2054. $kontrahenci = [];
  2055. $kw_person = [];
  2056. $_items_results = [];
  2057. $refUmowyToKontrahenci = $this->getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI');
  2058. $refKwRequestedToKwRequestedPerson = $this->getRefTable('BI_audit_KW_requested', 'BI_audit_KW_requested_person');
  2059. if ($resultsPart === null) $results = $this->results;
  2060. else $results = (!empty($this->splittedResults[$resultsPart])) ? $this->splittedResults[$resultsPart] : [];
  2061. foreach ($results as $result) {
  2062. $item_results = [];
  2063. foreach ($result as $ID => $rel) {
  2064. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  2065. $row = DB::getPDO()->fetchFirst($query);
  2066. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  2067. $obj = DB::fetch(DB::query($query));
  2068. $item_result = [$row['REMOTE_TABLE'] => (array) $obj];
  2069. if ($refTable = $this->getRefTable('BI_audit_operational_raport_note', $row['REMOTE_TABLE'], false)) {
  2070. $query = "select `note`.* from `BI_audit_operational_raport_note` `note` join `{$refTable}` `ref` on `note`.`ID` = `ref`.`PRIMARY_KEY` where `ref`.`REMOTE_PRIMARY_KEY` = '{$row['REMOTE_ID']}'";
  2071. if ($notes = DB::getPDO()->fetchAll($query)) $item_result[$row['REMOTE_TABLE']]['BI_audit_operational_raport_note'] = $notes;
  2072. }
  2073. if ($refTable = $this->getRefTable($row['REMOTE_TABLE'], 'BI_audit_taxpayer', false)) {
  2074. $query = "select `taxpayer`.* from `{$refTable}` `ref` join `BI_audit_taxpayer` `taxpayer` on `ref`.`REMOTE_PRIMARY_KEY` = `taxpayer`.`ID` where `ref`.`PRIMARY_KEY` = '{$row['REMOTE_ID']}'";
  2075. if ($taxpayer = DB::getPDO()->fetchFirst($query)) $item_result[$row['REMOTE_TABLE']]['BI_audit_taxpayer'] = $taxpayer;
  2076. }
  2077. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  2078. $item_results['object'][] = $item_result;
  2079. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  2080. $kontrahenci[] = $row['REMOTE_ID'];
  2081. $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']}'";
  2082. $res = DB::query($query);
  2083. if (mysql_num_rows($res)) {
  2084. $umowy = [];
  2085. while ($obj = DB::fetch($res)) $umowy[] = (array) $obj;
  2086. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  2087. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  2088. $items_kontrahenci[] = $item_kontrahenci;
  2089. }
  2090. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  2091. $kw_person[] = $row['REMOTE_ID'];
  2092. $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']}'";
  2093. $res = DB::query($query);
  2094. if (mysql_num_rows($res)) {
  2095. $kw = [];
  2096. while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
  2097. $item_kw_person['ID'] = $row['REMOTE_ID'];
  2098. $item_kw_person['BI_audit_KW_requested'] = $kw;
  2099. $items_kw_person[] = $item_kw_person;
  2100. }
  2101. }
  2102. }
  2103. $this->items_results[$resultsPart][$xmlRoot2][$xmlElements][] = $item_results;
  2104. }
  2105. $this->items_results[$resultsPart][$xmlRoot2]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  2106. $this->items_results[$resultsPart][$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;
  2107. self::saveToLog("Wygenerowano dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  2108. }
  2109. private function saveToDb() {
  2110. self::saveToLog("Zapisuję wyliczone dane do bazy");
  2111. if (!$this->results) {
  2112. self::saveToLog("Brak wyliczonych danych - nie zapisaono niczego do bazy");
  2113. return null;
  2114. }
  2115. $refPowiazaniaToPowiazaniaRow = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
  2116. $refPowiazaniaRowToPowiazaniaRowObject = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  2117. foreach ($this->results as $result) {
  2118. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  2119. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  2120. foreach ($result as $ID => $rel) {
  2121. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  2122. $object = DB::getPDO()->fetchFirst($query);
  2123. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relations[$rel]]);
  2124. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  2125. $ref = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', $object['REMOTE_TABLE']);
  2126. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  2127. }
  2128. }
  2129. self::saveToLog("Zapisano wyliczone dane do bazy");
  2130. }
  2131. public function saveXml() {
  2132. if ($this->getPartsCount()) {
  2133. self::saveToLog("Generuję pliki XML (liczba plików do wygenerowania: {$this->getPartsCount()})");
  2134. for ($i =0; $i < $this->getPartsCount(); $i++) {
  2135. $partNo = str_pad($i + 1, 6, '0', STR_PAD_LEFT);
  2136. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  2137. file_put_contents($xmlFile, $this->asXml($i));
  2138. }
  2139. self::saveToLog("Zakończono generowanie plików XML");
  2140. } else {
  2141. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
  2142. file_put_contents($xmlFile, $this->asXml());
  2143. }
  2144. }
  2145. public function asXml($resultsPart = null) {
  2146. self::saveToLog("Generuję plik XML ({$resultsPart})");
  2147. if (!$this->results) {
  2148. self::saveToLog("Brak wyników (#1), nie wygenerowano pliku XML ({$resultsPart})");
  2149. return null;
  2150. }
  2151. if (!$this->items_results[$resultsPart]) $this->generateItemsResults($resultsPart);
  2152. if (!$this->items_results[$resultsPart]) {
  2153. self::saveToLog("Brak wyników (#2), nie wygenerowano pliku XML ({$resultsPart})");
  2154. return null;
  2155. }
  2156. $xmlRoot = "RelatedFeatureRoot";
  2157. $return = V::arrayToXML($this->items_results[$resultsPart], true, $xmlRoot);
  2158. self::saveToLog("Wygenerowano plik XML ({$resultsPart})");
  2159. return $return;
  2160. }
  2161. public function asArray($resultsPart = null, $subArray = null) {
  2162. if (!$this->results) return null;
  2163. if (!$this->items_results[$resultsPart]) $this->generateItemsResults($resultsPart);
  2164. if (!$this->items_results[$resultsPart]) return null;
  2165. if ($subArray) {
  2166. if (isset($this->items_results[$resultsPart][$subArray])) return $this->items_results[$subArray];
  2167. else return [];
  2168. } else return $this->items_results[$resultsPart];
  2169. }
  2170. public function powiazaniaFound() {
  2171. if ($this->results) return true;
  2172. else return false;
  2173. }
  2174. public function generatePdfAndHtml() {
  2175. if ($this->getPartsCount()) {
  2176. self::saveToLog("Generuję raporty w plikach PDF oraz HTML (liczba raportów do wygenerowania: {$this->getPartsCount()})");
  2177. for ($i =0; $i < $this->getPartsCount(); $i++) $this->_generatePdfAndHtml($i);
  2178. self::saveToLog("Zakończono generowanie raportów w plikach PDF oraz HTML");
  2179. } else $this->_generatePdfAndHtml();
  2180. }
  2181. private function _generatePdfAndHtml($resultsPart = null) {
  2182. $id_part = $resultsPart === null ? $this->ID : $this->ID . "_" . str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  2183. self::saveToLog("Generuję raport w pliku PDF oraz HTML ({$resultsPart})");
  2184. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.xml";
  2185. $pdfDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.pdf";
  2186. $htmlDestDir = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.html";
  2187. $htmlZipDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.zip";
  2188. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  2189. $antXmlFilename = "relations-{$id_part}.out_task.dita.final_with_RelatedFeatureLoop.xml";
  2190. $antXmlFile = $antDir . "/" . $antXmlFilename;
  2191. $pdfFile = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}/pdf/relations-{$id_part}.pdf";
  2192. $htmlDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}/html";
  2193. if (!file_exists($antDir)) mkdir($antDir, 0755, true);
  2194. if (!is_dir($antDir)) {
  2195. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików PDF i HTML";
  2196. self::saveToLog("Nie wygenerowano plików PDF oraz HTML - problem z utworzeniem katalogu dla ant ({$resultsPart})");
  2197. } else {
  2198. copy($xmlFile, $antXmlFile);
  2199. 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-{$id_part}");
  2200. self::saveToLog("Generuję plik PDF ({$resultsPart})");
  2201. shell_exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o pdf -i relations-{$id_part}.ditamap -f pdf");
  2202. if (file_exists($pdfFile)) {
  2203. rename($pdfFile, $pdfDestFile);
  2204. self::saveToLog("Wygenerowano plik PDF ({$resultsPart})");
  2205. } else $self::saveToLog("Nie udało się wygenerować pliku PDF ({$resultsPart})");
  2206. self::saveToLog("Generuję pliki HTML ({$resultsPart})");
  2207. shell_exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o html -i relations-{$id_part}.ditamap -f tocjs");
  2208. if (file_exists($htmlDir) && is_dir($htmlDir)) {
  2209. shell_exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}\" && zip -r \"{$htmlZipDestFile}\" html");
  2210. if (file_exists($htmlDestDir)) shell_exec("rm -rf \"{$htmlDestDir}\"");
  2211. shell_exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
  2212. self::saveToLog("Wygenerowano pliki HTML ({$resultsPart})");
  2213. } else self::saveToLog("Nie udało się wygenerować plików HTML {$resultsPart})");
  2214. }
  2215. }
  2216. }