BiAuditGenerate.php 170 KB

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