BiAuditGenerate.php 179 KB

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