BiAuditGenerate.php 109 KB

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