BiAuditGenerate.php 144 KB

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