BiAuditGenerate.php 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677
  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. private $POWIAZANIA_ID = null;
  22. public function handleAuth() {
  23. if (!User::logged()) {
  24. User::authByRequest();
  25. }
  26. }
  27. private static function getDirectory($table, $id) {
  28. $folderConf = FoldersConfig::getAll($table.'_COLUMN');
  29. $record = new stdClass;
  30. $record->ID = $id;
  31. $uploader = new FileUploader($table.'_COLUMN', $record);
  32. $errMsg = "";
  33. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
  34. $uploader->findFolder();
  35. return $uploader->getDestLocalPath(true);
  36. }
  37. private static function getUrl($table, $id) {
  38. $folderConf = FoldersConfig::getAll($table.'_COLUMN');
  39. $record = new stdClass;
  40. $record->ID = $id;
  41. $uploader = new FileUploader($table.'_COLUMN', $record);
  42. $errMsg = "";
  43. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
  44. return $uploader->getFolderWeb() . "/" . $uploader->getDestFolder(true);
  45. }
  46. private static function getMainDirectory() {
  47. $folderConf = FoldersConfig::getAll('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_COLUMN');
  48. if (!isset($folderConf['mount_point'])) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
  49. return $folderConf['mount_point'];
  50. }
  51. private static function parseNipRegon($string) {
  52. $nip = null; $regon = null;
  53. preg_match('/^(.*[^[:digit:]])?([[:digit:]]{10})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
  54. if (!empty($matches[2])) $nip = trim($matches[2]);
  55. if ($nip && !V::isNip($nip)) $nip = null;
  56. preg_match('/^(.*[^[:digit:]])?([[:digit:]]{9})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
  57. if (!empty($matches[2])) $regon = trim($matches[2]);
  58. if ($regon && !V::isRegon($regon)) $regon = null;
  59. return [$nip, $regon];
  60. }
  61. private function initializePowiazaniaForm() {
  62. ?>
  63. <div class="container" style="margin-top:20px">
  64. <form class="form-horizontal" method="post">
  65. <legend>
  66. Generowanie powiązań :: <?=$this->powiazanie['L_APPOITMENT_INFO']?>
  67. <span class="pull-right"># <?=$this->powiazanie['ID']?></span>
  68. </legend>
  69. <div class="form-group">
  70. <div class="col-sm-12">
  71. <h4>Wybierz pracowników, dla których mają zostać wyszukane powiązania</h4>
  72. <table class="table table-bordered table-hover table-striped" height=5>
  73. <thead>
  74. <tr style="text-align:center; background-color:lightgray">
  75. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  76. <td width=1>ID</td>
  77. <td>Imiona</td>
  78. <td>Nazwisko</td>
  79. <td>Pesel</td>
  80. <td>NIP</td>
  81. <td>Regon</td>
  82. <td>source</td>
  83. </tr>
  84. </thead>
  85. <tbody>
  86. <?php
  87. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
  88. $queryFeatures = $acl->buildQuery(['limit' => 0]);
  89. $pracownicy = $queryFeatures->getItems();
  90. foreach ($pracownicy as $pracownik) {
  91. ?>
  92. <tr>
  93. <td><input type="checkbox" name="prID[]" value="<?=$pracownik['ID']?>" onClick="toggle(this)"/></td>
  94. <td align="right"><?=$pracownik['ID']?></td>
  95. <td><?=$pracownik['imiona']?></td>
  96. <td><?=$pracownik['nazwisko']?></td>
  97. <td><?=$pracownik['pesel']?></td>
  98. <td><?=$pracownik['nip']?></td>
  99. <td><?=$pracownik['regon']?></td>
  100. <td><?=$pracownik['source']?></td>
  101. </tr>
  102. <?php
  103. }
  104. ?>
  105. </tbody>
  106. </table>
  107. </div>
  108. </div>
  109. <!-- <div class="form-group">
  110. <label class="col-sm-2 control-label">
  111. Odśwież cache
  112. </label>
  113. <div class="col-sm-2">
  114. <select name="reloadCache" class="form-control">
  115. <option value="No" selected>Nie</option>
  116. <!-#- <option value="Part">Częściowe</option>-#->
  117. <option value="Full">Pełne</option>
  118. </select>
  119. </div>
  120. </div>
  121. <div class="form-group">
  122. <div class="col-sm-offset-2 col-sm-10">
  123. <!-#- Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>-#->
  124. Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów.<br/>
  125. Uwaga! Jeżeli aktywne są inne zadania, te zadanie zostanie wstrzymane do momentu ich ukończenia.
  126. </div>
  127. </div>-->
  128. <div class="form-group">
  129. <div class="col-sm-12">
  130. <div class="containter" style="text-align:center">
  131. <button type="submit" class="btn btn-primary btn-sm" name="action" value="initialize">Generuj</button>
  132. <a href="<?=$this->REFERER?>" class="btn btn-default">Anuluj</a>
  133. </div>
  134. </div>
  135. </div>
  136. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  137. </form>
  138. </div>
  139. <script language="JavaScript">
  140. <!--
  141. function toggleAll(source) {
  142. checkboxes = document.getElementsByName('prID[]');
  143. for(var i=0, n=checkboxes.length;i<n;i++) checkboxes[i].checked = source.checked;
  144. }
  145. function toggle(source) {
  146. checkboxes = document.getElementsByName('prID[]');
  147. all = true;
  148. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked == false) all = false;
  149. source.form['checkAll'].checked = all;
  150. }
  151. -->
  152. </script>
  153. <?php
  154. }
  155. private function initializePowiazaniaSave() {
  156. $prID = V::get('prID', array(), $_POST);
  157. if (!$prID) throw new Exception("Nie wybrano żadnego pracownika!");
  158. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
  159. $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
  160. $kontrahenci = $queryFeatures->getItems();
  161. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_KW_requested_person/BI_audit_KW_requested_person');
  162. $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
  163. $requestedPersons = $queryFeatures->getItems();
  164. if (!($kontrahenci || $requestedPersons)) throw new Exception("Nie znaleziono żadnego obiektu końcowego");
  165. $sqlUpdate = ['FILE_STATUS' => 'TO_GENERATE'];
  166. $reloadCache = V::get('reloadCache', 'No', $_POST);
  167. $reloadCacheAvailable = ['Full', 'Part', 'No'];
  168. if (!in_array($reloadCache, $reloadCacheAvailable)) throw new Exception("Błąd formularza!");
  169. $sqlUpdate['BI_analiza_reloadCache'] = $reloadCache;
  170. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part')";
  171. $result = DB::getPDO()->fetchValue($query);
  172. if ($result) $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache (wymagane dla innego rekordu)';
  173. elseif ($reloadCache != 'No') $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache';
  174. else $sqlUpdate['FILE_STATUS_info'] = "Oczekuje na wygenerowanie powiązań";
  175. if ($this->powiazanie) { // wyzwolone z poziomu tabeli BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA - aktualizujemy istniejący rekord
  176. $powiazanieID = $this->powiazanie['ID'];
  177. } else { // wyzwolone z poziomu tabeli BI_audit_ENERGA_PRACOWNICY - dodajemy nowy rekord
  178. if (count($prID) != 1) throw new Exception("Błąd formularza!");
  179. if (!($lAppoitmentInfo = V::get('info', false, $_POST))) throw new Exception("Błąd formularza!");
  180. if (!($BiAnalizaMinDepth = V::get('minDepth', false, $_POST))) throw new Exception("Błąd formularza!");
  181. if (!($BiAnalizaMaxDepth = V::get('maxDepth', false, $_POST))) throw new Exception("Błąd formularza!");
  182. if (!($BiAnalizaOnlyTargets = V::get('onlyTargets', false, $_POST))) throw new Exception("Błąd formularza!");
  183. $query = "select * from BI_audit_ENERGA_PRACOWNICY where ID='{$prID[0]}'";
  184. $result = DB::getPDO()->fetchFirst($query);
  185. if (!$result) throw new Exception("Błąd formularza!");
  186. $sqlInsert = [
  187. 'L_APPOITMENT_INFO' => $lAppoitmentInfo,
  188. 'A_STATUS' => 'NORMAL',
  189. 'A_STATUS_INFO' => 'Dodane przez BiAuditGenerate z poziomu tabeli BI_audit_ENERGA_PRACOWNICY',
  190. 'A_ADM_COMPANY' => $result['A_ADM_COMPANY'],
  191. 'A_CLASSIFIED' => $result['A_CLASSIFIED'],
  192. 'FILE_STATUS' => 'NONE',
  193. 'FILE_STATUS_info' => 'Oczekuję na zdefiniowanie danych wejściowych',
  194. 'BI_analiza_reloadCache' => $sqlUpdate['BI_analiza_reloadCache'],
  195. 'BI_analiza_minDepth' => $BiAnalizaMinDepth,
  196. 'BI_analiza_maxDepth' => $BiAnalizaMaxDepth,
  197. 'BI_analiza_onlyTargets' => $BiAnalizaOnlyTargets,
  198. ];
  199. $powiazanieID = DB::getDB()->ADD_NEW_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', (object)$sqlInsert);
  200. if ($powiazanieID) SE_Layout::alert('success','Dodano rekord do wygenerowania powiązań');
  201. else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  202. }
  203. $sqlUpdate['ID'] = $powiazanieID;
  204. self::truncatePowiazaniaFromDB($powiazanieID);
  205. $refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
  206. foreach ($prID as $v) DB::getPDO()->insert($refPowiazaniaToPracownicy, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $v]);
  207. $refPowiazaniaToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  208. foreach ($kontrahenci as $kontrahent) DB::getPDO()->insert($refPowiazaniaToKontrahenci, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $kontrahent['ID']]);
  209. $refPowiazaniaToKwRequestedPreson = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_KW_requested_person', true);
  210. foreach ($requestedPersons as $requestedPerson) DB::getPDO()->insert($refPowiazaniaToKwRequestedPreson, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $requestedPerson['ID']]);
  211. $affected = DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlUpdate);
  212. if ($affected) {
  213. if ($this->powiazanie) {
  214. SE_Layout::alert('success','Oznaczono rekord do wygenerowania powiązań');
  215. ?>
  216. <div class="container" style="text-align:center">
  217. <a href="<?=$this->REFERER?>" class="btn btn-primary">Powrót</a>
  218. </div>
  219. <?php
  220. }
  221. } else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  222. }
  223. private function initializePowiazania() {
  224. switch (V::get('action', '', $_POST)) {
  225. case "initialize":
  226. $this->initializePowiazaniaSave();
  227. break;
  228. default:
  229. $this->initializePowiazaniaForm();
  230. }
  231. }
  232. private function showPowiazania() {
  233. // echo "Statystyki znalezionych powiązań [TODO]";
  234. $dir = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  235. $url = self::getUrl('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  236. $reports = [
  237. 'pdf' => [
  238. 'files' => glob("{$dir}/relations*.pdf"),
  239. 'label' => 'Raporty PDF:<br/>&nbsp;',
  240. 'button' => 'Pokaż raport PDF',
  241. 'regex' => "/^relations(-{$this->powiazanie['ID']})?_([[:digit:]]+)\.pdf$/",
  242. 'parentDir' => false,
  243. ],
  244. 'html' => [
  245. 'files' => glob("{$dir}/html*/relations-{$this->powiazanie['ID']}*.html"),
  246. 'label' => 'Raporty HTML<br/>do przeglądania:',
  247. 'button' => 'Pokaż raport HTML',
  248. 'regex' => "/^relations-({$this->powiazanie['ID']})_([[:digit:]]+)\.html$/",
  249. 'parentDir' => true,
  250. ],
  251. 'htmlZip' => [
  252. 'files' => glob("{$dir}/html*.zip"),
  253. 'label' => 'Raporty HTML<br/>do pobrania:',
  254. 'button' => 'Pobież raport HTML',
  255. 'regex' => "/^html(-{$this->powiazanie['ID']})?_([[:digit:]]+)\.zip$/",
  256. 'parentDir' => false,
  257. ],
  258. ];
  259. ?>
  260. <div class="container" style="margin-top:20px">
  261. <legend>
  262. Wygenerowany raport nr <?=$this->powiazanie['ID']?>
  263. </legend>
  264. <div class="form-group" style="text-align: center;">
  265. <?php
  266. array_walk($reports, function ($report) use ($url) {
  267. echo "<div class=\"col-sm-2\"><h4>{$report['label']}</h4>";
  268. $hrefs = array_filter(array_map(function ($path) use ($url, $report) {
  269. if (!is_file($path)) return false;
  270. $file = basename($path);
  271. if (preg_match($report['regex'], $file, $matches)) $i = " (" . ltrim($matches[2], '0') . ")";
  272. else $i = '';
  273. if ($report['parentDir']) $file = basename(dirname($path)) . "/" . $file;
  274. return "<a href=\"{$url}/{$file}\" target=\"_blank\" class=\"btn btn-primary\">{$report['button']}{$i}</a>";
  275. }, $report['files']));
  276. if ($hrefs) echo implode('<br/><br/>', $hrefs);
  277. else echo "<h5>Nie znaleziono</h5>";
  278. echo "</div>\n";
  279. });
  280. ?>
  281. </div>
  282. <div class="form-group">
  283. <div class="col-sm-12">
  284. <br/><br/><a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  285. </div>
  286. </div>
  287. </div>
  288. <?php
  289. }
  290. private function showPowiazaniaList() {
  291. switch (V::get('action', '', $_POST)) {
  292. case "initialize":
  293. $this->initializePowiazaniaSave();
  294. break;
  295. }
  296. $this->showPowiazaniaListForm();
  297. }
  298. private function showPowiazaniaListForm() {
  299. if (!$this->SOURCE['ID']) throw new Exception("Błąd danych");
  300. elseif ($this->SOURCE['TABLE'] != 'BI_audit_ENERGA_PRACOWNICY') throw new Exception("Błąd danych");
  301. $query = "select * from `{$this->SOURCE['TABLE']}` where ID = '{$this->SOURCE['ID']}'";
  302. $pracownik = DB::getPDO()->fetchFirst($query);
  303. if (!$pracownik) throw new Exception("Błąd danych");
  304. ?>
  305. <div class="container" style="margin-top:20px">
  306. <legend>
  307. Lista wygenerowanych powiązań :: <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>
  308. <span class="pull-right"># <?=$pracownik['ID']?></span>
  309. </legend>
  310. <div class="form-group">
  311. <div class="col-sm-12">
  312. <h4>Lista wygenerowanych powiązań, w których znajduje się pracownik</h4>
  313. <table class="table table-bordered table-hover table-striped" height=5>
  314. <thead>
  315. <tr style="text-align:center; background-color:lightgray">
  316. <td width=1>ID</td>
  317. <td>Adnotacje</td>
  318. <td>Minimalna głębokość analizy</td>
  319. <td>Maksymalna głębokość analizy</td>
  320. <td>Powiązania tylko do celów</td>
  321. <td>Status raportu</td>
  322. <td>Status raportu - informacje</td>
  323. <td>Indywidualny raport</td>
  324. <td width=1></td>
  325. </tr>
  326. </thead>
  327. <tbody>
  328. <?php
  329. $refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
  330. $query = "select `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.*
  331. from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  332. join `{$refPowiazaniaToPracownicy}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPracownicy}`.`PRIMARY_KEY`
  333. where `REMOTE_PRIMARY_KEY` = '{$this->SOURCE['ID']}'";
  334. $result = DB::getPDO()->fetchAll($query);
  335. if (!$result) echo '<tr><td align="center" colspan="9">Brak znalezionych powiązań</td></tr>';
  336. else {
  337. foreach ($result as $row) {
  338. $query = "select count(*) from `{$refPowiazaniaToPracownicy}` where `PRIMARY_KEY` = '{$row['ID']}'";
  339. $count = DB::getPDO()->fetchValue($query);
  340. ?>
  341. <tr>
  342. <td align="right"><?=$row['ID']?></td>
  343. <td><?=$row['L_APPOITMENT_INFO']?></td>
  344. <td><?=$row['BI_analiza_minDepth']?></td>
  345. <td><?=$row['BI_analiza_maxDepth']?></td>
  346. <td><?=($row['BI_analiza_onlyTargets'] == 'N' ? "Nie" : "Tak")?></td>
  347. <td><?=$row['FILE_STATUS']?></td>
  348. <td><?=$row['FILE_STATUS_info']?></td>
  349. <td><?=($count > 1 ? 'Nie' : 'Tak')?></td>
  350. <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>
  351. </tr>
  352. <?php
  353. }
  354. }
  355. ?>
  356. </tbody>
  357. </table>
  358. </div>
  359. </div>
  360. <div class="form-group">
  361. <div class="col-sm-12">
  362. <h4>Dodaj nowe zadanie generowania powiazań dla tego pracownika</h4>
  363. </div>
  364. </div>
  365. <form class="form-horizontal" method="post">
  366. <div class="form-group">
  367. <label class="col-sm-4 control-label">Minimalna głębokość poszukiwań (liczba rekurencji)</label>
  368. <div class="col-sm-1">
  369. <input type="number" class="form-control" name="minDepth" id="minDepth" data-bind="value:replyNumber" min="1" max="9" value="1" required/>
  370. </div>
  371. </div>
  372. <div class="form-group">
  373. <label class="col-sm-4 control-label">Maksymalna głębokość poszukiwań (liczba rekurencji)</label>
  374. <div class="col-sm-1">
  375. <input type="number" class="form-control" name="maxDepth" id="maxDepth" data-bind="value:replyNumber" min="1" max="9" value="6" required/>
  376. </div>
  377. </div>
  378. <div class="form-group">
  379. <label class="col-sm-4 control-label">Czy zwracać tylko wyniki ze znalezionymi obiektami docelowymi (z tabeli kontrahentów)?</label>
  380. <div class="col-sm-1">
  381. <select name="onlyTargets" class="form-control">
  382. <option value="Y" selected>Tak</option>
  383. <option value="N">Nie</option>
  384. </select>
  385. </div>
  386. </div>
  387. <div class="form-group">
  388. <label class="col-sm-4 control-label">Adnotacje</label>
  389. <div class="col-sm-4">
  390. <input type="text" class="form-control" name="info" value="Indywidualnie dla <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>" required/>
  391. </div>
  392. </div>
  393. <!-- <div class="form-group">
  394. <label class="col-sm-4 control-label">
  395. Odśwież cache
  396. </label>
  397. <div class="col-sm-2">
  398. <select name="reloadCache" class="form-control">
  399. <option value="No" selected>Nie</option>
  400. <!-#- <option value="Part">Częściowe</option>-#->
  401. <option value="Full">Pełne</option>
  402. </select>
  403. </div>
  404. </div>
  405. <div class="form-group">
  406. <div class="col-sm-offset-4 col-sm-8">
  407. <!-#- Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>-#->
  408. Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów.<br/>
  409. Uwaga! Jeżeli aktywne są inne zadania, te zadanie zostanie wstrzymane do momentu ich ukończenia.
  410. </div>
  411. </div>-->
  412. <div class="form-group">
  413. <div class="col-sm-12">
  414. <div class="containter" style="text-align:center">
  415. <button type="submit" class="btn btn-primary" name="action" value="initialize" onClick="return validate()">Generuj</button>
  416. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  417. </div>
  418. </div>
  419. </div>
  420. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  421. <input type="hidden" name="prID[]" value="<?=$pracownik['ID']?>">
  422. </form>
  423. </div>
  424. <script language="JavaScript">
  425. <!--
  426. function validate() {
  427. result = (document.getElementById('minDepth').value <= document.getElementById('maxDepth').value);
  428. if (!result) alert('Wartość minimalnej głębokości analizy nie może być większa od wartości maksymalnej głębokości analizy!');
  429. return result;
  430. }
  431. -->
  432. </script>
  433. <?php
  434. }
  435. private function powiazania() {
  436. try {
  437. if (!$this->SOURCE) throw new Exception("Błąd danych");
  438. elseif (!(isset($this->SOURCE['TABLE']) && isset($this->SOURCE['ID']))) throw new Exception("Błąd danych");
  439. switch ($this->SOURCE['TABLE']) {
  440. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  441. $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->SOURCE['ID']}'");
  442. if (!$powiazania) throw new Exception("Błąd danych");
  443. $this->powiazanie = $powiazania[0];
  444. switch ($this->powiazanie['FILE_STATUS']) {
  445. case "NONE":
  446. $this->initializePowiazania();
  447. break;
  448. case "GENERATED":
  449. $this->showPowiazania();
  450. break;
  451. default: throw new Exception("Błędny status rekordu");
  452. }
  453. break;
  454. case "BI_audit_ENERGA_PRACOWNICY":
  455. $this->showPowiazaniaList();
  456. break;
  457. case "BI_audit_KRS":
  458. case "BI_audit_MSIG":
  459. $this->importToPracownicySearch($this->SOURCE['ID']);
  460. break;
  461. case "BI_audit_KRS_person":
  462. $this->showKrsForKrsPerson();
  463. break;
  464. default: throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate");
  465. }
  466. } catch (Exception $e) {
  467. SE_Layout::alert('danger',$e->getMessage());
  468. $_SESSION['REFERER'] = $this->REFERER;
  469. ?>
  470. <div class="container" style="text-align:center">
  471. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
  472. </div>
  473. <?php
  474. }
  475. }
  476. private function importToPracownicy() {
  477. $action = V::get('action', '', $_POST);
  478. switch ($action) {
  479. case "search":
  480. $this->importToPracownicySearch();
  481. break;
  482. default: $this->importToPracownicyForm();
  483. }
  484. }
  485. private $tableDesc = ['BI_audit_KRS' => 'KRS', 'BI_audit_MSIG' => 'MSiG'];
  486. private function importToPracownicyForm() {
  487. $TABLE = $this->SOURCE['TABLE'];
  488. $DESC = $this->tableDesc[$TABLE];
  489. ?>
  490. <div class="container" style="margin-top:20px">
  491. <legend>
  492. Importowanie podmiotów z <?=$DESC?> do tabel kontrahentów i pracowników
  493. </legend>
  494. <div class="form-group">
  495. <div class="col-sm-12">
  496. <h4>Znajdź podmiot</h4>
  497. </div>
  498. </div>
  499. <form class="form-horizontal" method="post">
  500. <div class="form-group">
  501. <label class="col-sm-1 control-label">Nazwa</label>
  502. <div class="col-sm-4">
  503. <input type="text" class="form-control" name="nazwa" title="Podaj nazwę podmiotu">
  504. </div>
  505. </div>
  506. <div class="form-group">
  507. <label class="col-sm-1 control-label">KRS</label>
  508. <div class="col-sm-2">
  509. <input type="text" class="form-control" name="krs" pattern="^[0-9]{0,10}$" title="Podaj KRS"/>
  510. </div>
  511. </div>
  512. <div class="form-group">
  513. <label class="col-sm-1 control-label">NIP</label>
  514. <div class="col-sm-2">
  515. <input type="text" class="form-control" name="nip" pattern="^[0-9]{0,10}$" title="Podaj NIP (bez kresek i bez oznaczenia kraju)"/>
  516. </div>
  517. </div>
  518. <div class="form-group">
  519. <label class="col-sm-1 control-label">Regon</label>
  520. <div class="col-sm-2">
  521. <input type="text" class="form-control" name="regon" pattern="^[0-9]{0,9}$" title="Podaj regon"/>
  522. </div>
  523. </div>
  524. <div class="form-group">
  525. <div class="col-sm-offset-1 col-sm-11">
  526. <button type="submit" class="btn btn-primary" name="action" value="search">Szukaj</button>
  527. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  528. </div>
  529. </div>
  530. </form>
  531. </div>
  532. <?php
  533. }
  534. private function importToPracownicySearch($krsId = null) {
  535. $TABLE = $this->SOURCE['TABLE'];
  536. $DESC = $this->tableDesc[$TABLE];
  537. $formItems = [
  538. "nazwa" => 'like',
  539. "krs" => '=',
  540. "nip" => '=',
  541. "regon" => '=',
  542. ];
  543. try {
  544. $subaction = V::get('subaction', '', $_POST);
  545. switch ($subaction) {
  546. case "listPerson":
  547. $krsId = V::get('krsId', 0, $_POST, int);
  548. break;
  549. case "addPersonToPracownicy":
  550. $krsId = V::get('krsId', 0, $_POST, int);
  551. $personId = V::get('personId', [], $_POST);
  552. if (!$personId) throw new Exception("Błąd formularza");
  553. $query = "insert into BI_audit_ENERGA_PRACOWNICY (source, imiona, nazwisko, pesel) select 'KRS', imiona, nazwisko, pesel from {$TABLE}_person where ID in (" . implode(", ", $personId) . ")";
  554. DB::getPDO()->query($query);
  555. SE_Layout::alert('success', "Pomyślnie zaimportowano " . count($personId) . " pracownik" . ((count($personId) == 1) ? "a" : "ów"));
  556. break;
  557. case "addToKontrahenci":
  558. $krsId = V::get('krsId', 0, $_POST, int);
  559. if (!$krsId) throw new Exception("Błąd formularza");
  560. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI kh join {$TABLE} krs on (kh.NIP = krs.nip or kh.REGON = krs.regon or kh.KRS = krs.krs) where krs.ID = '{$krsId}'";
  561. $kontrahentExists = DB::getPDO()->fetchValue($query);
  562. if ($kontrahentExists) throw new Exception("Podmiot znajduje się już w tabeli kontrahentów");
  563. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (Tytul_dokumentu, Pelna_nazwa_kontrahenta, REGON, NIP, KRS) select 'ZaImportowano z {$DESC}', nazwa, regon, nip, krs from {$TABLE} where ID = ".$krsId." ";
  564. DB::getPDO()->query($query);
  565. SE_Layout::alert('success', "Pomyślnie zaimportowano kontrahenta");
  566. break;
  567. }
  568. if ($krsId) {
  569. $where = ["ID = '{$krsId}'"];
  570. } else {
  571. $form = [];
  572. foreach ($formItems as $item => $type) {
  573. if ($param = V::get($item, '', $_POST)) {
  574. if ($type == 'like') $param = "%{$param}%";
  575. $form[$item] = DB::getPDO()->quote($param);
  576. }
  577. }
  578. if (!$form) throw new Exception("Nie wypełniono żadnego pola wyszukiwania!");
  579. $where = [];
  580. foreach ($form as $name => $value) $where[] = "`{$name}` {$formItems[$name]} {$value}";
  581. }
  582. } catch (Exception $e) {
  583. SE_Layout::alert('danger', $e->getMessage());
  584. $this->importToPracownicyForm();
  585. return;
  586. }
  587. $query = "select * from `{$TABLE}` where " . implode(" and ", $where) . "order by ID limit 1001";
  588. $result = DB::getPDO()->fetchAll($query);
  589. if (count($result) == 1001) {
  590. SE_Layout::alert('danger', 'Znaleziono zbyt wiele wyników. Doprecyzuj parametry wyszukiwania.');
  591. $this->importToPracownicyForm();
  592. return;
  593. } elseif (count($result) == 1) {
  594. $krsId = $result[0]['ID'];
  595. }
  596. ?>
  597. <div class="container" style="margin-top:20px">
  598. <form method="post">
  599. <legend>
  600. Importowanie podmiotów z <?=$DESC?> do tabel kontrahentów i pracowników
  601. </legend>
  602. <div class="form-group">
  603. <div class="col-sm-12">
  604. <h4>Znalezione podmioty:</h4>
  605. </div>
  606. </div>
  607. <div class="form-group">
  608. <div class="col-sm-12">
  609. <table class="table table-bordered table-hover table-striped" height=5>
  610. <thead>
  611. <tr style="text-align:center; background-color:lightgray">
  612. <td width=1>Lp.</td>
  613. <td>Nazwa</td>
  614. <td>Adres</td>
  615. <td>KRS</td>
  616. <td>NIP</td>
  617. <td>Regon</td>
  618. <?php
  619. if (count($result) > 1) {
  620. ?>
  621. <td width=1>Wybierz</td>
  622. <?php
  623. }
  624. ?>
  625. </tr>
  626. </thead>
  627. <tbody>
  628. <?php
  629. if (!$result) echo '<tr><td align="center" colspan="6">Nie znaleziono podmiotu</td></tr>';
  630. else {
  631. $lp = 1;
  632. foreach ($result as $row) {
  633. $adres = $row['A_miejscowosc'];
  634. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  635. if ($row['A_nrDomu']) {
  636. $adres .= " {$row['A_nrDomu']}";
  637. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  638. }
  639. ?>
  640. <tr>
  641. <td align="right"><?=$lp++?></td>
  642. <td><?=htmlspecialchars($row['nazwa'])?></td>
  643. <td><?=htmlspecialchars($adres)?></td>
  644. <td><?=$row['krs']?></td>
  645. <td><?=$row['nip']?></td>
  646. <td><?=$row['regon']?></td>
  647. <?php
  648. if (count($result) > 1) {
  649. ?>
  650. <td align="center">
  651. <input type="radio" name="krsId" value="<?=$row['ID']?>"/>
  652. </td>
  653. <?php
  654. }
  655. ?>
  656. </tr>
  657. <?php
  658. }
  659. }
  660. ?>
  661. </tbody>
  662. </table>
  663. </div>
  664. </div>
  665. <?php
  666. if (count($result) > 1) {
  667. ?>
  668. <div class="form-group">
  669. <div class="col-sm-12">
  670. <?php
  671. foreach (array_keys($formItems) as $item) {
  672. ?>
  673. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  674. <?php
  675. }
  676. ?>
  677. <input type="hidden" name="back" value="search"/>
  678. <div class="containter" style="text-align:center">
  679. <button type="submit" class="btn btn-primary" name="subaction" value="listPerson" onClick="return validateCompany(this)">Wybierz zaznaczony podmiot</button>
  680. <a href="" class="btn btn-default">Powrót</a>
  681. </div>
  682. </div>
  683. </div>
  684. <?php
  685. } elseif ($krsId) {
  686. ?>
  687. <div class="form-group">
  688. <div class="col-sm-12">
  689. <h4>Znalezione osoby:</h4>
  690. </div>
  691. </div>
  692. <div class="form-group">
  693. <div class="col-sm-12">
  694. <table class="table table-bordered table-hover table-striped" height=5>
  695. <thead>
  696. <tr style="text-align:center; background-color:lightgray">
  697. <td width=1>Lp.</td>
  698. <td>Nazwisko</td>
  699. <td>Imiona</td>
  700. <td>Pesel</td>
  701. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  702. </tr>
  703. </thead>
  704. <tbody>
  705. <?php
  706. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI kh join {$TABLE} krs on (kh.NIP = krs.nip or kh.REGON = krs.regon or kh.KRS = krs.krs) where krs.ID = '{$krsId}'";
  707. $kontrahentExists = DB::getPDO()->fetchValue($query);
  708. $refToPerson = BiAuditRefTables::getRefTable($TABLE, "{$TABLE}_person", true);
  709. $query = "select person.*, pracownicy.ID as pracownicyId from `{$refToPerson}` ref join `{$TABLE}_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}'";
  710. $result = DB::getPDO()->fetchAll($query);
  711. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono osób powiązanych z podmiotem</td></tr>';
  712. else {
  713. $lp = 1;
  714. foreach ($result as $row) {
  715. ?>
  716. <tr<?=($row['pracownicyId'] ? ' style="color:darkgrey"' : '')?>>
  717. <td align="right"><?=$lp++?></td>
  718. <td><?=$row['nazwisko']?></td>
  719. <td><?=$row['imiona']?></td>
  720. <td><?=$row['pesel']?></td>
  721. <td><input type="checkbox" name="personId[]" value="<?=$row['ID']?>" onClick="toggle(this)" <?=($row['pracownicyId'] ? "disabled" : "")?>/></td>
  722. </tr>
  723. <?php
  724. }
  725. }
  726. ?>
  727. </tbody>
  728. </table>
  729. </div>
  730. </div>
  731. <!-- <div class="form-group">
  732. <div class="col-sm-12">
  733. <label class="col-sm-4 control-label">Opis/źródło</label>
  734. <div class="col-sm-4">
  735. <input type="text" class="form-control" name="source" placeholder="KRS"/>
  736. </div>
  737. </div>
  738. </div>-->
  739. <div class="form-group">
  740. <div class="col-sm-12" style="text-align: center;">
  741. <button type="submit" class="btn btn-primary" name="subaction" value="addToKontrahenci"<?=($kontrahentExists ? " disabled" : "")?>>Dodaj firmę do tabeli kontrahentów</button>
  742. <button type="submit" class="btn btn-primary" name="subaction" value="addPersonToPracownicy" onClick="return validatePerson(this)">Dodaj zaznaczone osoby do tabeli pracowników</button>
  743. <input type="hidden" name="krsId" value="<?=$krsId?>"/>
  744. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  745. <?php
  746. if (V::get('back', '', $_POST) == 'search') {
  747. foreach (array_keys($formItems) as $item) {
  748. ?>
  749. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  750. <?php
  751. }
  752. ?>
  753. <button type="submit" class="btn btn-default" name="action" value="search">Powrót</button>
  754. <?php
  755. } else {
  756. ?>
  757. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  758. <?php
  759. }
  760. ?>
  761. </div>
  762. </div>
  763. <?php
  764. }
  765. ?>
  766. <input type="hidden" name="action" value="search">
  767. </form>
  768. </div>
  769. <script language="JavaScript">
  770. <!--
  771. function toggleAll(source) {
  772. checkboxes = document.getElementsByName('personId[]');
  773. checked = false;
  774. for(var i=0, n=checkboxes.length;i<n;i++) {
  775. if (!checkboxes[i].disabled) {
  776. checkboxes[i].checked = source.checked;
  777. checked = true;
  778. }
  779. }
  780. if (source.checked && (!checked)) source.checked = false;
  781. }
  782. function toggle(source) {
  783. checkboxes = document.getElementsByName('personId[]');
  784. all = true;
  785. for(var i=0, n=checkboxes.length;i<n;i++) if(!checkboxes[i].disabled && checkboxes[i].checked == false) all = false;
  786. source.form['checkAll'].checked = all;
  787. }
  788. function validatePerson(source) {
  789. checkboxes = document.getElementsByName('personId[]');
  790. checked = false;
  791. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked) checked = true;
  792. if (!checked) alert('Nie wybrano żadnej osoby!');
  793. return checked;
  794. }
  795. function validateCompany(source) {
  796. radios = document.getElementsByName('krsId');
  797. checked = false;
  798. for(var i=0, n=radios.length;i<n;i++) if(radios[i].checked) checked = true;
  799. if (!checked) alert('Nie wybrano żadnej firmy!');
  800. return checked;
  801. }
  802. -->
  803. </script>
  804. <?php
  805. }
  806. private function showKrsForKrsPerson() {
  807. $query = "select * from BI_audit_KRS_person where ID = '{$this->SOURCE['ID']}'";
  808. $result = DB::getPDO()->fetchFirst($query);
  809. ?>
  810. <div class="container" style="margin-top:20px">
  811. <legend>
  812. Lista podmiotów, w których występuje <?="{$result['nazwisko']} {$result['imiona']}" . ($result['pesel'] ? " (PESEL: {$result['pesel']})" : "")?>
  813. </legend>
  814. <div class="form-group">
  815. <div class="col-sm-12">
  816. <table class="table table-bordered table-hover table-striped" height=5>
  817. <thead>
  818. <tr style="text-align:center; background-color:lightgray">
  819. <td width=1>Lp.</td>
  820. <td>Nazwa</td>
  821. <td>Adres</td>
  822. <td>KRS</td>
  823. <td>NIP</td>
  824. <td>Regon</td>
  825. <td width=1></td>
  826. </tr>
  827. </thead>
  828. <tbody>
  829. <?php
  830. $refKrsToKrsPerson = BiAuditRefTables::getRefTable('BI_audit_KRS', 'BI_audit_KRS_person', true);
  831. $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']}'";
  832. $result = DB::getPDO()->fetchAll($query);
  833. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono powiązanych podmiotów</td></tr>';
  834. else {
  835. $lp = 1;
  836. foreach ($result as $row) {
  837. $adres = $row['A_miejscowosc'];
  838. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  839. if ($row['A_nrDomu']) {
  840. $adres .= " {$row['A_nrDomu']}";
  841. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  842. }
  843. ?>
  844. <tr>
  845. <td align="right"><?=$lp++?></td>
  846. <td><?=htmlspecialchars($row['nazwa'])?></td>
  847. <td><?=htmlspecialchars($adres)?></td>
  848. <td><?=$row['krs']?></td>
  849. <td><?=$row['nip']?></td>
  850. <td><?=$row['regon']?></td>
  851. <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>
  852. </tr>
  853. <?php
  854. }
  855. }
  856. ?>
  857. </tbody>
  858. </table>
  859. </div>
  860. </div>
  861. <div class="form-group">
  862. <div class="col-sm-12">
  863. <div class="containter" style="text-align:center">
  864. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-default">Powrót</a>
  865. </div>
  866. </div>
  867. </div>
  868. </div>
  869. <?php
  870. }
  871. private function clearTable_do() {
  872. try {
  873. $wynik = V::get('wynik', 0, $_POST, 'int');
  874. $ctrl = @gzuncompress(@base64_decode(V::get('_BiAuditGenerate_ctrl', '', $_SESSION)));
  875. unset($_SESSION['_BiAuditGenerate_ctrl']);
  876. $deleteFiles = (V::get('deleteFiles', '', $_POST) === 'on');
  877. $deletedDirs = 0; $deletedFiles = 0;
  878. if (!($ctrl)) throw new Exception('Błąd parametru');
  879. if (!($wynik == $ctrl)) {
  880. SE_Layout::alert('warning', 'Podano błędny wynik działania');
  881. $this->clearTable_form();
  882. return;
  883. }
  884. $refs = []; $backRefs = []; $tables = []; $queries = [];
  885. switch ($this->SOURCE['TABLE']) {
  886. case "BI_audit_ENERGA_PRACOWNICY":
  887. $refs[] = 'BI_audit_ENERGA_PRACOWNICY_adresy';
  888. $tables[] = 'BI_audit_ENERGA_PRACOWNICY_adresy';
  889. $queries[] = "update `BI_audit_ENERGA_PRACOWNICY_import` set `A_STATUS` = 'WAITING'";
  890. break;
  891. case "BI_audit_ENERGA_PRACOWNICY_import":
  892. break;
  893. case "BI_audit_ENERGA_RUM_KONTRAHENCI":
  894. $backRefs[] = 'BI_audit_ENERGA_RUM_UMOWY';
  895. $backRefs[] = 'BI_audit_ENERGA_FAKTURY';
  896. $queries[] = "update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING'";
  897. break;
  898. case "BI_audit_ENERGA_RUM_UMOWY":
  899. $refs[] = 'BI_audit_ENERGA_RUM_KONTRAHENCI';
  900. break;
  901. case "BI_audit_ENERGA_FAKTURY":
  902. $refs[] = 'BI_audit_ENERGA_RUM_KONTRAHENCI';
  903. break;
  904. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  905. $query = "select ID from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  906. $result = DB::getPDO()->fetchAll($query);
  907. foreach ($result as $row) {
  908. if ($deleteFiles) {
  909. $dir = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  910. if (!file_exists($dir)) continue;
  911. $deleted = V::deleteWholeDirectory($dir, true, false);
  912. $deletedDirs += count($deleted['dirs']);
  913. $deletedFiles += count($deleted['files']);
  914. }
  915. self::deleteResultsFromDB($row['ID']);
  916. self::truncatePowiazaniaFromDB($row['ID']);
  917. }
  918. break;
  919. default: throw new Exception('Błąd parametru');
  920. }
  921. $tables[] = $this->SOURCE['TABLE'];
  922. foreach ($refs as $ref) $tables[] = BiAuditRefTables::getRefTable($this->SOURCE['TABLE'], $ref, true);
  923. foreach ($backRefs as $backRef) $tables[] = BiAuditRefTables::getRefTable($backRef, $this->SOURCE['TABLE'], true);
  924. foreach ($tables as $table) $queries[] = "delete from `{$table}`";
  925. foreach ($queries as $query) DB::getPDO()->query($query);
  926. ?>
  927. <div style="text-align: center;">
  928. <h2>Pomyślnie wyczyszczono tabelę <?=$this->clearTable_tables[$this->SOURCE['TABLE']]?>.</h2>
  929. <?php
  930. if ($deleteFiles && ($deletedDirs || $deletedFiles)):
  931. ?>
  932. <h4>Ponadto usunięto <?=$deletedDirs?> katalogów oraz <?=$deletedFiles?> plików.</h4>
  933. <?php
  934. endif;
  935. ?>
  936. <br/><a href="<?=$this->REFERER?>" class="btn btn-primary" style="width: 80px;">Powrót</a>
  937. </div>
  938. <?php
  939. } catch (Exception $e) {
  940. SE_Layout::alert('danger', $e->getMessage());
  941. }
  942. }
  943. private function clearTable_form() {
  944. if (!isset($this->clearTable_tables[$this->SOURCE['TABLE']])) SE_Layout::alert('danger', 'Błąd parametru');
  945. $a = rand(10, 50);
  946. $b = rand(10, 50);
  947. if ($a == $b) $op = 1;
  948. else $op = rand(0, 1);
  949. if ($op) {
  950. $suma = $a + $b;
  951. $string = "{$a} + {$b}";
  952. } else {
  953. if ($a < $b) {
  954. $suma = $b - $a;
  955. $string = "{$b} - {$a}";
  956. } else {
  957. $suma = $a - $b;
  958. $string = "{$a} - {$b}";
  959. }
  960. }
  961. $string .= " = ";
  962. $_SESSION['_BiAuditGenerate_ctrl'] = base64_encode(gzcompress($suma));
  963. $im = imagecreate((strlen($string) - 1) * 10, 24);
  964. $bg = imagecolorallocate($im, 255, 255, 255);
  965. $textcolor = imagecolorallocate($im, 0, 0, 0);
  966. imagestring($im, 5, 0, 0, $string, $textcolor);
  967. ob_start();
  968. imagepng($im);
  969. $image = ob_get_contents();
  970. ob_end_clean();
  971. /*
  972. $image = new Imagick();
  973. $draw = new ImagickDraw();
  974. $pixel = new ImagickPixel('white');
  975. $image->newImage(200, 24, $pixel);
  976. // $image->setFont("schema/WPS_Functions/mapserver_gml_to_png/map/fonts/Arial_Bold.ttf");
  977. // $image->newPseudoImage(100, 100, "label:\"{$a} {$op} {$b}\"");
  978. // $image->newPseudoImage(100, 100, "caption:Hello");
  979. $image->setImageFormat('png');
  980. $draw->setFillColor('black');
  981. // $draw->setFont('Arial');
  982. $draw->setFontSize(24);
  983. $image->annotateImage($draw, 0, 24, 0, $s);
  984. $image->trimImage(0);
  985. */
  986. $imageBase64 = base64_encode($image);
  987. //echo $imageBase64;
  988. ?>
  989. <div style="text-align: center;">
  990. <h2>Czy jesteś pewien, że chcesz usunąć<br/><b>wszystkie dane</b> z tabeli <?=$this->clearTable_tables[$this->SOURCE['TABLE']]?>?</h2><br/>
  991. <h3>Podaj wynik działania:</h3>
  992. <form method="post">
  993. <img src="data:image/png;base64,<?=$imageBase64?>" height="36px"/><input type="text" name="wynik" style="font-size: 24px; width: 50px;" pattern="^[0-9]{1,3}$" oninvalid="setCustomValidity('Nieprawidłowy format')" maxlength="3" autofocus required autocomplete="off"/><br/><br/>
  994. <?php
  995. if ($this->SOURCE['TABLE'] == 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA'):
  996. ?>
  997. <h4><input type="checkbox" name="deleteFiles"/>&nbsp;&nbsp;Usuń również wszystkie pliki</h4><br/>
  998. <?php
  999. endif;
  1000. ?>
  1001. <button type="submit" class="btn btn-primary" name="action" value="doClearTable" style="width: 80px;">Tak</button>
  1002. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>">
  1003. <a href="<?=$this->REFERER?>" class="btn btn-default" style="width: 80px;">Anuluj</a>
  1004. </form>
  1005. </div>
  1006. <?php
  1007. }
  1008. private function clearTable() {
  1009. $this->clearTable_tables = [
  1010. 'BI_audit_ENERGA_PRACOWNICY' => 'pracowników',
  1011. 'BI_audit_ENERGA_PRACOWNICY_import' => 'pracowników (import)',
  1012. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => 'kontrahentów',
  1013. 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA' => 'raportów',
  1014. 'BI_audit_ENERGA_RUM_UMOWY' => 'umów',
  1015. 'BI_audit_ENERGA_FAKTURY' => 'faktur',
  1016. ];
  1017. $query = "select count(*) from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` where `FILE_STATUS` = 'IN_PROGRESS'";
  1018. if (DB::getPDO()->fetchValue($query)) {
  1019. ?>
  1020. <div style="text-align: center;">
  1021. <h2>Nie można usunąć żadnych danych<br/>(wykryto uruchomione zadania)</h2><br/>
  1022. <a href="<?=$this->REFERER?>" class="btn btn-primary" style="width: 80px;">Powrót</a>
  1023. </div>
  1024. <?php
  1025. return;
  1026. }
  1027. $action = V::get('action', '', $_POST);
  1028. switch ($action) {
  1029. case "doClearTable":
  1030. $this->clearTable_do();
  1031. break;
  1032. default: $this->clearTable_form();
  1033. }
  1034. }
  1035. private function benford_getDetails($a = null, $b = null) {
  1036. try {
  1037. if (!($benford = V::get('benford', '', $_SESSION))) throw new Exception("Nieznany błąd wewnętrzny #1");
  1038. if (isset($benford[$this->SOURCE['TABLE']]['details'][$a][$b])) throw new Exception(@gzuncompress($benford[$this->SOURCE['TABLE']]['details'][$a][$b]));
  1039. if (!($benford = @unserialize(@gzuncompress($benford[$this->SOURCE['TABLE']]['data'])))) throw new Exception("Nieznany błąd wewnętrzny #2");
  1040. if (!($groupField = V::get('_benfordGroupField', '', $_GET))) throw new Exception("Brak konfiguracji kolumny grupującej");
  1041. if ($a === null) throw new Exception("Nieznany błąd wewnętrzny #3");
  1042. if ($b === null) {
  1043. if (!isset($benford['firstStep'][$a]['keys'])) throw new Exception("Nieznany błąd wewnętrzny #4");
  1044. $keys = $benford['firstStep'][$a]['keys'];
  1045. } else {
  1046. if (!isset($benford['secondStep'][$a][$b]['keys'])) throw new Exception("Nieznany błąd wewnętrzny #5");
  1047. $keys = $benford['secondStep'][$a][$b]['keys'];
  1048. }
  1049. $tempTable = uniqid('_temp_benford_ids_');
  1050. DB::getPDO()->query("create temporary table `{$tempTable}` (`ID` int(11) NOT NULL, UNIQUE KEY `ID` (`ID`))");
  1051. foreach (array_chunk($keys, 100) as $ids) {
  1052. DB::getPDO()->query("insert into `{$tempTable}` values (" . implode('),(', $ids) . ")");
  1053. }
  1054. $query = "select `table`.`{$groupField}` as `field`, count(*) as `count` from `{$this->SOURCE['TABLE']}` `table` join `{$tempTable}` `temp` on `table`.`ID` = `temp`.`ID` where coalesce(`table`.`{$groupField}`,'') != '' group by `table`.`{$groupField}` having `count` > 1 order by `count` desc limit 10";
  1055. try {
  1056. $result = DB::getPDO()->fetchAll($query);
  1057. } catch (Exception $e) {
  1058. throw new Exception("Nieznany błąd, prawdopodobnie błędna konfiguracja kolumny grupującej");
  1059. }
  1060. $showDetails = "<h4>Najczęściej występujące wartości kolumny {$groupField}</h4>";
  1061. if ($result) {
  1062. $showDetails .= "<table class=\"table table-bordered table-hover table-striped table-condensed\"><thead><tr style=\"font-weight:bold;\"><td>Wartość</td><td>Liczba wystąpień</td><td>Procent występowania</td></tr></thead><tbody>";
  1063. $showDetails .= implode('', array_map(function($v) use ($keys) {
  1064. return "<tr><td>{$v['field']}</td><td>{$v['count']}</td><td>" . number_format(round($v['count'] / count($keys) * 100, 3), 3, ',', '') . "</td></tr>";
  1065. }, $result));
  1066. $showDetails .= "</tbody></table>";
  1067. } else {
  1068. $showDetails .= "<h5>Żadna wartość nie występuje wiele razy</h5>";
  1069. }
  1070. } catch (Exception $e) {
  1071. $showDetails = $e->getMessage();
  1072. }
  1073. $_SESSION['benford'][$this->SOURCE['TABLE']]['details'][$a][$b] = gzcompress($showDetails);
  1074. $showDetails .= '<button type="submit" class="btn btn-primary btn-sm" onClick="hideDetails()">Zamknij</button>';
  1075. return $showDetails;
  1076. }
  1077. private function benford_form($edit = false) {
  1078. if (!($valueField = V::get('_benfordValueField', '', $_GET))) throw new Exception ("Błąd konfiguracji UrlAction - brak parametru _benfordField (DANE )");
  1079. if (!($namespace = V::get('_fromNamespace', '', $_GET))) throw new Exception("Błąd formularza");
  1080. Lib::loadClass('FeatureAttrSelected');
  1081. $count = FeatureAttrSelected::getTotalSelected($namespace);
  1082. $selectedTable = FeatureAttrSelected::getAttributeTableName($namespace, User::getID());
  1083. $query = "select `t`.`ID`, `{$valueField}` from `{$this->SOURCE['TABLE']}` `t` join `{$selectedTable}` `s` on `t`.`ID` = `s`.`primaryKey` where `t`.`{$valueField}` != 0 order by `s`.`primaryKey`";
  1084. $values = [];
  1085. try {
  1086. $result = DB::getPDO()->fetchAll($query);
  1087. foreach ($result as $row) $values[$row['ID']] = $row[$valueField];
  1088. } catch (Exception $e) {
  1089. throw new Exception("Błąd zapytania SQL ({$e->getMessage()})");
  1090. }
  1091. if (!$values) throw new Exception("Nie wybrano żadnych obiektów lub wszystkie wybrane obiekty mają zerową wartość");
  1092. Lib::loadClass('Benford');
  1093. try {
  1094. $benfordObj = new Benford($values);
  1095. $benford = $benfordObj->getAllResult();
  1096. $_SESSION['benford'][$this->SOURCE['TABLE']] = ['data' => gzcompress(serialize($benford))];
  1097. } catch (Exception $e) {
  1098. die($e->getMessage());
  1099. }
  1100. ?>
  1101. <div class="container" style="margin-top:20px">
  1102. <form method="post">
  1103. <input type="hidden" name="count" value="<?=count($values)?>">
  1104. <legend>
  1105. Analiza rozkładu Benford'a
  1106. <span class="pull-right">Tabela: <?=$this->SOURCE['TABLE']?></span>
  1107. </legend>
  1108. <div class="form-group">
  1109. <div class="col-sm-12">
  1110. <h5>Analiza na podstawie kolumny <?=$valueField?>. Liczba znalezionych obiektów z niezerową wartością: <?=count($values)?> (wybrano obiektów: <?=$count?>)</h5>
  1111. </div>
  1112. </div>
  1113. <?php if($edit):?>
  1114. <div class="form-group">
  1115. <div class="col-sm-12">
  1116. <center>
  1117. <h3>Generowanie raportu analizy rozkładu Benford'a</h3>
  1118. <table>
  1119. <tr>
  1120. <td>
  1121. <select name="step" class="form-control" onChange="toggleStep(this)">
  1122. <option value="first" selected>Pierwszy stopień analizy</option>
  1123. <option value="second">Drugi stopień analizy</option>
  1124. </select>
  1125. </td>
  1126. <td>&nbsp;&nbsp;</td>
  1127. <td><input type="text" class="form-control" name="L_APPOITMENT_INFO" title="Tytuł raportu" placeholder="Tytuł raportu" required/ size="50"></td>
  1128. <td>&nbsp;&nbsp;</td>
  1129. <td><button type="submit" class="btn btn-primary" name="action" value="generate" style="width: 80px;">Generuj</button></td>
  1130. </tr>
  1131. </table>
  1132. </center>
  1133. <br/><br/>
  1134. </div>
  1135. </div>
  1136. <?php endif;?>
  1137. <div class="form-group" id="benford">
  1138. <div class="col-sm-offset-2 col-sm-8">
  1139. <table class="table table-bordered table-hover table-striped table-condensed" id="benford">
  1140. <thead style="text-align:center; font-weight:bold; background-color:lightgray">
  1141. <tr>
  1142. <td style="vertical-align:middle;" rowspan="2">Pierwsze cyfry</td>
  1143. <td style="vertical-align:middle;" rowspan="2">Stopień analizy</td>
  1144. <td style="vertical-align:middle;" rowspan="2">Liczba wystąpień</td>
  1145. <td style="vertical-align:middle;" rowspan="2">Procent występowania</td>
  1146. <td colspan="3">Rozkład Benford'a</td>
  1147. <td style="vertical-align:middle;" rowspan="2">Szczegóły</td>
  1148. <?php if($edit):?>
  1149. <td style="vertical-align:middle;" rowspan="2">Załącz obiekty<br/>do&nbsp;raportu</td>
  1150. <?php endif;?>
  1151. </tr>
  1152. <tr>
  1153. <td nowrap>Norma (%)</td>
  1154. <td nowrap>Odchylenie od&nbsp;normy (%)</td>
  1155. <td>Zgodność</td>
  1156. </tr>
  1157. </thead>
  1158. <tbody>
  1159. <?php
  1160. $number_format = function($n) {
  1161. return number_format($n, 3, ',', '');
  1162. };
  1163. for ($ka = 1; $ka < 10; $ka++) {
  1164. if (!isset($benford['firstStep'][$ka])) $benford['firstStep'][$ka] = ['count' => 0, 'value' => 0, 'correct' => true];
  1165. $va = $benford['firstStep'][$ka];
  1166. $odchylenie = round(($va['value'] / Benford::benford($ka) - 1) * 100, 3);
  1167. if ($odchylenie > 0) $odchylenie = "+" . $number_format($odchylenie);
  1168. else $odchylenie = $number_format($odchylenie);
  1169. ?>
  1170. <tr style="text-align:center; font-weight:bold;<?=$va['correct'] ? '' : ' cursor:pointer;'?>"<?=$va['correct'] ? '' : ' onClick="toggleSecondStep(' . $ka . ');"'?>>
  1171. <td style="text-align:left" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$ka?></td>
  1172. <td class="step1-<?=$va['correct'] ? 'green' : 'red'?>">I</td>
  1173. <td style="text-align:right" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$va['count']?></td>
  1174. <td style="text-align:right" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$number_format(round($va['value'] * 100, 3))?></td>
  1175. <td style="text-align:right" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$number_format(round(Benford::benford($ka) * 100, 3))?></td>
  1176. <td style="text-align:right" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$odchylenie?></td>
  1177. <td <?=$va['correct'] ? 'class="step1-green">Tak' : 'class="step1-red" name="firstStepDesc" data-ka="' . $ka . '" nowrap>Nie (rozwiń)'?></td>
  1178. <td<?=$va['correct'] ? '>' : ' onClick="showDetails(' . $ka . ', 0)"><span class="glyphicon glyphicon-search"></span>'?></td>
  1179. <?php if($edit):?>
  1180. <td<?=$va['correct'] ? '' : ' onClick="_click(\'checkFirstStep_' . $ka . '\')"'?>><input type="checkbox" <?=$va['correct'] ? 'disabled' : 'checked id="checkFirstStep_' . $ka . '" name="checkFirstStep[]" value="' . $ka . '" onClick="toggleCheckFirst(this)"'?>></td>
  1181. <?php endif;?>
  1182. </tr>
  1183. <?php
  1184. if (!$va['correct']) {
  1185. for ($kb = 0; $kb < 10; $kb++) {
  1186. if (!isset($benford['secondStep'][$ka][$kb])) $benford['secondStep'][$ka][$kb] = ['count' => 0, 'value' => 0, 'correct' => true];
  1187. $vb = $benford['secondStep'][$ka][$kb];
  1188. $odchylenie = round(($vb['value'] / Benford::benford($ka * 10 + $kb) - 1) * 100, 3);
  1189. if ($odchylenie > 0) $odchylenie = "+" . $number_format($odchylenie);
  1190. else $odchylenie = $number_format($odchylenie);
  1191. ?>
  1192. <tr style="text-align:center;" name="secondStep" data-ka="<?=$ka?>" hidden>
  1193. <td style="text-align:left" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$ka . $kb?></td>
  1194. <td class="step2-<?=$vb['correct'] ? 'green' : 'red'?>">II</td>
  1195. <td style="text-align:right" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$vb['count']?></td>
  1196. <td style="text-align:right" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$number_format(round($vb['value'] * 100, 3))?></td>
  1197. <td style="text-align:right" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$number_format(round(Benford::benford($ka * 10 + $kb) * 100, 3))?></td>
  1198. <td style="text-align:right" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$odchylenie?></td>
  1199. <td class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$vb['correct'] ? 'Tak' : 'Nie'?></td>
  1200. <td<?=$vb['correct'] ? '>' : ' style="cursor:pointer;" onClick="showDetails(' . "{$ka}, {$kb}" . ')"><span class="glyphicon glyphicon-search"></span>'?></td>
  1201. <?php if($edit):?>
  1202. <td<?=$vb['correct'] ? '' : ' style="cursor:pointer;" onClick="_click(\'checkSecondStep_' . $ka . $kb . '\')"'?>><input type="checkbox"<?=$vb['correct'] ?: ' checked id="checkSecondStep_' . $ka . $kb . '" name="checkSecondStep[]" value="' . $ka . $kb . '" onClick="toggleCheckSecond(this)"'?> disabled></td>
  1203. <?php endif;?>
  1204. </tr>
  1205. <?php
  1206. }
  1207. }
  1208. }
  1209. ?>
  1210. </tbody>
  1211. </table>
  1212. </div>
  1213. </div>
  1214. </form>
  1215. </div>
  1216. <div id="details" onClick="hideDetails();">
  1217. <div id="detailsMsg" onClick="event.stopPropagation();"></div>
  1218. </div>
  1219. <style type="text/css">
  1220. <!--
  1221. #benford .step1-green,#benford .step1-red {font-weight:bold;}
  1222. #benford .step1-green,#benford .step2-green {color:#008800;}
  1223. #benford .step1-red,#benford .step2-red {color:#ff0000;}
  1224. #benford table { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;}
  1225. td {font-size: 12px;}
  1226. #benford ::selection {background: transparent;}
  1227. #details {display:none; position: fixed; left: 0; top: 0; width: 100%; height: 100%; text-align: center; z-index: 1000; background-color: rgba(0,0,0,0.5);}
  1228. #details div {width: 500px; height: auto; margin: 100px auto; background: #fff; padding: 10px; text-align: center; overflow: hidden;}
  1229. -->
  1230. </style>
  1231. <script language="JavaScript">
  1232. <!--
  1233. function showDetails(ka, kb) {
  1234. event.stopPropagation();
  1235. document.getElementById('detailsMsg').innerHTML = "<h4>Proszę czekać...</h4>";
  1236. document.getElementById('details').style.display = 'block';
  1237. var post = "_noMenu=1&action=getDetails&_ka=" + ka;
  1238. if (kb) post += "&_kb=" + kb;
  1239. var xhttp = new XMLHttpRequest();
  1240. xhttp.open("POST", '', true);
  1241. xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  1242. xhttp.onreadystatechange = function() {
  1243. if (this.readyState == 4 && this.status == 200) {
  1244. document.getElementById('detailsMsg').innerHTML = this.responseText;
  1245. }
  1246. }
  1247. xhttp.send(post);
  1248. }
  1249. function hideDetails() {
  1250. document.getElementById('details').style.display = 'none';
  1251. }
  1252. function _click(id) {
  1253. event.stopPropagation();
  1254. document.getElementById(id).click();
  1255. }
  1256. function toggleSecondStep(ka) {
  1257. var rows = document.getElementsByName('secondStep');
  1258. var hidden = false;
  1259. for(var i = 0, n = rows.length; i < n; i++) {
  1260. if (rows[i].dataset.ka == ka) {
  1261. rows[i].hidden = !rows[i].hidden;
  1262. hidden = rows[i].hidden;
  1263. }
  1264. }
  1265. var descs = document.getElementsByName('firstStepDesc');
  1266. for(var i = 0, n = descs.length; i < n; i++) {
  1267. if (descs[i].dataset.ka == ka) {
  1268. descs[i].innerHTML = (hidden ? 'Nie (rozwiń)' : 'Nie (zwiń)');
  1269. }
  1270. }
  1271. }
  1272. function toggleStep(option) {
  1273. if (option.value == 'first') first = true;
  1274. else if (option.value == 'second') first = false;
  1275. else {
  1276. alert('Wystąpił nieznany błąd formularza');
  1277. return;
  1278. }
  1279. var checks = document.getElementsByName('checkSecondStep[]');
  1280. var all = [];
  1281. for(var i = 0, n = checks.length; i < n; i++) {
  1282. checks[i].disabled = first;
  1283. ka = checks[i].value / 10 | 0;
  1284. if (all[ka] === 'undefined') all[ka] = checks[i].checked;
  1285. else if (checks[i].checked) all[ka] = true;
  1286. }
  1287. var checks = document.getElementsByName('checkFirstStep[]');
  1288. for(var i = 0, n = checks.length; i < n; i++) {
  1289. checks[i].disabled = !(first);
  1290. if (checks[i].checked != all[checks[i].value]) {
  1291. checks[i].checked = all[checks[i].value];
  1292. toggleCheckFirst(checks[i]);
  1293. }
  1294. }
  1295. var descs = document.getElementsByName('firstStepDesc');
  1296. for(var i = 0, n = descs.length; i < n; i++) {
  1297. descs[i].innerHTML = (first ? 'Nie (rozwiń)' : 'Nie (zwiń)');
  1298. }
  1299. var rows = document.getElementsByName('secondStep');
  1300. for(var i = 0, n = rows.length; i < n; i++) {
  1301. rows[i].hidden = first;
  1302. }
  1303. }
  1304. function toggleCheckFirst(check) {
  1305. event.stopPropagation();
  1306. var checks = document.getElementsByName('checkSecondStep[]');
  1307. for(var i = 0, n = checks.length; i < n; i++) {
  1308. if ((checks[i].value / 10 | 0) == check.value) checks[i].checked = check.checked;
  1309. }
  1310. }
  1311. function toggleCheckSecond(check) {
  1312. event.stopPropagation();
  1313. var checks = document.getElementsByName('checkSecondStep[]');
  1314. var all = true;
  1315. var ka = check.value / 10 | 0;
  1316. for(var i = 0, n = checks.length; i < n; i++) {
  1317. if ((checks[i].value / 10 | 0) == ka) {
  1318. if (!checks[i].checked) {
  1319. all = false;
  1320. break;
  1321. }
  1322. }
  1323. }
  1324. var checks = document.getElementsByName('checkFirstStep[]');
  1325. for(var i = 0, n = checks.length; i < n; i++) {
  1326. if (checks[i].value == ka) {
  1327. checks[i].checked = all;
  1328. break;
  1329. }
  1330. }
  1331. }
  1332. -->
  1333. </script>
  1334. <?php
  1335. }
  1336. private function benford_generate() {
  1337. $benford = @unserialize(@gzuncompress(V::get('benford', '', $_SESSION)[$this->SOURCE['TABLE']]['data']));
  1338. unset($_SESSION['benford'][$this->SOURCE['TABLE']]);
  1339. if (!$benford) {
  1340. $this->benford_form(true);
  1341. return;
  1342. }
  1343. $root = 'RelatedFeatureRoot';
  1344. $namespace = 'BI_audit_BENFORD';
  1345. $array = [];
  1346. $array['@attributes'] = ['xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd'];
  1347. $array[$namespace] = [
  1348. '@attributes' => ['fid' => "{$namespace}.1"],
  1349. 'ID' => 1,
  1350. 'L_APPOITMENT_INFO' => V::get('L_APPOITMENT_INFO', '', $_POST),
  1351. 'step' => V::get('step', '', $_POST),
  1352. 'table' => $this->SOURCE['TABLE'],
  1353. 'count' => V::get('count', '', $_POST),
  1354. ];
  1355. $firstStep = [];
  1356. for ($ka = 1; $ka <= 9; $ka++) {
  1357. if (!isset($benford['firstStep'][$ka])) $va = ['count' => 0, 'value' => 0, 'correct' => true];
  1358. else $va = $benford['firstStep'][$ka];
  1359. $_firstStep = [
  1360. '@attributes' => ['leadingNumber' => $ka],
  1361. 'count' => $va['count'],
  1362. 'value' => $va['value'],
  1363. 'correct' => $va['correct'] ? 'true' : 'false'
  1364. ];
  1365. if ($array[$namespace]['step'] == 'second') {
  1366. $secondStep = [];
  1367. for ($kb = 0; $kb <= 9; $kb++) {
  1368. if (!isset($benford['secondStep'][$ka][$kb])) $vb = ['count' => 0, 'value' => 0, 'correct' => true];
  1369. else $vb = $benford['secondStep'][$ka][$kb];
  1370. $_secondStep = [
  1371. '@attributes' => ['leadingNumber' => $ka.$kb],
  1372. 'count' => $vb['count'],
  1373. 'value' => $vb['value'],
  1374. 'correct' => $vb['correct'] ? 'true' : 'false'
  1375. ];
  1376. if (!$vb['correct']) {
  1377. $objects = [];
  1378. foreach ($benford['secondStep'][$ka][$kb]['keys'] as $id) {
  1379. $object = DB::getPDO()->fetchFirst("select * from `{$this->SOURCE['TABLE']}` where `ID` = " . DB::getPDO()->quote($id));
  1380. if (!$object) continue;
  1381. $objects[] = array_merge(['@attributes' => ['fid' => "{$this->SOURCE['TABLE']}.{$id}"]], $object);
  1382. }
  1383. $_secondStep[$this->SOURCE['TABLE']][] = $objects;
  1384. }
  1385. $secondStep[] = $_secondStep;
  1386. }
  1387. $_firstStep['secondStep'] = $secondStep;
  1388. } elseif (!$va['correct']) {
  1389. $objects = [];
  1390. foreach ($benford['firstStep'][$ka]['keys'] as $id) {
  1391. $object = DB::getPDO()->fetchFirst("select * from `{$this->SOURCE['TABLE']}` where `ID` = " . DB::getPDO()->quote($id));
  1392. if (!$object) continue;
  1393. $objects[] = array_merge(['@attributes' => ['fid' => "{$this->SOURCE['TABLE']}.{$id}"]], $object);
  1394. }
  1395. $_firstStep[$this->SOURCE['TABLE']][] = $objects;
  1396. }
  1397. $firstStep[] = $_firstStep;
  1398. }
  1399. $array[$namespace]['firstStep'] = $firstStep;
  1400. $xml = V::arrayToXML($array, true, $root);
  1401. file_put_contents("/tmp/benford_{$array[$namespace]['step']}Step.xml", $xml);
  1402. ?>
  1403. <pre><?//=htmlspecialchars($xml)?></pre>
  1404. <br><br>
  1405. <div style="text-align:center">
  1406. <a href="<?=$this->REFERER?>" class="btn btn-default" style="width: 80px;">Powrót</a>
  1407. </div>
  1408. <?php
  1409. }
  1410. private function benford() {
  1411. try {
  1412. $action = V::get('action', '', $_POST);
  1413. switch ($action) {
  1414. case "generate":
  1415. $this->benford_generate();
  1416. break;
  1417. case "getDetails":
  1418. $ka = V::get('_ka', null, $_POST, 'int');
  1419. $kb = V::get('_kb', null, $_POST, 'int');
  1420. echo $this->benford_getDetails($ka, $kb);
  1421. break;
  1422. default:
  1423. $this->benford_form(true);
  1424. }
  1425. } catch (Exception $e) {
  1426. SE_Layout::alert('danger', $e->getMessage());
  1427. }
  1428. }
  1429. public function defaultAction() {
  1430. $showMenu = !(V::get('_noMenu', false, $_POST));
  1431. if ($showMenu) {
  1432. SE_Layout::gora();
  1433. SE_Layout::menu();
  1434. }
  1435. if (isset($_SESSION['REFERER'])) {
  1436. $this->REFERER = $_SESSION['REFERER'];
  1437. unset($_SESSION['REFERER']);
  1438. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  1439. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  1440. if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
  1441. elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
  1442. elseif (($ID = V::get('ID_BI_audit_KRS', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  1443. elseif (($ID = V::get('ID_BI_audit_MSIG', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_MSIG';
  1444. elseif (($ID = V::get('ID_BI_audit_KRS_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS_person';
  1445. if ($this->SOURCE) {
  1446. $this->SOURCE['ID'] = $ID;
  1447. $this->powiazania();
  1448. }
  1449. elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
  1450. $this->SOURCE['TABLE'] = ACL::getAclByTypeName($TABLE)->getRootTableName();
  1451. $_subUrlAction = V::get('_subUrlAction', '', $_GET);
  1452. switch ($this->SOURCE['TABLE']) {
  1453. case "BI_audit_ENERGA_PRACOWNICY":
  1454. switch ($_subUrlAction) {
  1455. case "clearTable":
  1456. $this->clearTable();
  1457. break;
  1458. case "importFromKRS":
  1459. $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  1460. $this->importToPracownicy();
  1461. break;
  1462. default: SE_Layout::alert('danger', 'Błąd parametru #21');
  1463. }
  1464. break;
  1465. case "BI_audit_ENERGA_PRACOWNICY_import":
  1466. switch ($_subUrlAction) {
  1467. case "clearTable":
  1468. $this->clearTable();
  1469. break;
  1470. default: SE_Layout::alert('danger', 'Błąd parametru #22');
  1471. }
  1472. break;
  1473. case "BI_audit_ENERGA_RUM_KONTRAHENCI":
  1474. switch ($_subUrlAction) {
  1475. case "clearTable":
  1476. $this->clearTable();
  1477. break;
  1478. default: SE_Layout::alert('danger', 'Błąd parametru #23');
  1479. }
  1480. break;
  1481. case "BI_audit_ENERGA_RUM_UMOWY":
  1482. switch ($_subUrlAction) {
  1483. case "clearTable":
  1484. $this->clearTable();
  1485. break;
  1486. case "benford":
  1487. $this->benford();
  1488. break;
  1489. default: SE_Layout::alert('danger', 'Błąd parametru #24');
  1490. }
  1491. break;
  1492. case "BI_audit_ENERGA_FAKTURY":
  1493. switch ($_subUrlAction) {
  1494. case "clearTable":
  1495. $this->clearTable();
  1496. break;
  1497. case "benford":
  1498. $this->benford();
  1499. break;
  1500. default: SE_Layout::alert('danger', 'Błąd parametru #25');
  1501. }
  1502. break;
  1503. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  1504. switch ($_subUrlAction) {
  1505. case "clearTable":
  1506. $this->clearTable();
  1507. break;
  1508. default: SE_Layout::alert('danger', 'Błąd parametru #25');
  1509. }
  1510. break;
  1511. default:
  1512. switch ($_subUrlAction) {
  1513. case "benford":
  1514. $this->benford();
  1515. break;
  1516. default: SE_Layout::alert('danger', 'Błąd parametru #1');
  1517. }
  1518. }
  1519. }
  1520. else SE_Layout::alert('danger', 'Błąd parametru #0');
  1521. if ($showMenu) {
  1522. echo "<br/><br/>";
  1523. SE_Layout::dol();
  1524. }
  1525. }
  1526. private static function truncatePowiazaniaFromDB($ID) {
  1527. $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  1528. if (!$refTables) return null;
  1529. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  1530. $refTables = array_diff($refTables, [$refPowiazaniaToPowiazaniaRow]);
  1531. $query = "delete from `" . implode("`, `", $refTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  1532. foreach ($refTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  1533. $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  1534. DB::getPDO()->query($query);
  1535. }
  1536. private static function deleteResultsFromDB($ID) {
  1537. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  1538. $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
  1539. $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  1540. $sqlDeleteFrom = "delete from
  1541. `{$refPowiazaniaToPowiazaniaRow}`,
  1542. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
  1543. `{$refPowiazaniaRowToPowiazaniaRowObject}`,
  1544. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
  1545. $sqlUsing = "
  1546. using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  1547. join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
  1548. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
  1549. join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
  1550. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
  1551. $sqlWhere = "
  1552. where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  1553. foreach ($refTables as $refTable) {
  1554. $sqlDeleteFrom .= ",\n`{$refTable}`";
  1555. $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  1556. }
  1557. $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
  1558. DB::getPDO()->query($query);
  1559. }
  1560. public function doGenerate() {
  1561. $generatePhpScript = function($function) {
  1562. return '<?php
  1563. ini_set("memory_limit", "4G");
  1564. define("DS", DIRECTORY_SEPARATOR);
  1565. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  1566. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  1567. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  1568. ini_set("display_startup_errors", "0");
  1569. ini_set("display_errors", "1");
  1570. ini_set("log_errors", "1");
  1571. ini_set("error_log", "/var/log/apache2/error_log");
  1572. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  1573. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  1574. date_default_timezone_set("Europe/Warsaw");
  1575. Lib::loadClass("Router");
  1576. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  1577. ';
  1578. };
  1579. try {
  1580. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  1581. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  1582. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  1583. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  1584. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  1585. ### Ustawienie zmiennych
  1586. $powiazaniaDirLocation = self::getMainDirectory();
  1587. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1588. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  1589. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1590. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1591. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  1592. ### Utworzenie niezbędnych katalogów i plików
  1593. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0770, true);
  1594. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  1595. ### Wyłączenie wcześniej używanego mechanizmu wymuszania częściowego (oraz pełnego od 2018-04-19) odświeżania cache - teraz działa to z automatu
  1596. $sqlArr = [
  1597. 'BI_analiza_reloadCache' => 'No',
  1598. ];
  1599. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Part', 'Full') and FILE_STATUS = 'TO_GENERATE'";
  1600. $result = DB::getPDO()->fetchAll($query);
  1601. foreach ($result as $row) {
  1602. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  1603. }
  1604. /* 2018-04-19 - zmieniono działanie silnika tak, aby sam wykrywał czy należy wykonać pełne odświeżenie cache
  1605. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  1606. $doGenerate = true;
  1607. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full') and FILE_STATUS = 'TO_GENERATE'";
  1608. $result = DB::getPDO()->fetchAll($query);
  1609. if ($result) {
  1610. $doGenerate = false;
  1611. $sqlArr = [];
  1612. if (file_exists($reloadCachePhpFile)) {
  1613. if (file_exists($reloadCacheResultFile)) {
  1614. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  1615. if ($reloadCacheResult == "ok") {
  1616. $sqlArr = [
  1617. 'FILE_STATUS_info' => 'Ukończono pełne Odświeżenie cache, oczekiwanie na wygenerowanie powiązań',
  1618. 'BI_analiza_reloadCache' => 'No',
  1619. ];
  1620. $doGenerate = true;
  1621. } else {
  1622. $sqlArr = [
  1623. 'FILE_STATUS' => 'ERROR',
  1624. 'FILE_STATUS_info' => "Wystąpił błąd podczas pełnego odświeżania cache ({$reloadCacheResult})",
  1625. ];
  1626. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  1627. $result = DB::getPDO()->fetchAll($query);
  1628. }
  1629. unlink($reloadCachePhpFile);
  1630. unlink($reloadCachePidFile);
  1631. unlink($reloadCacheResultFile);
  1632. } elseif (file_exists($reloadCachePidFile)) {
  1633. $pid = file_get_contents($reloadCachePidFile);
  1634. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1635. $processShouldBeRunning = "php {$reloadCachePhpFile}";
  1636. if ($processRunning != $processShouldBeRunning) {
  1637. if (!file_exists($reloadCacheResultFile)) {
  1638. $sqlArr = [
  1639. 'FILE_STATUS' => 'ERROR',
  1640. 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas pełnego odświeżania cache - nie znaleziono procesu potomnego",
  1641. ];
  1642. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  1643. $result = DB::getPDO()->fetchAll($query);
  1644. unlink($reloadCachePhpFile);
  1645. unlink($reloadCachePidFile);
  1646. unlink($reloadCacheResultFile);
  1647. }
  1648. }
  1649. }
  1650. } else {
  1651. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1652. $result2 = DB::getPDO()->fetchValue($query);
  1653. if ($result2) {
  1654. $sqlArr = [
  1655. 'FILE_STATUS_info' => 'Wstrzymano pełne odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  1656. ];
  1657. } else {
  1658. $sqlArr = [
  1659. 'FILE_STATUS_info' => 'W trakcie pełnego odświeżania cache',
  1660. ];
  1661. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
  1662. $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
  1663. file_put_contents($reloadCachePhpFile, $generatePhpScript("doReloadCache({$fullReloadCache})"));
  1664. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  1665. }
  1666. }
  1667. if ($sqlArr) {
  1668. foreach ($result as $row) {
  1669. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  1670. }
  1671. }
  1672. }
  1673. */ $doGenerate = true;
  1674. ### Generowanie powiązań
  1675. if ($doGenerate) {
  1676. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
  1677. $result = DB::getPDO()->fetchAll($query);
  1678. foreach ($result as $row) {
  1679. $sqlArr = [
  1680. 'ID' => $row['ID'],
  1681. 'FILE_STATUS' => 'IN_PROGRESS',
  1682. 'FILE_STATUS_info' => 'Zadanie wyzwolone',
  1683. ];
  1684. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1685. self::deleteResultsFromDB($row['ID']);
  1686. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1687. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1688. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  1689. $generatePowiazaniaProgressFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.progress";
  1690. if (file_exists($generatePowiazaniaResultFile)) unlink ($generatePowiazaniaResultFile);
  1691. if (file_exists($generatePowiazaniaProgressFile)) unlink ($generatePowiazaniaProgressFile);
  1692. file_put_contents($generatePowiazaniaPhpFile, $generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  1693. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  1694. }
  1695. }
  1696. ### Weryfikacja świeżo wygenerowanych powiązań
  1697. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1698. $result = DB::getPDO()->fetchAll($query);
  1699. foreach ($result as $row) {
  1700. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1701. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  1702. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1703. $error = false;
  1704. $success = false;
  1705. $sqlArr = [];
  1706. if (file_exists($generatePowiazaniaResultFile)) {
  1707. $generatePowiazaniaResult = json_decode(file_get_contents($generatePowiazaniaResultFile), true);
  1708. if ($generatePowiazaniaResult['result'] == "ok") {
  1709. $powiazanieDirLocation = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  1710. if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0770, false);
  1711. if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
  1712. else $success = true;
  1713. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult['message']})";
  1714. } elseif (file_exists($generatePowiazaniaPidFile)) {
  1715. $pid = file_get_contents($generatePowiazaniaPidFile);
  1716. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1717. $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
  1718. if ($processRunning != $processShouldBeRunning) {
  1719. if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
  1720. }
  1721. }
  1722. if ($error) {
  1723. $sqlArr = [
  1724. 'FILE_STATUS' => 'ERROR',
  1725. 'FILE_STATUS_info' => $error,
  1726. ];
  1727. //self::deleteResultsFromDB($row['ID']);
  1728. //if (file_exists($xmlFile)) unlink($xmlFile);
  1729. } elseif ($success) {
  1730. $sqlArr = [
  1731. 'FILE_STATUS' => 'GENERATED',
  1732. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  1733. ];
  1734. if ($generatePowiazaniaResult['parts']) {
  1735. for ($i = 1; $i <= $generatePowiazaniaResult['parts']; $i++) {
  1736. $partNo = str_pad($i, 6, '0', STR_PAD_LEFT);
  1737. $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}_{$partNo}";
  1738. $generatePowiazaniaXmlFile = "{$generateFilesName}.xml";
  1739. $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
  1740. $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
  1741. $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
  1742. $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.xml";
  1743. $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.pdf";
  1744. $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}";
  1745. $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}.zip";
  1746. if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
  1747. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1748. if (file_exists($generatePowiazaniaHtmlDir)) {
  1749. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1750. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1751. }
  1752. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1753. }
  1754. } else {
  1755. $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}";
  1756. $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
  1757. $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
  1758. $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
  1759. $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.xml";
  1760. $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.pdf";
  1761. $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}";
  1762. $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}.zip";
  1763. if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
  1764. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1765. if (file_exists($generatePowiazaniaHtmlDir)) {
  1766. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1767. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1768. }
  1769. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1770. }
  1771. }
  1772. if ($sqlArr) {
  1773. $sqlArr['ID'] = $row['ID'];
  1774. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1775. if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
  1776. if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
  1777. if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
  1778. }
  1779. }
  1780. } catch (Exception $e) {
  1781. echo $e->getMessage()."\n";
  1782. }
  1783. }
  1784. private static function importPracownicy($full = false) {
  1785. $fields = [
  1786. 'BI_audit_ENERGA_PRACOWNICY' => [
  1787. 'imiona' => 'imiona',
  1788. 'nazwisko' => 'nazwisko',
  1789. 'pesel' => 'pesel',
  1790. 'jednostka_organizacyjna' => 'jednostka_organizacyjna',
  1791. 'GUID' => 'GUID',
  1792. ],
  1793. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1794. 'kodPocztowy' => 'kodPocztowy',
  1795. 'miejscowosc' => 'miejscowosc',
  1796. 'ulica' => 'ulica',
  1797. 'nrBudynku' => 'nr',
  1798. 'nrLokalu' => 'nrLokalu',
  1799. ],
  1800. ];
  1801. $refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy', true);
  1802. if ($full) DB::getPDO()->query("update `BI_audit_ENERGA_PRACOWNICY_import` set `A_STATUS` = 'WAITING'");
  1803. DB::getPDO()->query("update `BI_audit_ENERGA_PRACOWNICY_import` set `pesel` = null where `A_STATUS` = 'WAITING' and isPesel(`pesel`) = 0");
  1804. $query = "select * from `BI_audit_ENERGA_PRACOWNICY_import` where `A_STATUS` = 'WAITING'";
  1805. $pracownicy = DB::getPDO()->query($query);
  1806. while ($pracownik = $pracownicy->fetch()) {
  1807. if ($pracownik['pesel']) {
  1808. $ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `pesel` = '{$pracownik['pesel']}' or (coalesce(`pesel`, '') = '' and `GUID` = '{$pracownik['GUID']}')");
  1809. } elseif ($pracownik['GUID']) {
  1810. $ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `GUID` = '{$pracownik['GUID']}'");
  1811. } else {
  1812. DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY_import', 'ID', $pracownik['ID'], ['A_STATUS' => 'OFF_SOFT']);
  1813. continue;
  1814. }
  1815. $sqlArr = [];
  1816. $sqlArr['source'] = 'import';
  1817. $sqlArr['cached'] = '0';
  1818. foreach ($fields['BI_audit_ENERGA_PRACOWNICY'] as $tableField => $importField) {
  1819. $sqlArr[$tableField] = trim($pracownik[$importField]);
  1820. if (!$sqlArr[$tableField]) unset($sqlArr[$tableField]);
  1821. }
  1822. if ($ID_pracownik) {
  1823. DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY', 'ID', $ID_pracownik, $sqlArr);
  1824. $full = true;
  1825. }
  1826. else $ID_pracownik = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', $sqlArr);
  1827. $sqlArr = [];
  1828. foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $tableField => $importField) {
  1829. $sqlArr[$tableField] = trim($pracownik[$importField]);
  1830. if (!$sqlArr[$tableField]) unset($sqlArr[$tableField]);
  1831. }
  1832. if (!$sqlArr) {
  1833. DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY_import', 'ID', $pracownik['ID'], ['A_STATUS' => 'OFF_SOFT']);
  1834. continue;
  1835. }
  1836. $sqlWhereArr = [];
  1837. $sqlWhereArr[] = "`{$refTable}`.`PRIMARY_KEY` = '{$ID_pracownik}'";
  1838. foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $tableField => $importField) {
  1839. if (isset($sqlArr[$tableField])) $sqlWhereArr[] = "`BI_audit_ENERGA_PRACOWNICY_adresy`.`{$tableField}` = " . DB::getPDO()->quote($sqlArr[$tableField]);
  1840. else $sqlWhereArr[] = "`{$tableField}` is null";
  1841. }
  1842. $query = "select count(*) from `{$refTable}` join `BI_audit_ENERGA_PRACOWNICY_adresy` on `{$refTable}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_PRACOWNICY_adresy`.`ID` where " . implode(' and ', $sqlWhereArr);
  1843. if (!(DB::getPDO()->fetchValue($query))) {
  1844. $ID_adres = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY_adresy', $sqlArr);
  1845. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $ID_pracownik, 'REMOTE_PRIMARY_KEY' => $ID_adres]);
  1846. }
  1847. DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY_import', 'ID', $pracownik['ID'], ['A_STATUS' => 'NORMAL']);
  1848. }
  1849. return $full;
  1850. }
  1851. private static function reloadCache_parseFakturyUmowy($full = false) {
  1852. $fields = [
  1853. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1854. 'Tytul_dokumentu',
  1855. 'Pelna_nazwa_kontrahenta',
  1856. 'NIP',
  1857. 'REGON',
  1858. 'KRS',
  1859. 'Kraj',
  1860. 'Kod_pocztowy',
  1861. 'Miejscowosc',
  1862. 'Ulica',
  1863. 'Numer_budynku',
  1864. 'Numer_mieszkania_lokalu',
  1865. 'TERYT_SYM',
  1866. 'TERYT_SYM_UL',
  1867. ],
  1868. 'BI_audit_KRS' => [
  1869. '"Zaimportowano z KRS na podstawie faktury/umowy"',
  1870. 'nazwa',
  1871. 'nip',
  1872. 'regon',
  1873. 'krs',
  1874. 'A_kraj',
  1875. 'A_kod',
  1876. 'A_miejscowosc',
  1877. 'A_ulica',
  1878. 'A_nrDomu',
  1879. 'A_nrLokalu',
  1880. 'TERYT_SYM',
  1881. 'TERYT_SYM_UL',
  1882. ],
  1883. 'BI_audit_CEIDG' => [
  1884. '"Zaimportowano z CEiDG na podstawie faktury/umowy"',
  1885. 'firma',
  1886. 'nip',
  1887. 'regon',
  1888. 'null',
  1889. 'kraj',
  1890. 'kodPocztowy',
  1891. 'miejscowosc',
  1892. 'ulica',
  1893. 'budynek',
  1894. 'lokal',
  1895. 'TERYT_SYM',
  1896. 'TERYT_SYM_UL',
  1897. ],
  1898. ];
  1899. $refTableFakturyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_FAKTURY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  1900. $refTableUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  1901. if ($full) {
  1902. DB::getPDO()->query("truncate table `{$refTableFakturyToKontrahenci}`");
  1903. DB::getPDO()->query("truncate table `{$refTableUmowyToKontrahenci}`");
  1904. DB::getPDO()->query("update `BI_audit_ENERGA_FAKTURY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
  1905. DB::getPDO()->query("update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
  1906. }
  1907. $query = "select `ID`, `NIP` from `BI_audit_ENERGA_FAKTURY` where `A_STATUS` = 'WAITING'";
  1908. $result = DB::getPDO()->fetchAll($query);
  1909. foreach ($result as $row) {
  1910. $ID = $row['ID'];
  1911. $nip = trim($row['NIP']);
  1912. if (!$full) {
  1913. $query = "delete from `{$refTableFakturyToKontrahenci}` where PRIMARY_KEY = '{$row['ID']}'";
  1914. DB::getPDO()->query($query);
  1915. }
  1916. if (!$nip) {
  1917. DB::getPDO()->update('BI_audit_ENERGA_FAKTURY', "ID", $ID, ['A_STATUS' => 'OFF_SOFT']);
  1918. continue;
  1919. }
  1920. $K_IDs = [];
  1921. $query = "select `ID` from `BI_audit_ENERGA_RUM_KONTRAHENCI` where `NIP` = '{$nip}'";
  1922. if ($result2 = DB::getPDO()->fetchall($query)) {
  1923. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1924. } else {
  1925. $query = "select ID from BI_audit_KRS where nip = '{$nip}' order by `ID` desc limit 1";
  1926. if ($result2 = DB::getPDO()->fetchall($query)) {
  1927. foreach ($result2 as $item) {
  1928. $query = "insert into `BI_audit_ENERGA_RUM_KONTRAHENCI` (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1929. " select " . implode(', ', $fields['BI_audit_KRS']) . " from `BI_audit_KRS` where `ID` = '{$item['ID']}'";
  1930. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1931. }
  1932. } else {
  1933. $query = "select `ID` from `BI_audit_CEIDG` where `nip` = '{$nip}' order by `ID` desc limit 1";
  1934. if ($result2 = DB::getPDO()->fetchall($query)) {
  1935. foreach ($result2 as $item) {
  1936. $query = "insert into `BI_audit_ENERGA_RUM_KONTRAHENCI` (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1937. " select " . implode(', ', $fields['BI_audit_CEIDG']) . " from `BI_audit_CEIDG` where `ID` = '{$item['ID']}'";
  1938. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1939. }
  1940. }
  1941. }
  1942. }
  1943. foreach ($K_IDs as $K_ID) {
  1944. if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTableFakturyToKontrahenci}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
  1945. DB::getPDO()->query("insert into `{$refTableFakturyToKontrahenci}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`) values ({$ID}, {$K_ID})");
  1946. }
  1947. }
  1948. DB::getPDO()->update('BI_audit_ENERGA_FAKTURY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
  1949. }
  1950. $query = <<<SQL
  1951. update `BI_audit_ENERGA_RUM_UMOWY` set `Wartosc` = replace(
  1952. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_`,
  1953. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_`,
  1954. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_`,
  1955. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_`,
  1956. if(`Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_`, 0))))),
  1957. ',', '.') where `A_STATUS` = 'WAITING';
  1958. SQL;
  1959. DB::getPDO()->query($query);
  1960. $query = "select `ID`, `Kontrahenci` from `BI_audit_ENERGA_RUM_UMOWY` where `A_STATUS` = 'WAITING'";
  1961. $result = DB::getPDO()->fetchAll($query);
  1962. foreach ($result as $row) {
  1963. $ID = $row['ID'];
  1964. if (!$full) {
  1965. $query = "delete from `{$refTableUmowyToKontrahenci}` where PRIMARY_KEY = '{$ID}'";
  1966. DB::getPDO()->query($query);
  1967. }
  1968. $kontrahenci = array_map('trim', explode("|", $row['Kontrahenci']));
  1969. $K_IDs = [];
  1970. foreach ($kontrahenci as $item) {
  1971. $kontrahent = array_map('trim', explode(";", $item));
  1972. $nr = null;
  1973. if (count($kontrahent) == 3) $i = 1;//$nr = $kontrahent[1];
  1974. elseif (count($kontrahent) == 4) $i = 2;//$nr = $kontrahent[2];
  1975. elseif (count($kontrahent) >= 5 && count($kontrahent) <= 6) $i = 3;//$nr = $kontrahent[3];
  1976. else $i = null;
  1977. if ($i) $nr = $kontrahent[$i];
  1978. $notFound = false;
  1979. if (is_numeric($nr)) {
  1980. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Numer_kontrahenta = '{$nr}' and not (NIP is null and REGON is null and KRS is null)";
  1981. if ($K_ID = DB::getPDO()->fetchValue($query)) {
  1982. $K_IDs[] = $K_ID;
  1983. } else {
  1984. $nazwa = $kontrahent[$i+1];
  1985. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Pelna_nazwa_kontrahenta = '" . addslashes($nazwa) . "' and not (NIP is null and REGON is null and KRS is null)";
  1986. if ($result2 = DB::getPDO()->fetchAll($query)) {
  1987. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1988. } else $notFound = true;
  1989. }
  1990. } else $notFound = true;
  1991. if ($notFound) {
  1992. list($nip, $regon) = self::parseNipRegon($item);
  1993. if ($nip || $regon) {
  1994. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where NIP = '{$nip}' or REGON = '{$regon}'";
  1995. if ($result2 = DB::getPDO()->fetchall($query)) {
  1996. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1997. } else {
  1998. $query = "select ID from BI_audit_KRS where nip = '{$nip}' or regon = '{$regon}' order by `ID` desc limit 1";
  1999. if ($result2 = DB::getPDO()->fetchall($query)) {
  2000. foreach ($result2 as $item) {
  2001. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  2002. " select " . implode(', ', $fields['BI_audit_KRS']) . " from BI_audit_KRS where ID = '{$item['ID']}'";
  2003. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  2004. }
  2005. } else {
  2006. $query = "select ID from BI_audit_CEIDG where nip = '{$nip}' or regon = '{$regon}' order by `ID` desc limit 1";
  2007. if ($result2 = DB::getPDO()->fetchall($query)) {
  2008. foreach ($result2 as $item) {
  2009. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  2010. " select " . implode(', ', $fields['BI_audit_CEIDG']) .
  2011. " from BI_audit_CEIDG where ID = '{$item['ID']}'";
  2012. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  2013. }
  2014. }
  2015. }
  2016. }
  2017. }
  2018. }
  2019. }
  2020. foreach ($K_IDs as $K_ID) {
  2021. if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTableUmowyToKontrahenci}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
  2022. DB::getPDO()->query("insert into `{$refTableUmowyToKontrahenci}` (PRIMARY_KEY, REMOTE_PRIMARY_KEY) values ({$ID}, {$K_ID})");
  2023. }
  2024. }
  2025. DB::getPDO()->update('BI_audit_ENERGA_RUM_UMOWY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
  2026. }
  2027. $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";
  2028. $result = DB::getPDO()->fetchAll($query);
  2029. foreach ($result as $row) {
  2030. $query = "select nip, regon, krs from BI_audit_KRS where nip = '{$row['NIP']}' or regon = '{$row['REGON']}' or krs = '{$row['KRS']}'";
  2031. if ($items = DB::getPDO()->fetchAll($query)) {
  2032. list($nip, $regon, $krs) = [$items[0]["nip"], $items[0]["regon"], $items[0]["krs"]];
  2033. if (count($items) > 1) {
  2034. for ($i = 1; $i < count($items); $i++) {
  2035. if ($nip != $items[$i]["nip"]) $nip = null;
  2036. if ($regon != $items[$i]["regon"]) $regon = null;
  2037. if ($krs != $items[$i]["krs"]) $krs = null;
  2038. }
  2039. }
  2040. $set = [];
  2041. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  2042. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  2043. if ($krs && $krs != $row['KRS']) $set[] = "KRS = '{$krs}'";
  2044. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row['ID']}'");
  2045. }
  2046. }
  2047. $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";
  2048. $result = DB::getPDO()->fetchAll($query);
  2049. foreach ($result as $row) {
  2050. $query = "select nip, regon from BI_audit_CEIDG where nip = '{$row['NIP']}' or regon = '{$row['REGON']}'";
  2051. if ($items = DB::getPDO()->fetchAll($query)) {
  2052. list($nip, $regon) = [$items[0]["nip"], $items[0]["regon"]];
  2053. if (count($items) > 1) {
  2054. for ($i = 1; $i < count($items); $i++) {
  2055. if ($nip != $items[$i]["nip"]) $nip = null;
  2056. if ($regon != $items[$i]["regon"]) $regon = null;
  2057. }
  2058. }
  2059. $set = [];
  2060. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  2061. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  2062. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row->ID}'");
  2063. }
  2064. }
  2065. }
  2066. public static function reloadCache_reTeryt($full = false, $forceAll = false) {
  2067. Lib::loadClass('Teryt');
  2068. $tables = [
  2069. 'BI_audit_CEIDG' => [
  2070. 'fields' => [
  2071. 'wojewodztwo' => 'wojewodztwo',
  2072. 'powiat' => 'powiat',
  2073. 'gmina' => 'gmina',
  2074. 'miejscowosc' => 'miejscowosc',
  2075. 'ulica' => 'ulica',
  2076. 'kodPocztowy' => 'kodPocztowy',
  2077. ],
  2078. 'fieldsTeryt' => [
  2079. 'TERYT_SYM' => 'TERYT_SYM',
  2080. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2081. 'nrDomu' => 'budynek',
  2082. 'nrLokalu' => 'lokal',
  2083. ],
  2084. 'base' => '1',
  2085. ],
  2086. 'BI_audit_CEIDG_pelnomocnicy' => [
  2087. 'fields' => [
  2088. 'wojewodztwo' => 'wojewodztwo',
  2089. 'powiat' => 'powiat',
  2090. 'gmina' => 'gmina',
  2091. 'miejscowosc' => 'miejscowosc',
  2092. 'ulica' => 'ulica',
  2093. 'kodPocztowy' => 'kodPocztowy',
  2094. ],
  2095. 'fieldsTeryt' => [
  2096. 'TERYT_SYM' => 'TERYT_SYM',
  2097. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2098. 'nrDomu' => 'budynek',
  2099. 'nrLokalu' => 'lokal',
  2100. ],
  2101. 'base' => '1',
  2102. ],
  2103. 'BI_audit_ENERGA_PRACOWNICY' => [
  2104. 'fields' => [
  2105. 'miejscowosc' => 'miejscowosc',
  2106. 'kodPocztowy' => 'kodPocztowy',
  2107. 'ulica' => 'ulica',
  2108. ],
  2109. 'fieldsTeryt' => [
  2110. 'TERYT_SYM' => 'TERYT_SYM',
  2111. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2112. 'nrDomu' => 'nr',
  2113. 'nrLokalu' => 'nrLokalu',
  2114. ],
  2115. 'base' => '0',
  2116. ],
  2117. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  2118. 'fields' => [
  2119. 'kodPocztowy' => 'kodPocztowy',
  2120. 'miejscowosc' => 'miejscowosc',
  2121. 'ulica' => 'ulica',
  2122. ],
  2123. 'fieldsTeryt' => [
  2124. 'TERYT_SYM' => 'TERYT_SYM',
  2125. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2126. 'nrDomu' => 'nrBudynku',
  2127. 'nrLokalu' => 'nrLokalu',
  2128. ],
  2129. 'base' => '0',
  2130. ],
  2131. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  2132. 'fields' => [
  2133. 'kodPocztowy' => 'Kod_pocztowy',
  2134. 'miejscowosc' => 'Miejscowosc',
  2135. 'ulica' => 'Ulica',
  2136. ],
  2137. 'fieldsTeryt' => [
  2138. 'TERYT_SYM' => 'TERYT_SYM',
  2139. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2140. 'nrDomu' => 'Numer_budynku',
  2141. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  2142. ],
  2143. 'base' => '0',
  2144. ],
  2145. 'BI_audit_KRS' => [
  2146. 'fields' => [
  2147. 'wojewodztwo' => 'S_wojewodztwo',
  2148. 'powiat' => 'S_powiat',
  2149. 'gmina' => 'S_gmina',
  2150. 'miejscowosc' => 'A_miejscowosc',
  2151. 'ulica' => 'A_ulica',
  2152. 'kodPocztowy' => 'A_kod',
  2153. ],
  2154. 'fieldsTeryt' => [
  2155. 'TERYT_SYM' => 'TERYT_SYM',
  2156. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2157. 'nrDomu' => 'A_nrDomu',
  2158. 'nrLokalu' => 'A_nrLokalu',
  2159. ],
  2160. 'base' => '1',
  2161. ],
  2162. 'BI_audit_KRS_address' => [
  2163. 'fields' => [
  2164. 'wojewodztwo' => 'S_wojewodztwo',
  2165. 'powiat' => 'S_powiat',
  2166. 'gmina' => 'S_gmina',
  2167. 'miejscowosc' => 'A_miejscowosc',
  2168. 'ulica' => 'A_ulica',
  2169. 'kodPocztowy' => 'A_kod',
  2170. ],
  2171. 'fieldsTeryt' => [
  2172. 'TERYT_SYM' => 'TERYT_SYM',
  2173. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2174. 'nrDomu' => 'A_nrDomu',
  2175. 'nrLokalu' => 'A_nrLokalu',
  2176. ],
  2177. 'base' => '1',
  2178. ],
  2179. 'BI_audit_MSIG_address' => [
  2180. 'fields' => [
  2181. 'wojewodztwo' => 'S_wojewodztwo',
  2182. 'powiat' => 'S_powiat',
  2183. 'gmina' => 'S_gmina',
  2184. 'miejscowosc' => 'A_miejscowosc',
  2185. 'ulica' => 'A_ulica',
  2186. 'kodPocztowy' => 'A_kod',
  2187. ],
  2188. 'fieldsTeryt' => [
  2189. 'TERYT_SYM' => 'TERYT_SYM',
  2190. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2191. 'nrDomu' => 'A_nrDomu',
  2192. 'nrLokalu' => 'A_nrLokalu',
  2193. ],
  2194. 'base' => '1',
  2195. ],
  2196. ];
  2197. foreach ($tables as $table => $tableConf) {
  2198. DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrDomu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrDomu']}`) = ''");
  2199. DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrLokalu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrLokalu']}`) = ''");
  2200. $where = ($full && ($forceAll || (!$tableConf['base']))) ? "" : "where `TERYT_SYM` is null and `cached` = 0";
  2201. $query = "select * from `{$table}` {$where}";
  2202. $refTable = BiAuditRefTables::getRefTable($table, 'TERYT_adresy', true);
  2203. $terytJoinArr = [];
  2204. foreach ($tableConf['fieldsTeryt'] as $terytField => $tableField) {
  2205. $terytJoinArr[] = (
  2206. $terytField == 'nrLokalu'
  2207. ? "coalesce(`teryt`.`{$terytField}`, '') = coalesce(`table`.`{$tableField}`, '')"
  2208. : "`teryt`.`{$terytField}` = `table`.`{$tableField}`"
  2209. );
  2210. }
  2211. $terytJoin = implode(" and ", $terytJoinArr);
  2212. $insertFields = "`" . implode("`, `", array_keys($tableConf['fieldsTeryt'])) . "`";
  2213. $selectFields = "`" . implode("`, `", $tableConf['fieldsTeryt']) . "`";
  2214. //$adresy = DB::getPDO()->queryNotBuffered($query);
  2215. $adresy = DB::getPDO()->query($query);
  2216. while ($adres = $adresy->fetch()) {
  2217. DB::getPDO()->query("delete from `{$refTable}` where `PRIMARY_KEY` = '{$adres['ID']}'");
  2218. if (!($forceAll and $adres['TERYT_SYM'])) {
  2219. $search = [];
  2220. foreach ($tableConf['fields'] as $field => $param) if (!empty($adres[$param])) $search[$field] = $adres[$param];
  2221. try {
  2222. $teryt = Teryt::search($search);
  2223. } catch (Exception $e) {
  2224. continue;
  2225. }
  2226. if (empty($teryt['SYM'])) continue;
  2227. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  2228. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  2229. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  2230. }
  2231. if (!trim($adres[$tableConf['fieldsTeryt']['nrDomu']])) continue;
  2232. $terytID = DB::getPDO()->fetchValue("select `teryt`.`ID` from `TERYT_adresy` as `teryt` join `{$table}` as `table` on {$terytJoin} where `table`.`ID` = '{$adres['ID']}'");
  2233. if (!$terytID) {
  2234. if (DB::getPDO()->query("insert into `TERYT_adresy` ({$insertFields}) select {$selectFields} from `{$table}` where `ID` = '{$adres['ID']}'")) {
  2235. if (!($terytID = DB::getPDO()->lastInsertId())) {
  2236. throw new Exception("Błąd dodania rekordu do TERYT_adresy #1");
  2237. }
  2238. } else {
  2239. throw new Exception("Błąd dodania rekordu do TERYT_adresy #2");
  2240. }
  2241. }
  2242. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $adres['ID'], 'REMOTE_PRIMARY_KEY' => $terytID]);
  2243. }
  2244. }
  2245. }
  2246. private static function reloadCache_updateAll($full, $onlyBase) {
  2247. $tablesConf = [
  2248. 'BI_audit_CEIDG' => [
  2249. 'fields' => [
  2250. 'nip' => 'nip',
  2251. 'regon' => 'regon',
  2252. ],
  2253. 'base' => '1',
  2254. ],
  2255. 'BI_audit_CEIDG_pelnomocnicy' => [
  2256. 'fields' => [
  2257. 'nip' => 'nip',
  2258. ],
  2259. 'base' => '1',
  2260. ],
  2261. 'BI_audit_CEIDG_powiazania' => [
  2262. 'fields' => [
  2263. 'nip' => 'nip',
  2264. 'regon' => 'regon',
  2265. ],
  2266. 'base' => '1',
  2267. ],
  2268. 'BI_audit_ENERGA_PRACOWNICY' => [
  2269. 'fields' => [
  2270. 'nip' => 'nip',
  2271. 'regon' => 'regon',
  2272. 'pesel' => 'pesel',
  2273. 'krs' => 'krs',
  2274. ],
  2275. 'base' => '0',
  2276. //'where' => '',
  2277. ],
  2278. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  2279. 'fields' => [],
  2280. 'base' => '0',
  2281. //'where' => '',
  2282. ],
  2283. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  2284. 'fields' => [
  2285. 'krs' => 'KRS',
  2286. 'nip' => 'NIP',
  2287. 'regon' => 'REGON',
  2288. 'pesel' => 'PESEL',
  2289. ],
  2290. 'base' => '0',
  2291. 'where' => "and ownCompany != 'Y'",
  2292. ],
  2293. 'BI_audit_KRS' => [
  2294. 'fields' => [
  2295. 'krs' => 'krs',
  2296. 'nip' => 'nip',
  2297. 'regon' => 'regon',
  2298. ],
  2299. 'base' => '1',
  2300. ],
  2301. 'BI_audit_KRS_address' => [
  2302. 'fields' => [],
  2303. 'base' => '1',
  2304. ],
  2305. 'BI_audit_KRS_company' => [
  2306. 'fields' => [
  2307. 'regon' => 'regon',
  2308. 'krs' => 'krs',
  2309. ],
  2310. 'base' => '1',
  2311. ],
  2312. 'BI_audit_KRS_person' => [
  2313. 'fields' => [
  2314. 'pesel' => 'pesel',
  2315. ],
  2316. 'base' => '1',
  2317. ],
  2318. 'BI_audit_MSIG' => [
  2319. 'fields' => [
  2320. 'krs' => 'krs',
  2321. 'nip' => 'nip',
  2322. 'regon' => 'regon',
  2323. ],
  2324. 'base' => '1',
  2325. ],
  2326. 'BI_audit_MSIG_address' => [
  2327. 'fields' => [],
  2328. 'base' => '1',
  2329. ],
  2330. 'BI_audit_MSIG_company' => [
  2331. 'fields' => [
  2332. 'regon' => 'regon',
  2333. 'krs' => 'krs',
  2334. ],
  2335. 'base' => '1',
  2336. ],
  2337. 'BI_audit_MSIG_person' => [
  2338. 'fields' => [
  2339. 'pesel' => 'pesel',
  2340. ],
  2341. 'base' => '1',
  2342. ],
  2343. // 'BI_audit_KW_requested_person' => [
  2344. // 'fields' => [
  2345. // 'pesel' => 'Seller_person_pesel',
  2346. // 'krs' => 'Seller_person_KRS',
  2347. // 'nip' => 'Seller_person_NIP',
  2348. // 'regon' => 'Seller_person_REGON',
  2349. // ],
  2350. // 'base' => '0',
  2351. // //'where' => '',
  2352. // ],
  2353. 'TERYT_adresy' => [
  2354. 'fields' => [],
  2355. 'base' => '1',
  2356. ],
  2357. ];
  2358. $refTablesConf = [
  2359. 'BI_audit_CEIDG' => [
  2360. 'refTablesTo' => [
  2361. 'BI_audit_CEIDG_pelnomocnicy',
  2362. 'BI_audit_CEIDG_powiazania',
  2363. 'TERYT_adresy',
  2364. ],
  2365. 'base' => 1,
  2366. ],
  2367. 'BI_audit_CEIDG_pelnomocnicy' => [
  2368. 'refTablesTo' => [
  2369. 'TERYT_adresy',
  2370. ],
  2371. 'base' => 1,
  2372. ],
  2373. 'BI_audit_ENERGA_PRACOWNICY' => [
  2374. 'refTablesTo' => [
  2375. 'BI_audit_ENERGA_PRACOWNICY_adresy',
  2376. //'TERYT_adresy',
  2377. ],
  2378. 'base' => 0,
  2379. ],
  2380. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  2381. 'refTablesTo' => [
  2382. 'TERYT_adresy',
  2383. ],
  2384. 'base' => 0,
  2385. ],
  2386. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  2387. 'refTablesTo' => [
  2388. 'TERYT_adresy',
  2389. ],
  2390. 'base' => 0,
  2391. ],
  2392. 'BI_audit_KRS' => [
  2393. 'refTablesTo' => [
  2394. 'BI_audit_KRS_address',
  2395. 'BI_audit_KRS_company',
  2396. 'BI_audit_KRS_person',
  2397. 'TERYT_adresy',
  2398. ],
  2399. 'base' => 1,
  2400. ],
  2401. 'BI_audit_KRS_address' => [
  2402. 'refTablesTo' => [
  2403. 'TERYT_adresy',
  2404. ],
  2405. 'base' => 1,
  2406. ],
  2407. 'BI_audit_MSIG' => [
  2408. 'refTablesTo' => [
  2409. 'BI_audit_MSIG_address',
  2410. 'BI_audit_MSIG_company',
  2411. 'BI_audit_MSIG_person',
  2412. ],
  2413. 'base' => 1,
  2414. ],
  2415. 'BI_audit_MSIG_address' => [
  2416. 'refTablesTo' => [
  2417. 'TERYT_adresy',
  2418. ],
  2419. 'base' => 1,
  2420. ],
  2421. ];
  2422. $sourceTables = ['BI_audit_ENERGA_PRACOWNICY'];
  2423. if ($full) {
  2424. foreach ($tablesConf as $table => $tableConf) if (!$tableConf['base']) $queries[] = "update `{$table}` set `cached` = 0";
  2425. $queries[] = "delete from `BI_audit_ALL` where `BASE` = 0";
  2426. // $queries[] = "optimize table `BI_audit_ALL`";
  2427. $queries[] = "delete from `BI_audit_ALL_ref` where `BASE` = 0";
  2428. // $queries[] = "optimize table `BI_audit_ALL_ref`";
  2429. $allTables = [];
  2430. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  2431. $allTables[] = $refTableFrom;
  2432. // if ($refTableConf['base']) continue;
  2433. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  2434. $allTables[] = $refTableTo;
  2435. if ($refTableConf['base']) continue;
  2436. $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
  2437. $queries[] = "update `{$refTable}` set `A_STATUS` = 'WAITNG' where `A_STATUS` = 'NORMAL'";
  2438. // $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}'";
  2439. }
  2440. }
  2441. $allTables = array_unique($allTables);
  2442. foreach ($allTables as $refTableFrom) {
  2443. foreach ($allTables as $refTableTo) {
  2444. if ($refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, false)) {
  2445. $queries[] = "delete from `{$refTable}` where `TRANSACTION_ID` = '-1'";
  2446. $queries[] = "optimize table `{$refTable}`";
  2447. $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";
  2448. }
  2449. }
  2450. }
  2451. }
  2452. foreach ($tablesConf as $table => $tableConf) {
  2453. if ($onlyBase && (!$tableConf['base'])) continue;
  2454. $where = "where `{$table}`.`cached` = 0";
  2455. if (!empty($tableConf['where'])) $where .= " {$tableConf['where']}";
  2456. // $queries[] = "insert into `BI_audit_ALL` (`REMOTE_TABLE`, `REMOTE_ID`, `BASE`, " . implode(", ", array_keys($tableConf['fields'])) .
  2457. // ") select '{$table}', ID, '{$tableConf['base']}', " . implode(", ", $tableConf['fields']) . " from `{$table}` {$where}";
  2458. $fields = ["`REMOTE_TABLE`", "`REMOTE_ID`", "`BASE`"];
  2459. $values = ["'{$table}'", "`ID`", "'{$tableConf['base']}'"];
  2460. $updates = ["`BI_audit_ALL`.`reffed` = 0", "`{$table}`.`cached` = 1"];
  2461. foreach ($tableConf['fields'] as $field => $value) {
  2462. $fields[] = "`{$field}`";
  2463. $values[] = "`{$value}`";
  2464. $updates[] = "`BI_audit_ALL`.`{$field}` = `{$table}`.`{$value}`";
  2465. }
  2466. $queries[] = "update `BI_audit_ALL` join `{$table}` on `BI_audit_ALL`.`REMOTE_TABLE` = '{$table}' and `BI_audit_ALL`.`REMOTE_ID` = `{$table}`.`ID` set " . implode(", ", $updates) . " {$where}";
  2467. $queries[] = "insert into `BI_audit_ALL` (" . implode(", ", $fields) . ") select " . implode(", ", $values) . " from `{$table}` {$where}";
  2468. $queries[] = "update `{$table}` set `cached` = 1 {$where}";
  2469. }
  2470. $queries[] = "update `BI_audit_ALL` set `nip` = null where `nip` = 0";
  2471. $queries[] = "update `BI_audit_ALL` set `regon` = null where `regon` = 0";
  2472. $queries[] = "update `BI_audit_ALL` set `krs` = null where `krs` = 0";
  2473. $queries[] = "update `BI_audit_ALL` set `pesel` = null where `pesel` = 0";
  2474. $queries[] = "set @var = (select round(coalesce(max(`ID`), '0.5'), 1) from `BI_audit_ALL_ref_RELATIONS`)";
  2475. $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";
  2476. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  2477. if ($onlyBase && (!$tableConf['base'])) continue;
  2478. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  2479. $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
  2480. $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`";
  2481. if (!in_array($refTableFrom, $sourceTables)) {
  2482. $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`";
  2483. }
  2484. if ($backRefTable = BiAuditRefTables::getRefTable($refTableTo, $refTableFrom, false)) {
  2485. $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'";
  2486. }
  2487. $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'";
  2488. }
  2489. }
  2490. foreach ($queries as $query) {
  2491. echo "SQL: {$query}\n";
  2492. DB::getPDO()->query($query);
  2493. }
  2494. $BiAuditRelations = new BiAuditRelations();
  2495. //$result = DB::getPDO()->queryNotBuffered("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
  2496. $result = DB::getPDO()->query("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
  2497. while ($row = $result->fetch()) $BiAuditRelations->findRelations($row['ID']);
  2498. DB::getPDO()->query("update `BI_audit_ALL` set `reffed` = 1");
  2499. }
  2500. public function doReloadCache($full = false) {
  2501. if ($full === 'base') {
  2502. $onlyBase = true;
  2503. $full = false;
  2504. } else {
  2505. $onlyBase = false;
  2506. }
  2507. $setFull = function() {
  2508. BiAuditPowiazania::saveToLog("Wykryto niespójność tabel - uruchamiam pełne odświeżenie cache");
  2509. $sqlArr = [
  2510. 'BI_analiza_reloadCache' => 'Full',
  2511. 'FILE_STATUS_info' => 'Odświeżam w pełni cache',
  2512. ];
  2513. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $this->POWIAZANIA_ID, $sqlArr);
  2514. };
  2515. if ($this->POWIAZANIA_ID && (!$full)) {
  2516. $checkTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy', 'BI_audit_ENERGA_RUM_KONTRAHENCI'];
  2517. foreach ($checkTables as $table) {
  2518. $query = "select count(*) from `BI_audit_ALL` `all` left join `{$table}` `t` on `all`.`REMOTE_ID`=`t`.`ID` and `t`.`cached` = '1' where `all`.`REMOTE_TABLE`='{$table}' and `t`.`ID` is null";
  2519. if (DB::getPDO()->fetchValue($query)) {
  2520. $full = true;
  2521. $setFull();
  2522. break;
  2523. }
  2524. }
  2525. }
  2526. $powiazaniaDirLocation = self::getMainDirectory();
  2527. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  2528. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  2529. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  2530. if (!$this->POWIAZANIA_ID) file_put_contents($reloadCachePidFile, getmypid());
  2531. try {
  2532. error_log('now: self::importPracownicy');
  2533. $_full = self::importPracownicy($full);
  2534. if ((!$full) && $_full) {
  2535. $full = true;
  2536. if ($this->POWIAZANIA_ID) $setFull();
  2537. }
  2538. error_log('now: self::reloadCache_parseFakturyUmowy');
  2539. self::reloadCache_parseFakturyUmowy($full);
  2540. error_log('now: self::reloadCache_reTeryt');
  2541. self::reloadCache_reTeryt($full);
  2542. error_log('now: self::reloadCache_updateAll');
  2543. self::reloadCache_updateAll($full, $onlyBase);
  2544. if (!$this->POWIAZANIA_ID) file_put_contents($reloadCacheResultFile, "ok");
  2545. } catch (Exception $e) {
  2546. var_dump($e);
  2547. if (!$this->POWIAZANIA_ID) file_put_contents($reloadCacheResultFile, $e->getMessage());
  2548. else throw new Exception($e->getMessage());
  2549. }
  2550. }
  2551. public function doGeneratePowiazania($ID) {
  2552. $this->POWIAZANIA_ID = $ID;
  2553. $powiazaniaDirLocation = self::getMainDirectory();
  2554. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  2555. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  2556. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  2557. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  2558. file_put_contents($pidFile, getmypid());
  2559. /* $tablesConf = [
  2560. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  2561. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  2562. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  2563. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  2564. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  2565. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  2566. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  2567. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  2568. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  2569. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  2570. ];*/
  2571. try {
  2572. $BiAuditPowiazania = new BiAuditPowiazania($ID, $tasksDirLocation);
  2573. $query = "select count(*) from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` where `FILE_STATUS` = 'IN_PROGRESS' and `BI_analiza_reloadCache` in ('Part', 'Full') and ID != ${ID}";
  2574. $sqlArr = [
  2575. 'BI_analiza_reloadCache' => 'Part',
  2576. 'FILE_STATUS_info' => 'Odświeżam częściowo cache',
  2577. ];
  2578. do {
  2579. DB::getPDO()->query("lock tables `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` write");
  2580. $activeReloadingCache = DB::getPDO()->fetchValue($query);
  2581. if (!$activeReloadingCache) DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  2582. DB::getPDO()->query("unlock tables");
  2583. if ($activeReloadingCache) {
  2584. BiAuditPowiazania::saveToLog("Czekam na zakończenie odświeżania cache przez inne zadanie");
  2585. sleep(30);
  2586. }
  2587. } while ($activeReloadingCache);
  2588. BiAuditPowiazania::saveToLog("Uruchamiam częściowe odświeżenie cache");
  2589. $this->doReloadCache(); //DUPA testowe wylaczanie
  2590. BiAuditPowiazania::saveToLog("Odświeżono cache");
  2591. $sqlArr = [
  2592. 'BI_analiza_reloadCache' => 'No',
  2593. 'FILE_STATUS_info' => 'Szukam powiązań',
  2594. ];
  2595. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  2596. $BiAuditPowiazania->run();
  2597. //if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  2598. //file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  2599. $sqlArr = ['FILE_STATUS_info' => 'Generuję raporty PDF i HTML'];
  2600. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  2601. //$BiAuditPowiazania->saveXml();
  2602. $BiAuditPowiazania->generatePdfAndHtml();
  2603. file_put_contents($resultFile, json_encode(['result' => 'ok', 'parts' => $BiAuditPowiazania->getPartsCount()]));
  2604. } catch (Exception $e) {
  2605. file_put_contents($resultFile, json_encode(['result' => 'error', 'message' => $e->getMessage()]));
  2606. }
  2607. }
  2608. public function reinstallAction() {
  2609. $this->reinstall();
  2610. die('OK');
  2611. }
  2612. public function reinstall() {
  2613. $sqlList = array();
  2614. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  2615. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  2616. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  2617. SQL;
  2618. $sqlList['ChangeStructure1'] = <<<SQL
  2619. 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';
  2620. SQL;
  2621. $sqlList['ChangeStructure2'] = <<<SQL
  2622. UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
  2623. SQL;
  2624. $sqlList['ChangeStructure3'] = <<<SQL
  2625. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
  2626. SQL;
  2627. $sqlList['ChangeStructure4'] = <<<SQL
  2628. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_depth` `BI_analiza_maxDepth` INT(2) NULL DEFAULT '9';
  2629. SQL;
  2630. $sqlList['ChangeStructure5'] = <<<SQL
  2631. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_minDepth` INT(2) NOT NULL DEFAULT '0' AFTER `FILE_STATUS_info`;
  2632. SQL;
  2633. $sqlList['ChangeStructure6'] = <<<SQL
  2634. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_onlyTargets` ENUM('Y','N') NOT NULL DEFAULT 'Y' AFTER `BI_analiza_maxDepth`;
  2635. SQL;
  2636. $db = DB::getDB();
  2637. if ($db->has_errors()) {
  2638. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  2639. }
  2640. foreach ($sqlList as $sqlName => $sql) {
  2641. $res = $db->query($sql);
  2642. if ($db->has_errors()) {
  2643. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  2644. }
  2645. }
  2646. }
  2647. }
  2648. class BiAuditRelations {
  2649. private $RELATIONS_ID = [];
  2650. private $relations = [
  2651. 'nip' => ['nip'],
  2652. 'regon' => ['regon'],
  2653. 'krs' => ['krs'],
  2654. 'pesel' => ['pesel'],
  2655. ];
  2656. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  2657. private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  2658. public function __construct() {
  2659. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  2660. $result = DB::getPDO()->fetchAll($query);
  2661. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  2662. }
  2663. private function getRelationID($name) {
  2664. if (!isset($this->RELATIONS_ID[$name])) {
  2665. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  2666. $newID = DB::getPDO()->fetchValue($query);
  2667. $this->RELATIONS_ID[$name] = $newID;
  2668. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  2669. DB::getPDO()->query($query);
  2670. }
  2671. return $this->RELATIONS_ID[$name];
  2672. }
  2673. private function addToRefTable($fromTable, $toTable, $fromID, $toID) {
  2674. if ($refTable = BiAuditRefTables::getRefTable($fromTable, $toTable, false)) {
  2675. if (!DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = '{$fromID}' and `REMOTE_PRIMARY_KEY` = '{$toID}' and `A_STATUS` != 'DELETED'")) {
  2676. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $fromID, 'REMOTE_PRIMARY_KEY' => $toID, 'A_STATUS' => 'NORMAL', 'TRANSACTION_ID' => '-1']);
  2677. }
  2678. }
  2679. }
  2680. public function findRelations($ID) {
  2681. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  2682. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  2683. $row = $result[0];
  2684. $joins = [];
  2685. $items = '';
  2686. foreach ($this->relations as $name => $columns) {
  2687. $ok = 0;
  2688. $join = [];
  2689. foreach ($columns as $column) {
  2690. $join[] = "t1.{$column} = t2.{$column}";
  2691. if ($row[$column] !== null) $ok++;
  2692. }
  2693. if ($ok / count($columns) > 0.5) {
  2694. $joins[] = "(" . implode(" and ", $join) . ")";
  2695. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  2696. }
  2697. }
  2698. if (!$joins) return false;
  2699. $query = "select t2.ID as ID, t1.REMOTE_TABLE as REMOTE_TABLE_1, t1.REMOTE_ID as REMOTE_ID_1, t2.REMOTE_TABLE as REMOTE_TABLE_2, t2.REMOTE_ID as REMOTE_ID_2 {$items}, t1.BASE * t2.BASE as BASE " .
  2700. "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})";
  2701. $result = DB::getPDO()->fetchAll($query);
  2702. foreach ($result as $row) {
  2703. $relationID = 0;
  2704. foreach ($this->relations as $name => $v) {
  2705. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  2706. }
  2707. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  2708. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  2709. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  2710. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  2711. if (!($start2 || $end1)) {
  2712. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
  2713. $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
  2714. $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
  2715. DB::getPDO()->query($query);
  2716. }
  2717. if (!($start1 || $end2)) {
  2718. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
  2719. $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
  2720. $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
  2721. DB::getPDO()->query($query);
  2722. }
  2723. }
  2724. }
  2725. }
  2726. class BiAuditRefTables {
  2727. public static function getRefTable($tableFrom, $tableTo, $returnException = false) {
  2728. static $refTables = [];
  2729. static $tempRefTables = [];
  2730. if (is_array($tableTo)) {
  2731. if (!$tableTo) throw new Exception('BiAuditRefTables::getRefTable - bad parameter $tableTo');
  2732. if (count($tableTo) == 1) return self::getRefTable($tableFrom, reset($tableTo), $returnException);
  2733. $key = implode("__", $tableTo);
  2734. if (!isset($tempRefTables[$tableFrom][$key])) {
  2735. try {
  2736. $_tableFrom = $tableFrom;
  2737. foreach ($tableTo as $_tableTo) {
  2738. $_refTables[] = self::getRefTable($_tableFrom, $_tableTo, true);
  2739. $_tableFrom = $_tableTo;
  2740. }
  2741. $name = "TEMP__#REF_TABLE__" . (count($tempRefTables) + 1);
  2742. $first = reset($_refTables);
  2743. $last = end($_refTables);
  2744. $prev = array_shift($_refTables);
  2745. $query = "create temporary table `{$name}` select `{$first}`.`PRIMARY_KEY`, `{$last}`.`REMOTE_PRIMARY_KEY` from `{$first}`";
  2746. while ($next = array_shift($_refTables)) {
  2747. $query .= " join `{$next}` on `{$prev}`.`REMOTE_PRIMARY_KEY` = `{$next}`.`PRIMARY_KEY`";
  2748. $prev = $next;
  2749. }
  2750. $query .= " group by `{$first}`.`PRIMARY_KEY`, `{$last}`.`REMOTE_PRIMARY_KEY`";
  2751. DB::getPDO()->query($query);
  2752. $tempRefTables[$tableFrom][$key] = $name;
  2753. } catch (Exception $e) {
  2754. if ($returnException) throw new Exception($e->getMessage());
  2755. $tempRefTables[$tableFrom][$key] = false;
  2756. }
  2757. }
  2758. return $tempRefTables[$tableFrom][$key];
  2759. } else {
  2760. if (!isset($refTables[$tableFrom][$tableTo])) {
  2761. try {
  2762. $refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
  2763. } catch (Exception $e) {
  2764. if ($returnException) throw new Exception($e->getMessage());
  2765. $refTables[$tableFrom][$tableTo] = false;
  2766. }
  2767. }
  2768. return $refTables[$tableFrom][$tableTo];
  2769. }
  2770. }
  2771. public static function getRefTables($tableFrom) {
  2772. static $refTables = [];
  2773. if (!isset($refTables[$tableFrom])) {
  2774. $namespace = "default_db/{$tableFrom}/{$tableFrom}";
  2775. try {
  2776. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  2777. if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
  2778. $fields = $item['field'];
  2779. $_refTables = [];
  2780. foreach ($fields as $field) {
  2781. list($type, $child) = explode(":", $field['xsdType'], 2);
  2782. if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) {
  2783. try {
  2784. $_refTable = ACL::getRefTable($namespace, $child);
  2785. $_refTables[] = $_refTable;
  2786. } catch (Exception $e) {
  2787. }
  2788. }
  2789. }
  2790. $refTables[$tableFrom] = $_refTables;
  2791. } catch (Exception $e) {
  2792. $refTables[$tableFrom] = [];
  2793. }
  2794. }
  2795. return $refTables[$tableFrom];
  2796. }
  2797. }
  2798. class BiAuditPowiazania {
  2799. private $minDepth;
  2800. private $maxDepth, $origMaxDepth;
  2801. private $onlyTargets;
  2802. private $ID;
  2803. private $nodes = [];
  2804. private $endNodes;
  2805. private $path = [];
  2806. private $results = [];
  2807. private $items_results = [];
  2808. private $relations = [];
  2809. private $srcTables = ['BI_audit_ENERGA_PRACOWNICY']; //, ['BI_audit_POWIAZANIA_OD', 'BI_audit_POWIAZANIA_OBIEKTY']];
  2810. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person']; //, ['BI_audit_POWIAZANIA_DO', 'BI_audit_POWIAZANIA_OBIEKTY']];
  2811. private $step = 0;
  2812. private $tasksDirLocation;
  2813. private $progressFile;
  2814. private $progress = [
  2815. 'summary' => [
  2816. 'count' => 0,
  2817. 'message' => 'Inicjacja',
  2818. 'ts' => null,
  2819. 'step' => 'initialize',
  2820. 'reportsCount' => 0,
  2821. 'reportsCreated' => 0,
  2822. ],
  2823. 'details' => [],
  2824. ];
  2825. private $lastProgress = 0;
  2826. private $lastProgress_slowCheck = 0;
  2827. private $lastResults = 0;
  2828. private $startTimestamp = null;
  2829. private $lastTimestamp = null;
  2830. private $lowProgressCount = 0;
  2831. private $count, $i;
  2832. private $splittedResults = [];
  2833. private $maxResults = 1000000;
  2834. private $fidRow = [];
  2835. private $itemID = 0;
  2836. private $reverseSearch = false;
  2837. private $query = "";
  2838. private static function generateJson($type, $data) {
  2839. return json_encode(['ts' => microtime(true), 'type' => $type, 'data' => $data]);
  2840. }
  2841. public static function saveToLog($message) {
  2842. $messageJson = self::generateJson('message', ['message' => $message]);
  2843. echo $messageJson . "\n";
  2844. }
  2845. private static function exec($cmd) {
  2846. $path = 'export PATH=$PATH:/usr/sbin;';
  2847. $cmd = "{$path} {$cmd}";
  2848. echo "CMD :: {$cmd}\n";
  2849. shell_exec($cmd);
  2850. }
  2851. private function saveProgress($args = []) {
  2852. $timestamp = microtime(true);
  2853. if (isset($args['progress']) && $this->i) {
  2854. $elapsed = $timestamp - $this->startTimestamp;
  2855. if ($args['progress']) {
  2856. $estimated = ($elapsed * (1 - $args['progress'])) / $args['progress'];
  2857. } else $estimated = "N/A";
  2858. $this->lastProgress = $args['progress'];
  2859. $this->lastTimestamp = $timestamp;
  2860. $progressJson = self::generateJson('progress', ['progress' => $args['progress'], 'item' => $this->i . "/" . $this->count, 'results' => count($this->results), 'step' => $this->step, 'elapsed' => $elapsed, 'estimated' => $estimated]);
  2861. echo $progressJson . "\n";
  2862. $this->progress['details'][$this->itemID] = ['progress' => $args['progress'], 'results' => (count($this->results) - $this->lastResults), 'elapsed' => $elapsed, 'estimated' => $estimated];
  2863. }
  2864. if (isset($args['message'])) $this->progress['summary']['message'] = $args['message'];
  2865. if (isset($args['step'])) $this->progress['summary']['step'] = $args['step'];
  2866. if (isset($args['reportsCreated'])) $this->progress['summary']['reportsCreated'] = round($this->progress['summary']['reportsCreated'] + $args['reportsCreated'], 2);
  2867. $this->progress['summary']['ts'] = $timestamp;
  2868. file_put_contents($this->progressFile, json_encode($this->progress));
  2869. }
  2870. private static function throwException($message) {
  2871. self::saveToLog($message);
  2872. throw new Exception($message);
  2873. }
  2874. public function __construct($ID = 0, $tasksDirLocation = null) {
  2875. if (!$ID) self::throwException("Wrong ID parameter");
  2876. if (!$tasksDirLocation) self::throwException("Wrong directory of tasks location");
  2877. $this->ID = $ID;
  2878. $this->tasksDirLocation = $tasksDirLocation;
  2879. $this->progressFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.progress";
  2880. $this->saveProgress();
  2881. }
  2882. public function run() {
  2883. $query = "select BI_analiza_minDepth, BI_analiza_maxDepth, BI_analiza_onlyTargets from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->ID}' and FILE_STATUS = 'IN_PROGRESS' and BI_analiza_reloadCache not in ('Full')";
  2884. $result = DB::getPDO()->fetchAll($query);
  2885. if (!$result) self::throwException("Błąd danych");
  2886. if ($this->loadResults()) {
  2887. $this->splitResults();
  2888. return;
  2889. }
  2890. self::saveToLog("Wczytuję parametry wyszukiwania powiązań");
  2891. $this->minDepth = (int) $result[0]['BI_analiza_minDepth'];
  2892. $this->maxDepth = (int) $result[0]['BI_analiza_maxDepth'];
  2893. $this->onlyTargets = ($result[0]['BI_analiza_onlyTargets'] != 'N');
  2894. if (!$this->minDepth) $this->minDepth = 1;
  2895. if (!$this->maxDepth) self::throwException("Błąd danych - nieokreślono maksymalnej głębokości analizy");
  2896. if ($this->minDepth > $this->maxDepth) self::throwException("Wartość minimalnej głębokości analizy jest większa od wartości maksymalnej głębokości analizy");
  2897. $subQueries = [];
  2898. $resultDest = [];
  2899. foreach ($this->destTables as $destTable) {
  2900. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $destTable)) {
  2901. $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}'";
  2902. }
  2903. }
  2904. if ($subQueries) {
  2905. $query = implode(" union ", $subQueries) . " order by `ID` asc";
  2906. $resultDest = DB::getPDO()->fetchAll($query);
  2907. }
  2908. if ((!$resultDest) && $this->onlyTargets) self::throwException("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  2909. $subQueries = [];
  2910. $resultSrc = [];
  2911. foreach ($this->srcTables as $srcTable) {
  2912. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $srcTable)) {
  2913. $subQueries[] = "select `all`.`ID` from `BI_audit_ALL` `all` join `{$refTable}` `ref` on `all`.`REMOTE_TABLE` = '{$srcTable}' and `all`.`REMOTE_ID` = `ref`.`REMOTE_PRIMARY_KEY` and `ref`.`PRIMARY_KEY` = '{$this->ID}'";
  2914. }
  2915. }
  2916. if ($subQueries) {
  2917. $query = implode(" union ", $subQueries) . " order by `ID` asc";
  2918. $resultSrc = DB::getPDO()->fetchAll($query);
  2919. }
  2920. if (!$resultSrc) self::throwException("Błąd danych - nie zdefinowano żadnego początkowego obiektu");
  2921. if (count($resultSrc) <= count($resultDest) || (!$this->onlyTargets)) {
  2922. $result = $resultSrc;
  2923. $this->endNodes = array_map('reset', $resultDest);
  2924. $this->reverseSearch = false;
  2925. $this->query = "select ref.ID2 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID1";
  2926. } else {
  2927. $result = $resultDest;
  2928. $this->endNodes = array_map('reset', $resultSrc);
  2929. $this->reverseSearch = true;
  2930. $this->query = "select ref.ID1 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID2";
  2931. self::saveToLog("Docelowych obiektów jest mniej, niż początkowych - włączono mechanizm odwrotnego przeszukiwania");
  2932. }
  2933. self::saveToLog("Rozpoczynam wyszukiwanie powiązań");
  2934. $this->count = count($result);
  2935. $this->progress['summary']['count'] = $this->count;
  2936. $this->origMaxDepth = $this->maxDepth;
  2937. $this->saveProgress(['step' => 'relations']);
  2938. try {
  2939. foreach ($result as $i => $row) {
  2940. $this->i = $i + 1;
  2941. $this->itemID = DB::getPDO()->fetchValue("select `REMOTE_ID` from `BI_audit_ALL` where `ID` = :ID", [":ID" => $row['ID']]);
  2942. $this->startTimestamp = microtime(true);
  2943. $this->lastProgress = 0;
  2944. $this->lastProgress_slowCheck = 0;
  2945. $this->saveProgress(['progress' => 0, 'message' => "Wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
  2946. if ($this->maxDepth != $this->origMaxDepth) {
  2947. $this->maxDepth = $this->origMaxDepth;
  2948. self::saveToLog("Przywrócono oryginalną maksymalną głębokość przeszukiwania ({$this->origMaxDepth})");
  2949. }
  2950. $this->findPowiazania($row['ID']);
  2951. $this->saveProgress(['progress' => 1, 'message' => "Zakończono wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
  2952. $this->lastResults = count($this->results);
  2953. }
  2954. } catch (Exception $e) {
  2955. if ($this->i < $this->count) {
  2956. $this->startTimestamp = microtime(true);
  2957. $this->lastProgress = 0;
  2958. $this->lastResults = count($this->results);
  2959. while (++$this->i <= $this->count) $this->saveProgress(['progress' => 0]);
  2960. }
  2961. if ($message = $e->getMessage()) self::saveToLog("Wystąpił błąd podczas wyszukiwania powiązań - {$message}");
  2962. }
  2963. $this->nodes = [];
  2964. self::saveToLog("Zakończono wyszukiwanie powiązań");
  2965. $this->sortResults();
  2966. $this->saveResults();
  2967. //$this->saveToDb(); 2017-12-14 - przerobiono na zapisywanie danych do bazy w locie
  2968. $this->splitResults();
  2969. }
  2970. private static function reversePath($path) {
  2971. $arr = array_reverse($path, true);
  2972. $keys = array_keys($arr);
  2973. array_unshift($arr, array_pop($arr));
  2974. return array_combine($keys, $arr);
  2975. }
  2976. private function addResult($progress) {
  2977. if (count($this->results) == $this->maxResults) {
  2978. $message = "Przerwano wyszukiwanie powiązań - osiągnięto maksymalną liczbę wyników {$this->maxResults}";
  2979. self::saveToLog($message);
  2980. $this->saveProgress(['progress' => $progress, 'message' => $message]);
  2981. throw new Exception('');
  2982. }
  2983. if ($this->reverseSearch) $path = self::reversePath($this->path);
  2984. else $path = $this->path;
  2985. $this->results[] = $path;
  2986. $this->saveToDb($path);
  2987. }
  2988. private static function weightCalc($n) {
  2989. if ($n < 21) return 1;
  2990. if ($n < 41) return 2;
  2991. if ($n < 81) return 3;
  2992. if ($n < 161) return 4;
  2993. if ($n < 321) return 5;
  2994. if ($n < 641) return 6;
  2995. if ($n < 1281) return 7;
  2996. if ($n < 2561) return 8;
  2997. if ($n < 5121) return 9;
  2998. return 10;
  2999. }
  3000. public function findPowiazania($ID, $progress = 0, $steps = 1, $relation = "", $weight = 0) {
  3001. $this->step++;
  3002. if ($this->maxDepth > $this->minDepth) {
  3003. if (($this->step % 1000000) == 0) {
  3004. $progressDiff = $progress - $this->lastProgress_slowCheck;
  3005. if ($progressDiff < 0.00005) {
  3006. $this->lowProgressCount++;
  3007. if ($this->lowProgressCount == 10) {
  3008. $this->maxDepth--;
  3009. self::saveToLog("Zbyt dużo rekurencji, zmniejszono maksymalną głębokość poszukiwań do {$this->maxDepth} dla bieżącego obiektu");
  3010. $this->lowProgressCount = 0;
  3011. }
  3012. } else $this->lowProgressCount = 0;
  3013. $this->lastProgress_slowCheck = $progress;
  3014. }
  3015. }
  3016. if ((($this->step) % 100000) == 0) {
  3017. $this->saveProgress(['progress' => $progress]);
  3018. }
  3019. if ((($this->step) % 10000) == 0) {
  3020. if (memory_get_usage(true) > 3000000000) {
  3021. $this->nodes = [];
  3022. self::saveToLog("Oczyszczam podręczny cache - zajmuje zbyt dużo pamięci");
  3023. }
  3024. }
  3025. if (isset($this->path[$ID])) return false;
  3026. $this->path[$ID] = $relation;
  3027. if (!$relation) $relation = 0;
  3028. if (in_array($ID, $this->endNodes)) {
  3029. if (count($this->path) > $this->minDepth) $this->addResult($progress);
  3030. array_pop($this->path);
  3031. return;
  3032. }
  3033. if (count($this->path) > $this->maxDepth) {
  3034. if (!$this->onlyTargets) $this->addResult($progress);
  3035. array_pop($this->path);
  3036. return;
  3037. }
  3038. if (!isset($this->nodes[$ID][$relation])) {
  3039. $where = $relation ? "and ({$relation} & ref.RELATION_ID) = 0" : "";
  3040. $query = "{$this->query} = {$ID} {$where}";
  3041. $this->nodes[$ID][$relation] = DB::getPDO()->fetchAll($query);
  3042. }
  3043. $nodes = array_values(array_filter($this->nodes[$ID][$relation], function ($node) {
  3044. if (isset($this->path[$node['ID']])) return false;
  3045. return true;
  3046. }));
  3047. $count = count($nodes);
  3048. $weight += self::weightCalc($count);
  3049. if ($weight <= $this->maxDepth) {
  3050. foreach ($nodes as $i => $node) $this->findPowiazania($node['ID'], ($progress + ($i / ($count * $steps))), ($count * $steps), $node['RELATION_ID'], $weight);
  3051. }
  3052. array_pop($this->path);
  3053. }
  3054. private function sortResults() {
  3055. if (!$this->results) return;
  3056. uasort($this->results, function ($a, $b) {
  3057. $ca = count($a);
  3058. $cb = count($b);
  3059. $c = min($ca, $cb);
  3060. $ka = array_keys($a);
  3061. $kb = array_keys($b);
  3062. for ($i = 0; $i < $c; $i++) {
  3063. if ($ka[$i] < $kb[$i]) return -1;
  3064. if ($ka[$i] > $kb[$i]) return 1;
  3065. }
  3066. if ($ca < $cb) return -1;
  3067. if ($ca > $cb) return 1;
  3068. return 0;
  3069. });
  3070. }
  3071. private function saveResults() {
  3072. self::saveToLog("Zapisuję wyliczone dane do pliku");
  3073. // if (!$this->results) {
  3074. // self::saveToLog("Brak wyliczonych danych - niczego nie zapisaono");
  3075. // return false;
  3076. // }
  3077. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  3078. $data = base64_encode(gzcompress(json_encode(['results' => $this->results, 'fidRow' => $this->fidRow])));
  3079. file_put_contents($dataFile, $data);
  3080. self::saveToLog("Zapisano wyliczone dane do pliku");
  3081. return true;
  3082. }
  3083. private function loadResults() {
  3084. self::saveToLog("Próbuję wczytać wcześniej wyliczone dane");
  3085. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  3086. if (!file_exists($dataFile)) {
  3087. self::saveToLog("Nie znaleziono pliku z wyliczonymi danymi");
  3088. return false;
  3089. }
  3090. $data = file_get_contents($dataFile);
  3091. $results = @json_decode(gzuncompress(base64_decode($data)), true);
  3092. if (!$results) {
  3093. self::saveToLog("Wystąpił błąd wczytywania wcześniej wyliczonych danych");
  3094. return false;
  3095. }
  3096. if (isset($results['results'])) {
  3097. $this->results = $results['results'];
  3098. if (isset($results['fidRow'])) $this->fidRow = $results['fidRow'];
  3099. } else $this->results = $results;
  3100. self::saveToLog("Wczytano wcześniej wyliczone dane");
  3101. return true;
  3102. }
  3103. private function relationName($ID) {
  3104. if (!$ID) return '';
  3105. if (!isset($this->relations[$ID])) {
  3106. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  3107. $result = DB::getPDO()->fetchAll($query);
  3108. $rels = array_map('reset', $result);
  3109. $this->relations[$ID] = implode(", ", $rels);
  3110. }
  3111. return $this->relations[$ID];
  3112. }
  3113. private function splitResults() {
  3114. $MAX = 1000;
  3115. $countBySource = [];
  3116. $resultsKeys = [];
  3117. foreach ($this->results as $resultKey => $result) {
  3118. $_keys = array_keys($result);
  3119. $countBySource[reset($_keys)][] = $resultKey;
  3120. }
  3121. foreach ($countBySource as $resultKeys) {
  3122. if (count($resultKeys) > $MAX) {
  3123. $countByDest = [];
  3124. foreach ($resultKeys as $resultKey) {
  3125. $_keys = array_keys($this->results[$resultKey]);
  3126. $countByDest[end($_keys)][] = $resultKey;
  3127. }
  3128. foreach ($countByDest as $resultKeys2) $resultsKeys = array_merge($resultsKeys, array_chunk($resultKeys2, $MAX));
  3129. } else $resultsKeys[] = $resultKeys;
  3130. }
  3131. $results = [];
  3132. while ($resultsKeys) {
  3133. $resultKeys = array_shift($resultsKeys);
  3134. while ($next = current($resultsKeys)) {
  3135. if (count($resultKeys) + count($next) <= $MAX) {
  3136. $resultKeys = array_merge($resultKeys, $next);
  3137. unset($resultsKeys[key($resultsKeys)]);
  3138. } else break; //next($resultsKeys);
  3139. }
  3140. $_results = [];
  3141. foreach ($resultKeys as $key) $_results[$key] = $this->results[$key];
  3142. $results[] = $_results;
  3143. // $results[] = array_map(function ($resultKey) {return $this->results[$resultKey];}, $resultKeys);
  3144. }
  3145. if ($results) $this->splittedResults = $results;
  3146. else $this->splittedResults[] = $this->results;
  3147. $this->progress['summary']['reportsCount'] = count($results);
  3148. }
  3149. public function getPartsCount() {
  3150. return count($this->splittedResults);
  3151. }
  3152. private function generateItemsResults($resultsPart = null) {
  3153. if ($resultsPart === null) self::saveToLog("Generuję dane na potrzeby utworzenia pojedynczego pliku XML");
  3154. else {
  3155. self::saveToLog("Generuję dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  3156. if ($resultsPart >= $this->getPartsCount()) throw new Exception("generateItemsResults() error - bad part number");
  3157. }
  3158. $xmlTask = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  3159. $xmlRow = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  3160. $xmlObject = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object";
  3161. $items_kontrahenci = [];
  3162. $items_kw_person = [];
  3163. $kontrahenci = [];
  3164. $kw_person = [];
  3165. $_items_results = [];
  3166. $refUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  3167. $refFakturyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_FAKTURY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  3168. $refKwRequestedToKwRequestedPerson = BiAuditRefTables::getRefTable('BI_audit_KW_requested', 'BI_audit_KW_requested_person', true);
  3169. $this->items_results[$resultsPart] = [];
  3170. $this->items_results[$resultsPart]['@attributes'] = ['xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd'];
  3171. $this->items_results[$resultsPart][$xmlTask]['@attributes'] = ['fid' => "{$xmlTask}.{$this->ID}"];
  3172. if ($resultsPart === null) {
  3173. $results = $this->results;
  3174. } else {
  3175. $results = (!empty($this->splittedResults[$resultsPart])) ? $this->splittedResults[$resultsPart] : [];
  3176. $this->items_results[$resultsPart][$xmlTask]['@attributes']['system_cache__dita:part'] = ($resultsPart + 1);
  3177. }
  3178. foreach ($results as $key => $result) {
  3179. if ($this->fidRow) $item_results = ['@attributes' => ['fid' => "{$xmlRow}.{$this->fidRow[$key]['fid']}"]];
  3180. foreach ($result as $ID => $rel) {
  3181. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  3182. $row = DB::getPDO()->fetchFirst($query);
  3183. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  3184. $obj = DB::fetch(DB::query($query));
  3185. $item_result = [];
  3186. if ($this->fidRow) {
  3187. $item_result['@attributes'] = ['fid' => "{$xmlObject}.{$this->fidRow[$key]['obj'][$ID]}"];
  3188. }
  3189. $item_result[$row['REMOTE_TABLE']] = array_merge(['@attributes' => ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"]], (array) $obj);
  3190. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_operational_raport_note', $row['REMOTE_TABLE'], false)) {
  3191. $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']}'";
  3192. if ($notes = DB::getPDO()->fetchAll($query)) $item_result[$row['REMOTE_TABLE']]['BI_audit_operational_raport_note'] = $notes;
  3193. }
  3194. if ($refTable = BiAuditRefTables::getRefTable($row['REMOTE_TABLE'], 'BI_audit_taxpayer', false)) {
  3195. $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']}'";
  3196. if ($taxpayer = DB::getPDO()->fetchFirst($query)) {
  3197. $item_result[$row['REMOTE_TABLE']]['BI_audit_taxpayer'] = array_merge(['@attributes' => ['fid' => "BI_audit_taxpayer.{$taxpayer['ID']}"]], $taxpayer);
  3198. }
  3199. }
  3200. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  3201. $item_results[$xmlObject][] = $item_result;
  3202. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  3203. $kontrahenci[] = $row['REMOTE_ID'];
  3204. $query = "select faktury.* from BI_audit_ENERGA_FAKTURY faktury join `{$refFakturyToKontrahenci}` ref on faktury.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
  3205. $res = DB::query($query);
  3206. $faktury = [];
  3207. if (mysql_num_rows($res)) {
  3208. while ($obj = DB::fetch($res)) {
  3209. $faktura = (array) $obj;
  3210. $faktura = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_FAKTURY.{$faktura['ID']}"]], $faktura);
  3211. $faktury[] = $faktura;
  3212. }
  3213. }
  3214. $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']}'";
  3215. $res = DB::query($query);
  3216. $umowy = [];
  3217. if (mysql_num_rows($res)) {
  3218. while ($obj = DB::fetch($res)) {
  3219. $umowa = (array) $obj;
  3220. $umowa = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_RUM_UMOWY.{$umowa['ID']}"]], $umowa);
  3221. $umowy[] = $umowa;
  3222. }
  3223. }
  3224. if ($faktury || $umowy) {
  3225. $item_kontrahenci['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
  3226. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  3227. if ($faktury) $item_kontrahenci['BI_audit_ENERGA_FAKTURY'] = $faktury;
  3228. if ($umowy) $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  3229. $items_kontrahenci[] = $item_kontrahenci;
  3230. }
  3231. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  3232. $kw_person[] = $row['REMOTE_ID'];
  3233. $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']}'";
  3234. $res = DB::query($query);
  3235. if (mysql_num_rows($res)) {
  3236. $kws = [];
  3237. while ($obj = DB::fetch($res)) {
  3238. $kw = (array) $obj;
  3239. $kw = array_merge(['@attributes' => ['fid' => "BI_audit_KW_requested.{$kw['ID']}"]], $kw);
  3240. $kws[] = $kw;
  3241. }
  3242. $item_kw_person['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
  3243. $item_kw_person['ID'] = $row['REMOTE_ID'];
  3244. $item_kw_person['BI_audit_KW_requested'] = $kws;
  3245. $items_kw_person[] = $item_kw_person;
  3246. }
  3247. }
  3248. }
  3249. $this->items_results[$resultsPart][$xmlTask][$xmlRow][] = $item_results;
  3250. }
  3251. $this->items_results[$resultsPart][$xmlTask]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  3252. $this->items_results[$resultsPart][$xmlTask]['BI_audit_KW_requested_person'] = $items_kw_person;
  3253. self::saveToLog("Wygenerowano dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  3254. }
  3255. private function saveToDb($result = null, $key = null) {
  3256. if ($result === null) {
  3257. self::saveToLog("Zapisuję wyliczone dane do bazy");
  3258. if (!$this->results) {
  3259. self::saveToLog("Brak wyliczonych danych - nie zapisaono niczego do bazy");
  3260. return null;
  3261. }
  3262. foreach ($this->results as $key => $result) $this->saveToDb($result, $key);
  3263. self::saveToLog("Zapisano wyliczone dane do bazy");
  3264. } else {
  3265. if ($key === null) {
  3266. end($this->results);
  3267. $key = key($this->results);
  3268. }
  3269. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  3270. $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
  3271. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  3272. $fidObj = [];
  3273. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  3274. foreach ($result as $ID => $rel) {
  3275. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  3276. $object = DB::getPDO()->fetchFirst($query);
  3277. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relationName($rel)]);
  3278. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  3279. $ref = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', $object['REMOTE_TABLE'], true);
  3280. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  3281. $fidObj[$ID] = $idPowiazaniaRowObject;
  3282. }
  3283. $this->fidRow[$key] = [
  3284. 'fid' => $IdPowiazaniaRow,
  3285. 'obj' => $fidObj,
  3286. ];
  3287. }
  3288. }
  3289. public function saveXml($resultsPart = null) {
  3290. if ($this->getPartsCount()) {
  3291. if ($resultsPart === null) {
  3292. self::saveToLog("Generuję pliki XML (liczba plików do wygenerowania: {$this->getPartsCount()})");
  3293. for ($i =0; $i < $this->getPartsCount(); $i++) {
  3294. $partNo = str_pad($i + 1, 6, '0', STR_PAD_LEFT);
  3295. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  3296. file_put_contents($xmlFile, $this->asXml($i));
  3297. }
  3298. self::saveToLog("Zakończono generowanie plików XML");
  3299. } else {
  3300. if ($resultsPart >= $this->getPartsCount()) {
  3301. self::saveToLog("saveXml() error - bad result number");
  3302. return;
  3303. }
  3304. $partNo = str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  3305. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  3306. file_put_contents($xmlFile, $this->asXml($resultsPart));
  3307. }
  3308. } else {
  3309. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
  3310. file_put_contents($xmlFile, $this->asXml());
  3311. }
  3312. }
  3313. public function asXml($resultsPart = null) {
  3314. self::saveToLog("Generuję plik XML ({$resultsPart})");
  3315. if (!$this->results) {
  3316. self::saveToLog("Brak wyników (#1), wygenerowano pusty plik XML ({$resultsPart})");
  3317. // self::saveToLog("Brak wyników (#1), nie wygenerowano pliku XML ({$resultsPart})");
  3318. // return null;
  3319. }
  3320. if (!isset($this->items_results[$resultsPart])) $this->generateItemsResults($resultsPart);
  3321. if (!isset($this->items_results[$resultsPart])) {
  3322. self::saveToLog("Brak wyników (#2), nie wygenerowano pliku XML ({$resultsPart})");
  3323. return null;
  3324. }
  3325. $xmlRoot = "RelatedFeatureRoot";
  3326. $return = V::arrayToXML($this->items_results[$resultsPart], true, $xmlRoot);
  3327. self::saveToLog("Wygenerowano plik XML ({$resultsPart})");
  3328. return $return;
  3329. }
  3330. public function asArray($resultsPart = null, $subArray = null) {
  3331. if (!$this->results) return null;
  3332. if (!$this->items_results[$resultsPart]) $this->generateItemsResults($resultsPart);
  3333. if (!$this->items_results[$resultsPart]) return null;
  3334. if ($subArray) {
  3335. if (isset($this->items_results[$resultsPart][$subArray])) return $this->items_results[$subArray];
  3336. else return [];
  3337. } else return $this->items_results[$resultsPart];
  3338. }
  3339. public function powiazaniaFound() {
  3340. if ($this->results) return true;
  3341. else return false;
  3342. }
  3343. public function generatePdfAndHtml() {
  3344. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  3345. if (!file_exists($antDir)) mkdir($antDir, 0770, true);
  3346. if (!is_dir($antDir)) {
  3347. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików PDF i HTML";
  3348. self::saveToLog("Nie wygenerowano plików PDF oraz HTML - problem z utworzeniem katalogu dla ant ({$resultsPart})");
  3349. $this->saveProgress(['reportsCreated' => 1]);
  3350. return;
  3351. }
  3352. $this->saveProgress(['step' => 'reports']);
  3353. if ($this->getPartsCount()) {
  3354. self::saveToLog("Generuję raporty w plikach PDF oraz HTML (liczba raportów do wygenerowania: {$this->getPartsCount()})");
  3355. for ($i =0; $i < $this->getPartsCount(); $i++) $this->_generatePdfAndHtml($i);
  3356. self::saveToLog("Zakończono generowanie raportów w plikach PDF oraz HTML");
  3357. } else $this->_generatePdfAndHtml();
  3358. }
  3359. private function _generatePdfAndHtml($resultsPart = null) {
  3360. $id_part = $resultsPart === null ? $this->ID : $this->ID . "_" . str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  3361. self::saveToLog("Generuję raport w pliku PDF oraz HTML ({$resultsPart})");
  3362. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.xml";
  3363. $pdfDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.pdf";
  3364. $htmlDestDir = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.html";
  3365. $htmlZipDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.zip";
  3366. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  3367. $antXmlFilename = "relations-{$id_part}.out_task.dita.final_with_RelatedFeatureLoop.xml";
  3368. $antXmlFile = $antDir . "/" . $antXmlFilename;
  3369. //$baseDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}";
  3370. $baseDir = "/opt/local/pl.procesy5/p5build_SE/temp/WPS_Functions/temp/default_db/CRM_PROCES_tree/relations-{$id_part}";
  3371. $ditamapFile = "{$baseDir}/relations-{$id_part}.ditamap";
  3372. $pdfFile = "{$baseDir}/pdf/relations-{$id_part}.pdf";
  3373. $htmlDir = "{$baseDir}/html";
  3374. $htmlFile = "{$htmlDir}/relations-{$id_part}.html";
  3375. //if (!file_exists($xmlFile))
  3376. $this->saveXml($resultsPart);
  3377. if (!file_exists($xmlFile)) {
  3378. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików XML, PDF i HTML";
  3379. self::saveToLog("Nie wygenerowano plików XML, PDF oraz HTML - problem z wygenerowaniem pliku XML ({$resultsPart})");
  3380. $this->saveProgress(['reportsCreated' => 1]);
  3381. return;
  3382. }
  3383. $this->saveProgress(['reportsCreated' => 0.05]);
  3384. copy($xmlFile, $antXmlFile);
  3385. self::saveToLog("Generuję plik przejściowy do wygenerowania plików PDF i HTML ({$resultsPart})");
  3386. self::exec("cd /Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree && /opt/local/bin/ant -f build_CRM_PROCES_tree.xml default_db:PROCES_INIT:tree:dita -Duuid=relations-{$id_part}");
  3387. if (file_exists($ditamapFile))
  3388. {
  3389. self::saveToLog("Wygenerowano plik przejściowy");
  3390. $this->saveProgress(['reportsCreated' => 0.15]);
  3391. } else {
  3392. self::saveToLog("Nie udało się wygenerować pliku przejściowego, przerywm");
  3393. $this->saveProgress(['reportsCreated' => 1]);
  3394. return;
  3395. }
  3396. self::saveToLog("Generuję plik PDF ({$resultsPart})");
  3397. self::exec("cd \"{$baseDir}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o pdf -i relations-{$id_part}.ditamap -f pdf");
  3398. if (file_exists($pdfFile)) {
  3399. rename($pdfFile, $pdfDestFile);
  3400. self::saveToLog("Wygenerowano plik PDF ({$resultsPart})");
  3401. } else self::saveToLog("Nie udało się wygenerować pliku PDF ({$resultsPart})");
  3402. $this->saveProgress(['reportsCreated' => 0.45]);
  3403. self::saveToLog("Generuję pliki HTML ({$resultsPart})");
  3404. self::exec("cd \"{$baseDir}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o html -i relations-{$id_part}.ditamap -f tocjs");
  3405. if (file_exists($htmlDir) && is_dir($htmlDir) && file_exists($htmlFile)) {
  3406. self::exec("cd \"{$baseDir}\" && zip -r \"{$htmlZipDestFile}\" html");
  3407. if (file_exists($htmlDestDir)) self::exec("rm -rf \"{$htmlDestDir}\"");
  3408. self::exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
  3409. self::saveToLog("Wygenerowano pliki HTML ({$resultsPart})");
  3410. } else self::saveToLog("Nie udało się wygenerować plików HTML {$resultsPart})");
  3411. $this->saveProgress(['reportsCreated' => 0.35]);
  3412. }
  3413. }