BiAuditGenerate.php 172 KB

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