BiAuditGenerate.php 164 KB

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