BiAuditGenerate.php 163 KB

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