BiAuditGenerate.php 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087
  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. switch ($this->SOURCE['TABLE']) {
  885. case "BI_audit_ENERGA_PRACOWNICY":
  886. case "BI_audit_ENERGA_RUM_KONTRAHENCI":
  887. $query = "delete from `{$this->SOURCE['TABLE']}`";
  888. break;
  889. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  890. //throw new Exception('Not implemented yet');//TODO
  891. if ($deleteFiles) {
  892. $query = "select ID from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  893. $result = DB::getPDO()->fetchAll($query);
  894. foreach ($result as $row) {
  895. $dir = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  896. if (!file_exists($dir)) continue;
  897. $deleted = V::deleteWholeDirectory($dir, true, false);
  898. $deletedDirs += count($deleted['dirs']);
  899. $deletedFiles += count($deleted['files']);
  900. }
  901. }
  902. $query = "";
  903. break;
  904. default: throw new Exception('Błąd parametru');
  905. //DB::getPDO()->query($query);
  906. }
  907. ?>
  908. <div style="text-align: center;">
  909. <h2>Pomyślnie wyczyszczono tabelę.</h2>
  910. <?php
  911. if ($deleteFiles && ($deletedDirs || $deletedFiles)):
  912. ?>
  913. <h4>Ponadto usunięto <?=$deletedDirs?> katalogów oraz <?=$deletedFiles?> plików.</h4>
  914. <?php
  915. endif;
  916. ?>
  917. <br/><a href="<?=$this->REFERER?>" class="btn btn-primary" style="width: 80px;">Powrót</a>
  918. </div>
  919. <?php
  920. } catch (Exception $e) {
  921. SE_Layout::alert('danger', $e->getMessage());
  922. }
  923. }
  924. private function clearTable_form() {
  925. $tables = [
  926. 'BI_audit_ENERGA_PRACOWNICY' => 'pracowników',
  927. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => 'kontrahentów',
  928. 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA' => 'raportów',
  929. ];
  930. if (!isset($tables[$this->SOURCE['TABLE']])) SE_Layout::alert('danger', 'Błąd parametru');
  931. $a = rand(10, 50);
  932. $b = rand(10, 50);
  933. if ($a == $b) $op = 1;
  934. else $op = rand(0, 1);
  935. if ($op) {
  936. $suma = $a + $b;
  937. $string = "{$a} + {$b}";
  938. } else {
  939. if ($a < $b) {
  940. $suma = $b - $a;
  941. $string = "{$b} - {$a}";
  942. } else {
  943. $suma = $a - $b;
  944. $string = "{$a} - {$b}";
  945. }
  946. }
  947. $string .= " = ";
  948. $_SESSION['_BiAuditGenerate_ctrl'] = base64_encode(gzcompress($suma));
  949. $im = imagecreate((strlen($string) - 1) * 10, 24);
  950. $bg = imagecolorallocate($im, 255, 255, 255);
  951. $textcolor = imagecolorallocate($im, 0, 0, 0);
  952. imagestring($im, 5, 0, 0, $string, $textcolor);
  953. ob_start();
  954. imagepng($im);
  955. $image = ob_get_contents();
  956. ob_end_clean();
  957. /*
  958. $image = new Imagick();
  959. $draw = new ImagickDraw();
  960. $pixel = new ImagickPixel('white');
  961. $image->newImage(200, 24, $pixel);
  962. // $image->setFont("schema/WPS_Functions/mapserver_gml_to_png/map/fonts/Arial_Bold.ttf");
  963. // $image->newPseudoImage(100, 100, "label:\"{$a} {$op} {$b}\"");
  964. // $image->newPseudoImage(100, 100, "caption:Hello");
  965. $image->setImageFormat('png');
  966. $draw->setFillColor('black');
  967. // $draw->setFont('Arial');
  968. $draw->setFontSize(24);
  969. $image->annotateImage($draw, 0, 24, 0, $s);
  970. $image->trimImage(0);
  971. */
  972. $imageBase64 = base64_encode($image);
  973. //echo $imageBase64;
  974. ?>
  975. <div style="text-align: center;">
  976. <h2>Czy jesteś pewien, że chcesz usunąć<br/><b>wszystkie dane</b> z tabeli <?=$tables[$this->SOURCE['TABLE']]?>?</h2><br/>
  977. <h3>Podaj wynik działania:</h3>
  978. <form method="post">
  979. <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/>
  980. <?php
  981. if ($this->SOURCE['TABLE'] == 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA'):
  982. ?>
  983. <h4><input type="checkbox" name="deleteFiles"/>&nbsp;&nbsp;Usuń również wszystkie pliki</h4><br/>
  984. <?php
  985. endif;
  986. ?>
  987. <button type="submit" class="btn btn-primary" name="action" value="doClearTable" style="width: 80px;">Tak</button>
  988. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>">
  989. <a href="<?=$this->REFERER?>" class="btn btn-default" style="width: 80px;">Anuluj</a>
  990. </form>
  991. </div>
  992. <?php
  993. }
  994. private function clearTable() {
  995. SE_Layout::alert('warning', 'Funkcja w fazie testów - niczego jeszcze nie usuwa');
  996. $query = "select count(*) from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` where `FILE_STATUS` = 'IN_PROGRESS'";
  997. if (DB::getPDO()->fetchValue($query)) {
  998. ?>
  999. <div style="text-align: center;">
  1000. <h2>Nie można usunąć żadnych danych<br/>(wykryto uruchomione zadania)</h2><br/>
  1001. <a href="<?=$this->REFERER?>" class="btn btn-primary" style="width: 80px;">Powrót</a>
  1002. </div>
  1003. <?php
  1004. return;
  1005. }
  1006. $action = V::get('action', '', $_POST);
  1007. switch ($action) {
  1008. case "doClearTable":
  1009. $this->clearTable_do();
  1010. break;
  1011. default: $this->clearTable_form();
  1012. }
  1013. }
  1014. public function defaultAction() {
  1015. SE_Layout::gora();
  1016. SE_Layout::menu();
  1017. if (isset($_SESSION['REFERER'])) {
  1018. $this->REFERER = $_SESSION['REFERER'];
  1019. unset($_SESSION['REFERER']);
  1020. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  1021. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  1022. if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
  1023. elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
  1024. elseif (($ID = V::get('ID_BI_audit_KRS', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  1025. elseif (($ID = V::get('ID_BI_audit_MSIG', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_MSIG';
  1026. elseif (($ID = V::get('ID_BI_audit_KRS_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS_person';
  1027. if ($this->SOURCE) {
  1028. $this->SOURCE['ID'] = $ID;
  1029. $this->powiazania();
  1030. }
  1031. elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
  1032. $_subUrlAction = V::get('_subUrlAction', '', $_GET);
  1033. switch ($TABLE) {
  1034. case "default_db/BI_audit_ENERGA_PRACOWNICY":
  1035. $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
  1036. switch ($_subUrlAction) {
  1037. case "clearTable":
  1038. $this->clearTable();
  1039. break;
  1040. case "importFromKRS":
  1041. $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  1042. $this->importToPracownicy();
  1043. break;
  1044. default: SE_Layout::alert('danger', 'Błąd parametru #21');
  1045. }
  1046. break;
  1047. case "default_db/BI_audit_ENERGA_RUM_KONTRAHENCI":
  1048. $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI';
  1049. switch ($_subUrlAction) {
  1050. case "clearTable":
  1051. $this->clearTable();
  1052. break;
  1053. default: SE_Layout::alert('danger', 'Błąd parametru #22');
  1054. }
  1055. break;
  1056. case "default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  1057. $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
  1058. switch ($_subUrlAction) {
  1059. case "clearTable":
  1060. $this->clearTable();
  1061. break;
  1062. efault: SE_Layout::alert('danger', 'Błąd parametru #23');
  1063. }
  1064. break;
  1065. default: SE_Layout::alert('danger', 'Błąd parametru #1');
  1066. }
  1067. }
  1068. else SE_Layout::alert('danger', 'Błąd parametru #0');
  1069. SE_Layout::dol();
  1070. }
  1071. private static function truncatePowiazaniaFromDB($ID) {
  1072. $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  1073. if (!$refTables) return null;
  1074. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  1075. $refTables = array_diff($refTables, [$refPowiazaniaToPowiazaniaRow]);
  1076. $query = "delete from `" . implode("`, `", $refTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  1077. foreach ($refTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  1078. $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  1079. DB::getPDO()->query($query);
  1080. }
  1081. private static function deleteResultsFromDB($ID) {
  1082. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  1083. $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
  1084. $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  1085. $sqlDeleteFrom = "delete from
  1086. `{$refPowiazaniaToPowiazaniaRow}`,
  1087. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
  1088. `{$refPowiazaniaRowToPowiazaniaRowObject}`,
  1089. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
  1090. $sqlUsing = "
  1091. using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  1092. join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
  1093. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
  1094. join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
  1095. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
  1096. $sqlWhere = "
  1097. where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  1098. foreach ($refTables as $refTable) {
  1099. $sqlDeleteFrom .= ",\n`{$refTable}`";
  1100. $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  1101. }
  1102. $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
  1103. DB::getPDO()->query($query);
  1104. }
  1105. public function doGenerate() {
  1106. $generatePhpScript = function($function) {
  1107. return '<?php
  1108. ini_set("memory_limit", "4G");
  1109. define("DS", DIRECTORY_SEPARATOR);
  1110. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  1111. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  1112. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  1113. ini_set("display_startup_errors", "0");
  1114. ini_set("display_errors", "1");
  1115. ini_set("log_errors", "1");
  1116. ini_set("error_log", "/var/log/apache2/error_log");
  1117. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  1118. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  1119. date_default_timezone_set("Europe/Warsaw");
  1120. Lib::loadClass("Router");
  1121. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  1122. ';
  1123. };
  1124. try {
  1125. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  1126. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  1127. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  1128. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  1129. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  1130. ### Ustawienie zmiennych
  1131. $powiazaniaDirLocation = self::getMainDirectory();
  1132. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1133. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  1134. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1135. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1136. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  1137. ### Utworzenie niezbędnych katalogów i plików
  1138. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0770, true);
  1139. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  1140. ### 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
  1141. $sqlArr = [
  1142. 'BI_analiza_reloadCache' => 'No',
  1143. ];
  1144. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Part', 'Full') and FILE_STATUS = 'TO_GENERATE'";
  1145. $result = DB::getPDO()->fetchAll($query);
  1146. foreach ($result as $row) {
  1147. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  1148. }
  1149. /* 2018-04-19 - zmieniono działanie silnika tak, aby sam wykrywał czy należy wykonać pełne odświeżenie cache
  1150. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  1151. $doGenerate = true;
  1152. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full') and FILE_STATUS = 'TO_GENERATE'";
  1153. $result = DB::getPDO()->fetchAll($query);
  1154. if ($result) {
  1155. $doGenerate = false;
  1156. $sqlArr = [];
  1157. if (file_exists($reloadCachePhpFile)) {
  1158. if (file_exists($reloadCacheResultFile)) {
  1159. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  1160. if ($reloadCacheResult == "ok") {
  1161. $sqlArr = [
  1162. 'FILE_STATUS_info' => 'Ukończono pełne Odświeżenie cache, oczekiwanie na wygenerowanie powiązań',
  1163. 'BI_analiza_reloadCache' => 'No',
  1164. ];
  1165. $doGenerate = true;
  1166. } else {
  1167. $sqlArr = [
  1168. 'FILE_STATUS' => 'ERROR',
  1169. 'FILE_STATUS_info' => "Wystąpił błąd podczas pełnego odświeżania cache ({$reloadCacheResult})",
  1170. ];
  1171. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  1172. $result = DB::getPDO()->fetchAll($query);
  1173. }
  1174. unlink($reloadCachePhpFile);
  1175. unlink($reloadCachePidFile);
  1176. unlink($reloadCacheResultFile);
  1177. } elseif (file_exists($reloadCachePidFile)) {
  1178. $pid = file_get_contents($reloadCachePidFile);
  1179. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1180. $processShouldBeRunning = "php {$reloadCachePhpFile}";
  1181. if ($processRunning != $processShouldBeRunning) {
  1182. if (!file_exists($reloadCacheResultFile)) {
  1183. $sqlArr = [
  1184. 'FILE_STATUS' => 'ERROR',
  1185. 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas pełnego odświeżania cache - nie znaleziono procesu potomnego",
  1186. ];
  1187. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  1188. $result = DB::getPDO()->fetchAll($query);
  1189. unlink($reloadCachePhpFile);
  1190. unlink($reloadCachePidFile);
  1191. unlink($reloadCacheResultFile);
  1192. }
  1193. }
  1194. }
  1195. } else {
  1196. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1197. $result2 = DB::getPDO()->fetchValue($query);
  1198. if ($result2) {
  1199. $sqlArr = [
  1200. 'FILE_STATUS_info' => 'Wstrzymano pełne odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  1201. ];
  1202. } else {
  1203. $sqlArr = [
  1204. 'FILE_STATUS_info' => 'W trakcie pełnego odświeżania cache',
  1205. ];
  1206. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
  1207. $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
  1208. file_put_contents($reloadCachePhpFile, $generatePhpScript("doReloadCache({$fullReloadCache})"));
  1209. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  1210. }
  1211. }
  1212. if ($sqlArr) {
  1213. foreach ($result as $row) {
  1214. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  1215. }
  1216. }
  1217. }
  1218. */ $doGenerate = true;
  1219. ### Generowanie powiązań
  1220. if ($doGenerate) {
  1221. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
  1222. $result = DB::getPDO()->fetchAll($query);
  1223. foreach ($result as $row) {
  1224. $sqlArr = [
  1225. 'ID' => $row['ID'],
  1226. 'FILE_STATUS' => 'IN_PROGRESS',
  1227. 'FILE_STATUS_info' => 'Zadanie wyzwolone',
  1228. ];
  1229. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1230. self::deleteResultsFromDB($row['ID']);
  1231. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1232. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1233. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  1234. $generatePowiazaniaProgressFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.progress";
  1235. if (file_exists($generatePowiazaniaResultFile)) unlink ($generatePowiazaniaResultFile);
  1236. if (file_exists($generatePowiazaniaProgressFile)) unlink ($generatePowiazaniaProgressFile);
  1237. file_put_contents($generatePowiazaniaPhpFile, $generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  1238. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  1239. }
  1240. }
  1241. ### Weryfikacja świeżo wygenerowanych powiązań
  1242. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1243. $result = DB::getPDO()->fetchAll($query);
  1244. foreach ($result as $row) {
  1245. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1246. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  1247. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1248. $error = false;
  1249. $success = false;
  1250. $sqlArr = [];
  1251. if (file_exists($generatePowiazaniaResultFile)) {
  1252. $generatePowiazaniaResult = json_decode(file_get_contents($generatePowiazaniaResultFile), true);
  1253. if ($generatePowiazaniaResult['result'] == "ok") {
  1254. $powiazanieDirLocation = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  1255. if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0770, false);
  1256. if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
  1257. else $success = true;
  1258. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult['message']})";
  1259. } elseif (file_exists($generatePowiazaniaPidFile)) {
  1260. $pid = file_get_contents($generatePowiazaniaPidFile);
  1261. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1262. $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
  1263. if ($processRunning != $processShouldBeRunning) {
  1264. if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
  1265. }
  1266. }
  1267. if ($error) {
  1268. $sqlArr = [
  1269. 'FILE_STATUS' => 'ERROR',
  1270. 'FILE_STATUS_info' => $error,
  1271. ];
  1272. //self::deleteResultsFromDB($row['ID']);
  1273. //if (file_exists($xmlFile)) unlink($xmlFile);
  1274. } elseif ($success) {
  1275. $sqlArr = [
  1276. 'FILE_STATUS' => 'GENERATED',
  1277. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  1278. ];
  1279. if ($generatePowiazaniaResult['parts']) {
  1280. for ($i = 1; $i <= $generatePowiazaniaResult['parts']; $i++) {
  1281. $partNo = str_pad($i, 6, '0', STR_PAD_LEFT);
  1282. $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}_{$partNo}";
  1283. $generatePowiazaniaXmlFile = "{$generateFilesName}.xml";
  1284. $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
  1285. $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
  1286. $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
  1287. $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.xml";
  1288. $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.pdf";
  1289. $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}";
  1290. $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}.zip";
  1291. if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
  1292. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1293. if (file_exists($generatePowiazaniaHtmlDir)) {
  1294. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1295. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1296. }
  1297. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1298. }
  1299. } else {
  1300. $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}";
  1301. $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
  1302. $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
  1303. $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
  1304. $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.xml";
  1305. $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.pdf";
  1306. $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}";
  1307. $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}.zip";
  1308. if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
  1309. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1310. if (file_exists($generatePowiazaniaHtmlDir)) {
  1311. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1312. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1313. }
  1314. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1315. }
  1316. }
  1317. if ($sqlArr) {
  1318. $sqlArr['ID'] = $row['ID'];
  1319. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1320. if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
  1321. if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
  1322. if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
  1323. }
  1324. }
  1325. } catch (Exception $e) {
  1326. echo $e->getMessage()."\n";
  1327. }
  1328. }
  1329. private static function importPracownicy() { //TODO
  1330. $fields = [
  1331. 'BI_audit_ENERGA_PRACOWNICY' => [
  1332. 'PERNR',
  1333. 'imiona',
  1334. 'nazwisko',
  1335. 'pesel',
  1336. 'nr_konta',
  1337. 'jednostka_organizacyjna',
  1338. 'nip',
  1339. 'regon',
  1340. 'krs',
  1341. 'source',
  1342. ],
  1343. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1344. 'kodPocztowy',
  1345. 'miejscowosc',
  1346. 'ulica',
  1347. 'nrBudynku',
  1348. 'nrLokalu',
  1349. ],
  1350. ];
  1351. $query = "select * from `BI_audit_ENERGA_PRACOWNICY_import` where `importResult` = 'none'";
  1352. $pracownicy = DB::getPDO()->query($query);
  1353. while ($pracownik = $pracownicy->fetch()) {
  1354. $ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `pesel` = '{$pracownik['pesel']}'");
  1355. $sqlArr = [];
  1356. foreach ($fields['BI_audit_ENERGA_PRACOWNICY'] as $field) $sqlArr[$field] = trim($pracownik[$field]);
  1357. if ($ID_pracownik) DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY', 'ID', $ID, $sqlArr);
  1358. else $ID_pracownik = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', $sqlArr);
  1359. $sqlArr = [];
  1360. foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $field) {
  1361. $sqlArr[$field] = trim($pracownik[$field]);
  1362. if (!$sqlArr[$field]) unset($sqlArr[$field]);
  1363. }
  1364. if (!$sqlArr) break;
  1365. $sql = [];
  1366. // foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $field) {
  1367. // if (isset($sqlArr[$field])) $sql[] = "`{$field}` = " . DUPA;
  1368. // }
  1369. }
  1370. }
  1371. private static function reloadCache_parseUmowy($full = false) {
  1372. $fields = [
  1373. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1374. 'Tytul_dokumentu',
  1375. 'Pelna_nazwa_kontrahenta',
  1376. 'NIP',
  1377. 'REGON',
  1378. 'KRS',
  1379. 'Kraj',
  1380. 'Kod_pocztowy',
  1381. 'Miejscowosc',
  1382. 'Ulica',
  1383. 'Numer_budynku',
  1384. 'Numer_mieszkania_lokalu',
  1385. 'TERYT_SYM',
  1386. 'TERYT_SYM_UL',
  1387. ],
  1388. 'BI_audit_KRS' => [
  1389. '"Zaimportowanoz KRS na podstawie umowy"',
  1390. 'nazwa',
  1391. 'nip',
  1392. 'regon',
  1393. 'krs',
  1394. 'A_kraj',
  1395. 'A_kod',
  1396. 'A_miejscowosc',
  1397. 'A_ulica',
  1398. 'A_nrDomu',
  1399. 'A_nrLokalu',
  1400. 'TERYT_SYM',
  1401. 'TERYT_SYM_UL',
  1402. ],
  1403. 'BI_audit_CEIDG' => [
  1404. '"Zaimportowano z CEiDG na podstawie umowy"',
  1405. 'firma',
  1406. 'nip',
  1407. 'regon',
  1408. 'null',
  1409. 'kraj',
  1410. 'kodPocztowy',
  1411. 'miejscowosc',
  1412. 'ulica',
  1413. 'budynek',
  1414. 'lokal',
  1415. 'TERYT_SYM',
  1416. 'TERYT_SYM_UL',
  1417. ],
  1418. ];
  1419. $refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  1420. if ($full) {
  1421. DB::getPDO()->query("truncate table `{$refTable}`");
  1422. DB::getPDO()->query("update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
  1423. }
  1424. $query = <<<SQL
  1425. update `BI_audit_ENERGA_RUM_UMOWY` set `Wartosc` = replace(
  1426. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_`,
  1427. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_`,
  1428. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_`,
  1429. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_`,
  1430. if(`Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_`, 0))))),
  1431. ',', '.') where `A_STATUS` = 'WAITING';
  1432. SQL;
  1433. DB::getPDO()->query($query);
  1434. $query = "select `ID`, `Strony_umowy` from `BI_audit_ENERGA_RUM_UMOWY` where `A_STATUS` = 'WAITING'";
  1435. $result = DB::getPDO()->fetchAll($query);
  1436. foreach ($result as $row) {
  1437. $ID = $row['ID'];
  1438. $strony = array_map('trim', explode("|", $row['Strony_umowy']));
  1439. $K_IDs = [];
  1440. foreach ($strony as $item) {
  1441. $strona = array_map('trim', explode(";", $item));
  1442. $nr = null;
  1443. if (count($strona) == 3) $i = 1;//$nr = $strona[1];
  1444. elseif (count($strona) == 4) $i = 2;//$nr = $strona[2];
  1445. elseif (count($strona) >= 5 && count($strona) <= 6) $i = 3;//$nr = $strona[3];
  1446. else $i = null;
  1447. if ($i) $nr = $strona[$i];
  1448. $notFound = false;
  1449. if (is_numeric($nr)) {
  1450. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Numer_kontrahenta = '{$nr}'";
  1451. if ($K_ID = DB::getPDO()->fetchValue($query)) {
  1452. $K_IDs[] = $K_ID;
  1453. } else {
  1454. $nazwa = $strona[$i+1];
  1455. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Pelna_nazwa_kontrahenta = '" . addslashes($nazwa) . "'";
  1456. if ($result2 = DB::getPDO()->fetchAll($query)) {
  1457. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1458. } else $notFound = true;
  1459. }
  1460. } else $notFound = true;
  1461. if ($notFound) {
  1462. list($nip, $regon) = self::parseNipRegon($item);
  1463. if ($nip || $regon) {
  1464. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where NIP = '{$nip}' or REGON = '{$regon}'";
  1465. if ($result2 = DB::getPDO()->fetchall($query)) {
  1466. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1467. } else {
  1468. $query = "select ID from BI_audit_KRS where nip = '{$nip}' or regon = '{$regon}'";
  1469. if ($result2 = DB::getPDO()->fetchall($query)) {
  1470. foreach ($result2 as $item) {
  1471. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1472. " select " . implode(', ', $fields['BI_audit_KRS']) . " from BI_audit_KRS where ID = '{$item['ID']}'";
  1473. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1474. }
  1475. } else {
  1476. $query = "select ID from BI_audit_CEIDG where nip = '{$nip}' or regon = '{$regon}'";
  1477. if ($result2 = DB::getPDO()->fetchall($query)) {
  1478. foreach ($result2 as $item) {
  1479. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1480. " select " . implode(', ', $fields['BI_audit_CEIDG']) .
  1481. " from BI_audit_CEIDG where ID = '{$item['ID']}'";
  1482. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1483. }
  1484. }
  1485. }
  1486. }
  1487. }
  1488. }
  1489. }
  1490. foreach ($K_IDs as $K_ID) {
  1491. if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
  1492. DB::getPDO()->query("insert into `{$refTable}` (PRIMARY_KEY, REMOTE_PRIMARY_KEY) values ({$ID}, {$K_ID})");
  1493. }
  1494. }
  1495. DB::getPDO()->update('BI_audit_ENERGA_RUM_UMOWY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
  1496. }
  1497. $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";
  1498. $result = DB::getPDO()->fetchAll($query);
  1499. foreach ($result as $row) {
  1500. $query = "select nip, regon, krs from BI_audit_KRS where nip = '{$row['NIP']}' or regon = '{$row['REGON']}' or krs = '{$row['KRS']}'";
  1501. if ($items = DB::getPDO()->fetchAll($query)) {
  1502. list($nip, $regon, $krs) = [$items[0]["nip"], $items[0]["regon"], $items[0]["krs"]];
  1503. if (count($items) > 1) {
  1504. for ($i = 1; $i < count($items); $i++) {
  1505. if ($nip != $items[$i]["nip"]) $nip = null;
  1506. if ($regon != $items[$i]["regon"]) $regon = null;
  1507. if ($krs != $items[$i]["krs"]) $krs = null;
  1508. }
  1509. }
  1510. $set = [];
  1511. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  1512. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  1513. if ($krs && $krs != $row['KRS']) $set[] = "KRS = '{$krs}'";
  1514. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row['ID']}'");
  1515. }
  1516. }
  1517. $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";
  1518. $result = DB::getPDO()->fetchAll($query);
  1519. foreach ($result as $row) {
  1520. $query = "select nip, regon from BI_audit_CEIDG where nip = '{$row['NIP']}' or regon = '{$row['REGON']}'";
  1521. if ($items = DB::getPDO()->fetchAll($query)) {
  1522. list($nip, $regon) = [$items[0]["nip"], $items[0]["regon"]];
  1523. if (count($items) > 1) {
  1524. for ($i = 1; $i < count($items); $i++) {
  1525. if ($nip != $items[$i]["nip"]) $nip = null;
  1526. if ($regon != $items[$i]["regon"]) $regon = null;
  1527. }
  1528. }
  1529. $set = [];
  1530. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  1531. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  1532. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row->ID}'");
  1533. }
  1534. }
  1535. }
  1536. public static function reloadCache_reTeryt($full = false, $forceAll = false) {
  1537. Lib::loadClass('Teryt');
  1538. $tables = [
  1539. 'BI_audit_CEIDG' => [
  1540. 'fields' => [
  1541. 'wojewodztwo' => 'wojewodztwo',
  1542. 'powiat' => 'powiat',
  1543. 'gmina' => 'gmina',
  1544. 'miejscowosc' => 'miejscowosc',
  1545. 'ulica' => 'ulica',
  1546. 'kodPocztowy' => 'kodPocztowy',
  1547. ],
  1548. 'fieldsTeryt' => [
  1549. 'TERYT_SYM' => 'TERYT_SYM',
  1550. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1551. 'nrDomu' => 'budynek',
  1552. 'nrLokalu' => 'lokal',
  1553. ],
  1554. 'base' => '1',
  1555. ],
  1556. 'BI_audit_CEIDG_pelnomocnicy' => [
  1557. 'fields' => [
  1558. 'wojewodztwo' => 'wojewodztwo',
  1559. 'powiat' => 'powiat',
  1560. 'gmina' => 'gmina',
  1561. 'miejscowosc' => 'miejscowosc',
  1562. 'ulica' => 'ulica',
  1563. 'kodPocztowy' => 'kodPocztowy',
  1564. ],
  1565. 'fieldsTeryt' => [
  1566. 'TERYT_SYM' => 'TERYT_SYM',
  1567. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1568. 'nrDomu' => 'budynek',
  1569. 'nrLokalu' => 'lokal',
  1570. ],
  1571. 'base' => '1',
  1572. ],
  1573. 'BI_audit_ENERGA_PRACOWNICY' => [
  1574. 'fields' => [
  1575. 'miejscowosc' => 'miejscowosc',
  1576. 'kodPocztowy' => 'kodPocztowy',
  1577. 'ulica' => 'ulica',
  1578. ],
  1579. 'fieldsTeryt' => [
  1580. 'TERYT_SYM' => 'TERYT_SYM',
  1581. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1582. 'nrDomu' => 'nr',
  1583. 'nrLokalu' => 'nrLokalu',
  1584. ],
  1585. 'base' => '0',
  1586. ],
  1587. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1588. 'fields' => [
  1589. 'kodPocztowy' => 'kodPocztowy',
  1590. 'miejscowosc' => 'miejscowosc',
  1591. 'ulica' => 'ulica',
  1592. ],
  1593. 'fieldsTeryt' => [
  1594. 'TERYT_SYM' => 'TERYT_SYM',
  1595. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1596. 'nrDomu' => 'nrBudynku',
  1597. 'nrLokalu' => 'nrLokalu',
  1598. ],
  1599. 'base' => '0',
  1600. ],
  1601. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1602. 'fields' => [
  1603. 'kodPocztowy' => 'Kod_pocztowy',
  1604. 'miejscowosc' => 'Miejscowosc',
  1605. 'ulica' => 'Ulica',
  1606. ],
  1607. 'fieldsTeryt' => [
  1608. 'TERYT_SYM' => 'TERYT_SYM',
  1609. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1610. 'nrDomu' => 'Numer_budynku',
  1611. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  1612. ],
  1613. 'base' => '0',
  1614. ],
  1615. 'BI_audit_KRS' => [
  1616. 'fields' => [
  1617. 'wojewodztwo' => 'S_wojewodztwo',
  1618. 'powiat' => 'S_powiat',
  1619. 'gmina' => 'S_gmina',
  1620. 'miejscowosc' => 'A_miejscowosc',
  1621. 'ulica' => 'A_ulica',
  1622. 'kodPocztowy' => 'A_kod',
  1623. ],
  1624. 'fieldsTeryt' => [
  1625. 'TERYT_SYM' => 'TERYT_SYM',
  1626. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1627. 'nrDomu' => 'A_nrDomu',
  1628. 'nrLokalu' => 'A_nrLokalu',
  1629. ],
  1630. 'base' => '1',
  1631. ],
  1632. 'BI_audit_KRS_address' => [
  1633. 'fields' => [
  1634. 'wojewodztwo' => 'S_wojewodztwo',
  1635. 'powiat' => 'S_powiat',
  1636. 'gmina' => 'S_gmina',
  1637. 'miejscowosc' => 'A_miejscowosc',
  1638. 'ulica' => 'A_ulica',
  1639. 'kodPocztowy' => 'A_kod',
  1640. ],
  1641. 'fieldsTeryt' => [
  1642. 'TERYT_SYM' => 'TERYT_SYM',
  1643. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1644. 'nrDomu' => 'A_nrDomu',
  1645. 'nrLokalu' => 'A_nrLokalu',
  1646. ],
  1647. 'base' => '1',
  1648. ],
  1649. 'BI_audit_MSIG_address' => [
  1650. 'fields' => [
  1651. 'wojewodztwo' => 'S_wojewodztwo',
  1652. 'powiat' => 'S_powiat',
  1653. 'gmina' => 'S_gmina',
  1654. 'miejscowosc' => 'A_miejscowosc',
  1655. 'ulica' => 'A_ulica',
  1656. 'kodPocztowy' => 'A_kod',
  1657. ],
  1658. 'fieldsTeryt' => [
  1659. 'TERYT_SYM' => 'TERYT_SYM',
  1660. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1661. 'nrDomu' => 'A_nrDomu',
  1662. 'nrLokalu' => 'A_nrLokalu',
  1663. ],
  1664. 'base' => '1',
  1665. ],
  1666. ];
  1667. foreach ($tables as $table => $tableConf) {
  1668. DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrDomu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrDomu']}`) = ''");
  1669. DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrLokalu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrLokalu']}`) = ''");
  1670. $where = ($full && ($forceAll || (!$tableConf['base']))) ? "" : "where `TERYT_SYM` is null and `cached` = 0";
  1671. $query = "select * from `{$table}` {$where}";
  1672. $refTable = BiAuditRefTables::getRefTable($table, 'TERYT_adresy', true);
  1673. $terytJoinArr = [];
  1674. foreach ($tableConf['fieldsTeryt'] as $terytField => $tableField) {
  1675. $terytJoinArr[] = (
  1676. $terytField == 'nrLokalu'
  1677. ? "coalesce(`teryt`.`{$terytField}`, '') = coalesce(`table`.`{$tableField}`, '')"
  1678. : "`teryt`.`{$terytField}` = `table`.`{$tableField}`"
  1679. );
  1680. }
  1681. $terytJoin = implode(" and ", $terytJoinArr);
  1682. $insertFields = "`" . implode("`, `", array_keys($tableConf['fieldsTeryt'])) . "`";
  1683. $selectFields = "`" . implode("`, `", $tableConf['fieldsTeryt']) . "`";
  1684. $adresy = DB::getPDO()->query($query);
  1685. while ($adres = $adresy->fetch()) {
  1686. DB::getPDO()->query("delete from `{$refTable}` where `PRIMARY_KEY` = '{$adres['ID']}'");
  1687. if (!($forceAll and $adres['TERYT_SYM'])) {
  1688. $search = [];
  1689. foreach ($tableConf['fields'] as $field => $param) if (!empty($adres[$param])) $search[$field] = $adres[$param];
  1690. try {
  1691. $teryt = Teryt::search($search);
  1692. } catch (Exception $e) {
  1693. continue;
  1694. }
  1695. if (empty($teryt['SYM'])) continue;
  1696. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  1697. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  1698. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  1699. }
  1700. if (!trim($adres[$tableConf['fieldsTeryt']['nrDomu']])) continue;
  1701. $terytID = DB::getPDO()->fetchValue("select `teryt`.`ID` from `TERYT_adresy` as `teryt` join `{$table}` as `table` on {$terytJoin} where `table`.`ID` = '{$adres['ID']}'");
  1702. if (!$terytID) {
  1703. if (DB::getPDO()->query("insert into `TERYT_adresy` ({$insertFields}) select {$selectFields} from `{$table}` where `ID` = '{$adres['ID']}'")) {
  1704. if (!($terytID = DB::getPDO()->lastInsertId())) {
  1705. throw new Exception("Błąd dodania rekordu do TERYT_adresy #1");
  1706. }
  1707. } else {
  1708. throw new Exception("Błąd dodania rekordu do TERYT_adresy #2");
  1709. }
  1710. }
  1711. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $adres['ID'], 'REMOTE_PRIMARY_KEY' => $terytID]);
  1712. }
  1713. }
  1714. }
  1715. private static function reloadCache_updateAll($full, $onlyBase) {
  1716. $tablesConf = [
  1717. 'BI_audit_CEIDG' => [
  1718. 'fields' => [
  1719. 'nip' => 'nip',
  1720. 'regon' => 'regon',
  1721. ],
  1722. 'base' => '1',
  1723. ],
  1724. 'BI_audit_CEIDG_pelnomocnicy' => [
  1725. 'fields' => [
  1726. 'nip' => 'nip',
  1727. ],
  1728. 'base' => '1',
  1729. ],
  1730. 'BI_audit_CEIDG_powiazania' => [
  1731. 'fields' => [
  1732. 'nip' => 'nip',
  1733. 'regon' => 'regon',
  1734. ],
  1735. 'base' => '1',
  1736. ],
  1737. 'BI_audit_ENERGA_PRACOWNICY' => [
  1738. 'fields' => [
  1739. 'nip' => 'nip',
  1740. 'regon' => 'regon',
  1741. 'pesel' => 'pesel',
  1742. 'krs' => 'krs',
  1743. ],
  1744. 'base' => '0',
  1745. //'where' => '',
  1746. ],
  1747. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1748. 'fields' => [],
  1749. 'base' => '0',
  1750. //'where' => '',
  1751. ],
  1752. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1753. 'fields' => [
  1754. 'krs' => 'KRS',
  1755. 'nip' => 'NIP',
  1756. 'regon' => 'REGON',
  1757. 'pesel' => 'PESEL',
  1758. ],
  1759. 'base' => '0',
  1760. 'where' => "and ownCompany != 'Y'",
  1761. ],
  1762. 'BI_audit_KRS' => [
  1763. 'fields' => [
  1764. 'krs' => 'krs',
  1765. 'nip' => 'nip',
  1766. 'regon' => 'regon',
  1767. ],
  1768. 'base' => '1',
  1769. ],
  1770. 'BI_audit_KRS_address' => [
  1771. 'fields' => [],
  1772. 'base' => '1',
  1773. ],
  1774. 'BI_audit_KRS_company' => [
  1775. 'fields' => [
  1776. 'regon' => 'regon',
  1777. 'krs' => 'krs',
  1778. ],
  1779. 'base' => '1',
  1780. ],
  1781. 'BI_audit_KRS_person' => [
  1782. 'fields' => [
  1783. 'pesel' => 'pesel',
  1784. ],
  1785. 'base' => '1',
  1786. ],
  1787. 'BI_audit_MSIG' => [
  1788. 'fields' => [
  1789. 'krs' => 'krs',
  1790. 'nip' => 'nip',
  1791. 'regon' => 'regon',
  1792. ],
  1793. 'base' => '1',
  1794. ],
  1795. 'BI_audit_MSIG_address' => [
  1796. 'fields' => [],
  1797. 'base' => '1',
  1798. ],
  1799. 'BI_audit_MSIG_company' => [
  1800. 'fields' => [
  1801. 'regon' => 'regon',
  1802. 'krs' => 'krs',
  1803. ],
  1804. 'base' => '1',
  1805. ],
  1806. 'BI_audit_MSIG_person' => [
  1807. 'fields' => [
  1808. 'pesel' => 'pesel',
  1809. ],
  1810. 'base' => '1',
  1811. ],
  1812. // 'BI_audit_KW_requested_person' => [
  1813. // 'fields' => [
  1814. // 'pesel' => 'Seller_person_pesel',
  1815. // 'krs' => 'Seller_person_KRS',
  1816. // 'nip' => 'Seller_person_NIP',
  1817. // 'regon' => 'Seller_person_REGON',
  1818. // ],
  1819. // 'base' => '0',
  1820. // //'where' => '',
  1821. // ],
  1822. 'TERYT_adresy' => [
  1823. 'fields' => [],
  1824. 'base' => '1',
  1825. ],
  1826. ];
  1827. $refTablesConf = [
  1828. 'BI_audit_CEIDG' => [
  1829. 'refTablesTo' => [
  1830. 'BI_audit_CEIDG_pelnomocnicy',
  1831. 'BI_audit_CEIDG_powiazania',
  1832. 'TERYT_adresy',
  1833. ],
  1834. 'base' => 1,
  1835. ],
  1836. 'BI_audit_CEIDG_pelnomocnicy' => [
  1837. 'refTablesTo' => [
  1838. 'TERYT_adresy',
  1839. ],
  1840. 'base' => 1,
  1841. ],
  1842. 'BI_audit_ENERGA_PRACOWNICY' => [
  1843. 'refTablesTo' => [
  1844. 'BI_audit_ENERGA_PRACOWNICY_adresy',
  1845. 'TERYT_adresy',
  1846. ],
  1847. 'base' => 0,
  1848. ],
  1849. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1850. 'refTablesTo' => [
  1851. 'TERYT_adresy',
  1852. ],
  1853. 'base' => 0,
  1854. ],
  1855. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1856. 'refTablesTo' => [
  1857. 'TERYT_adresy',
  1858. ],
  1859. 'base' => 0,
  1860. ],
  1861. 'BI_audit_KRS' => [
  1862. 'refTablesTo' => [
  1863. 'BI_audit_KRS_address',
  1864. 'BI_audit_KRS_company',
  1865. 'BI_audit_KRS_person',
  1866. 'TERYT_adresy',
  1867. ],
  1868. 'base' => 1,
  1869. ],
  1870. 'BI_audit_KRS_address' => [
  1871. 'refTablesTo' => [
  1872. 'TERYT_adresy',
  1873. ],
  1874. 'base' => 1,
  1875. ],
  1876. 'BI_audit_MSIG' => [
  1877. 'refTablesTo' => [
  1878. 'BI_audit_MSIG_address',
  1879. 'BI_audit_MSIG_company',
  1880. 'BI_audit_MSIG_person',
  1881. ],
  1882. 'base' => 1,
  1883. ],
  1884. 'BI_audit_MSIG_address' => [
  1885. 'refTablesTo' => [
  1886. 'TERYT_adresy',
  1887. ],
  1888. 'base' => 1,
  1889. ],
  1890. ];
  1891. $sourceTables = ['BI_audit_ENERGA_PRACOWNICY'];
  1892. if ($full) {
  1893. foreach ($tablesConf as $table => $tableConf) if (!$tableConf['base']) $queries[] = "update `{$table}` set `cached` = 0";
  1894. $queries[] = "delete from `BI_audit_ALL` where `BASE` = 0";
  1895. // $queries[] = "optimize table `BI_audit_ALL`";
  1896. $queries[] = "delete from `BI_audit_ALL_ref` where `BASE` = 0";
  1897. // $queries[] = "optimize table `BI_audit_ALL_ref`";
  1898. $allTables = [];
  1899. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  1900. $allTables[] = $refTableFrom;
  1901. // if ($refTableConf['base']) continue;
  1902. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  1903. $allTables[] = $refTableTo;
  1904. if ($refTableConf['base']) continue;
  1905. $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
  1906. $queries[] = "update `{$refTable}` set `A_STATUS` = 'WAITNG' where `A_STATUS` = 'NORMAL'";
  1907. // $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}'";
  1908. }
  1909. }
  1910. $allTables = array_unique($allTables);
  1911. foreach ($allTables as $refTableFrom) {
  1912. foreach ($allTables as $refTableTo) {
  1913. if ($refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, false)) {
  1914. $queries[] = "delete from `{$refTable}` where `TRANSACTION_ID` = '-1'";
  1915. $queries[] = "optimize table `{$refTable}`";
  1916. $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";
  1917. }
  1918. }
  1919. }
  1920. }
  1921. foreach ($tablesConf as $table => $tableConf) {
  1922. if ($onlyBase && (!$tableConf['base'])) continue;
  1923. $where = "where `cached` = 0";
  1924. if (!empty($tableConf['where'])) $where .= " {$tableConf['where']}";
  1925. // $queries[] = "insert into `BI_audit_ALL` (`REMOTE_TABLE`, `REMOTE_ID`, `BASE`, " . implode(", ", array_keys($tableConf['fields'])) .
  1926. // ") select '{$table}', ID, '{$tableConf['base']}', " . implode(", ", $tableConf['fields']) . " from `{$table}` {$where}";
  1927. $fields = ["`REMOTE_TABLE`", "`REMOTE_ID`", "`BASE`"];
  1928. foreach (array_keys($tableConf['fields']) as $field) $fields[] = "`{$field}`";
  1929. $values = ["'{$table}'", "`ID`", "'{$tableConf['base']}'"];
  1930. foreach ($tableConf['fields'] as $value) $values[] = "`{$value}`";
  1931. $queries[] = "insert into `BI_audit_ALL` (" . implode(", ", $fields) . ") select " . implode(", ", $values) . " from `{$table}` {$where}";
  1932. $queries[] = "update `{$table}` set `cached` = 1 {$where}";
  1933. }
  1934. $queries[] = "update `BI_audit_ALL` set `nip` = null where `nip` = 0";
  1935. $queries[] = "update `BI_audit_ALL` set `regon` = null where `regon` = 0";
  1936. $queries[] = "update `BI_audit_ALL` set `krs` = null where `krs` = 0";
  1937. $queries[] = "update `BI_audit_ALL` set `pesel` = null where `pesel` = 0";
  1938. $queries[] = "set @var = (select round(coalesce(max(`ID`), '0.5'), 1) from `BI_audit_ALL_ref_RELATIONS`)";
  1939. $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";
  1940. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  1941. if ($onlyBase && (!$tableConf['base'])) continue;
  1942. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  1943. $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
  1944. $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`";
  1945. if (!in_array($refTableFrom, $sourceTables)) {
  1946. $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`";
  1947. }
  1948. if ($backRefTable = BiAuditRefTables::getRefTable($refTableTo, $refTableFrom, false)) {
  1949. $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'";
  1950. }
  1951. $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'";
  1952. }
  1953. }
  1954. foreach ($queries as $query) {
  1955. echo "SQL: {$query}\n";
  1956. DB::getPDO()->query($query);
  1957. }
  1958. $BiAuditRelations = new BiAuditRelations();
  1959. $result = DB::getPDO()->query("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
  1960. while ($row = $result->fetch()) $BiAuditRelations->findRelations($row['ID']);
  1961. DB::getPDO()->query("update `BI_audit_ALL` set `reffed` = 1");
  1962. }
  1963. public function doReloadCache($full = false) {
  1964. if ($full === 'base') {
  1965. $onlyBase = true;
  1966. $full = false;
  1967. } else {
  1968. $onlyBase = false;
  1969. }
  1970. if ($this->POWIAZANIA_ID && (!$full)) {
  1971. $checkTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_RUM_KONTRAHENCI'];
  1972. foreach ($checkTables as $table) {
  1973. $query = "select count(*) from `BI_audit_ALL` `all` left join `{$table}` `t` on `all`.`REMOTE_ID`=`t`.`ID` where `all`.`REMOTE_TABLE`='{$table}' and `t`.`ID` is null";
  1974. if (DB::getPDO()->fetchValue($query)) {
  1975. $full = true;
  1976. BiAuditPowiazania::saveToLog("Wykryto niespójność tabel - uruchamiam pełne odświeżenie cache");
  1977. $sqlArr = [
  1978. 'BI_analiza_reloadCache' => 'Full',
  1979. 'FILE_STATUS_info' => 'Odświeżam w pełni cache',
  1980. ];
  1981. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $this->POWIAZANIA_ID, $sqlArr);
  1982. break;
  1983. }
  1984. }
  1985. }
  1986. $powiazaniaDirLocation = self::getMainDirectory();
  1987. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1988. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1989. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1990. if ($full) file_put_contents($reloadCachePidFile, getmypid());
  1991. try {
  1992. //self::importPracownicy(); //TODO
  1993. error_log('now: self::reloadCache_parseUmowy');
  1994. self::reloadCache_parseUmowy($full);
  1995. error_log('now: self::reloadCache_reTeryt');
  1996. self::reloadCache_reTeryt($full);
  1997. error_log('now: self::reloadCache_updateAll');
  1998. self::reloadCache_updateAll($full, $onlyBase);
  1999. if (!$this->POWIAZANIA_ID) file_put_contents($reloadCacheResultFile, "ok");
  2000. } catch (Exception $e) {
  2001. var_dump($e);
  2002. if (!$this->POWIAZANIA_ID) file_put_contents($reloadCacheResultFile, $e->getMessage());
  2003. else throw new Exception($e->getMessage());
  2004. }
  2005. }
  2006. public function doGeneratePowiazania($ID) {
  2007. $this->POWIAZANIA_ID = $ID;
  2008. $powiazaniaDirLocation = self::getMainDirectory();
  2009. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  2010. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  2011. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  2012. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  2013. file_put_contents($pidFile, getmypid());
  2014. $tablesConf = [
  2015. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  2016. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  2017. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  2018. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  2019. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  2020. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  2021. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  2022. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  2023. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  2024. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  2025. ];
  2026. try {
  2027. $BiAuditPowiazania = new BiAuditPowiazania($ID, $tasksDirLocation);
  2028. $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}";
  2029. $sqlArr = [
  2030. 'BI_analiza_reloadCache' => 'Part',
  2031. 'FILE_STATUS_info' => 'Odświeżam częściowo cache',
  2032. ];
  2033. do {
  2034. DB::getPDO()->query("lock tables `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` write");
  2035. $activeReloadingCache = DB::getPDO()->fetchValue($query);
  2036. if (!$activeReloadingCache) DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  2037. DB::getPDO()->query("unlock tables");
  2038. if ($activeReloadingCache) {
  2039. BiAuditPowiazania::saveToLog("Czekam na zakończenie odświeżania cache przez inne zadanie");
  2040. sleep(30);
  2041. }
  2042. } while ($activeReloadingCache);
  2043. BiAuditPowiazania::saveToLog("Uruchamiam częściowe odświeżenie cache");
  2044. $this->doReloadCache(); //DUPA testowe wylaczanie
  2045. BiAuditPowiazania::saveToLog("Odświeżono cache");
  2046. $sqlArr = [
  2047. 'BI_analiza_reloadCache' => 'No',
  2048. 'FILE_STATUS_info' => 'Szukam powiązań',
  2049. ];
  2050. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  2051. $BiAuditPowiazania->run();
  2052. //if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  2053. //file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  2054. $sqlArr = ['FILE_STATUS_info' => 'Generuję raporty PDF i HTML'];
  2055. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  2056. //$BiAuditPowiazania->saveXml();
  2057. $BiAuditPowiazania->generatePdfAndHtml();
  2058. file_put_contents($resultFile, json_encode(['result' => 'ok', 'parts' => $BiAuditPowiazania->getPartsCount()]));
  2059. } catch (Exception $e) {
  2060. file_put_contents($resultFile, json_encode(['result' => 'error', 'message' => $e->getMessage()]));
  2061. }
  2062. }
  2063. public function reinstallAction() {
  2064. $this->reinstall();
  2065. die('OK');
  2066. }
  2067. public function reinstall() {
  2068. $sqlList = array();
  2069. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  2070. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  2071. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  2072. SQL;
  2073. $sqlList['ChangeStructure1'] = <<<SQL
  2074. 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';
  2075. SQL;
  2076. $sqlList['ChangeStructure2'] = <<<SQL
  2077. UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
  2078. SQL;
  2079. $sqlList['ChangeStructure3'] = <<<SQL
  2080. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
  2081. SQL;
  2082. $sqlList['ChangeStructure4'] = <<<SQL
  2083. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_depth` `BI_analiza_maxDepth` INT(2) NULL DEFAULT '9';
  2084. SQL;
  2085. $sqlList['ChangeStructure5'] = <<<SQL
  2086. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_minDepth` INT(2) NOT NULL DEFAULT '0' AFTER `FILE_STATUS_info`;
  2087. SQL;
  2088. $sqlList['ChangeStructure6'] = <<<SQL
  2089. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_onlyTargets` ENUM('Y','N') NOT NULL DEFAULT 'Y' AFTER `BI_analiza_maxDepth`;
  2090. SQL;
  2091. $db = DB::getDB();
  2092. if ($db->has_errors()) {
  2093. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  2094. }
  2095. foreach ($sqlList as $sqlName => $sql) {
  2096. $res = $db->query($sql);
  2097. if ($db->has_errors()) {
  2098. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  2099. }
  2100. }
  2101. }
  2102. }
  2103. class BiAuditRelations {
  2104. private $RELATIONS_ID = [];
  2105. private $relations = [
  2106. 'nip' => ['nip'],
  2107. 'regon' => ['regon'],
  2108. 'krs' => ['krs'],
  2109. 'pesel' => ['pesel'],
  2110. ];
  2111. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  2112. private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  2113. public function __construct() {
  2114. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  2115. $result = DB::getPDO()->fetchAll($query);
  2116. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  2117. }
  2118. private function getRelationID($name) {
  2119. if (!isset($this->RELATIONS_ID[$name])) {
  2120. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  2121. $newID = DB::getPDO()->fetchValue($query);
  2122. $this->RELATIONS_ID[$name] = $newID;
  2123. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  2124. DB::getPDO()->query($query);
  2125. }
  2126. return $this->RELATIONS_ID[$name];
  2127. }
  2128. private function addToRefTable($fromTable, $toTable, $fromID, $toID) {
  2129. if ($refTable = BiAuditRefTables::getRefTable($fromTable, $toTable, false)) {
  2130. if (!DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = '{$fromID}' and `REMOTE_PRIMARY_KEY` = '{$toID}' and `A_STATUS` != 'DELETED'")) {
  2131. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $fromID, 'REMOTE_PRIMARY_KEY' => $toID, 'A_STATUS' => 'NORMAL', 'TRANSACTION_ID' => '-1']);
  2132. }
  2133. }
  2134. }
  2135. public function findRelations($ID) {
  2136. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  2137. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  2138. $row = $result[0];
  2139. $joins = [];
  2140. $items = '';
  2141. foreach ($this->relations as $name => $columns) {
  2142. $ok = 0;
  2143. $join = [];
  2144. foreach ($columns as $column) {
  2145. $join[] = "t1.{$column} = t2.{$column}";
  2146. if ($row[$column] !== null) $ok++;
  2147. }
  2148. if ($ok / count($columns) > 0.5) {
  2149. $joins[] = "(" . implode(" and ", $join) . ")";
  2150. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  2151. }
  2152. }
  2153. if (!$joins) return false;
  2154. $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 " .
  2155. "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})";
  2156. $result = DB::getPDO()->fetchAll($query);
  2157. foreach ($result as $row) {
  2158. $relationID = 0;
  2159. foreach ($this->relations as $name => $v) {
  2160. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  2161. }
  2162. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  2163. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  2164. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  2165. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  2166. if (!($start2 || $end1)) {
  2167. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
  2168. $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
  2169. $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
  2170. DB::getPDO()->query($query);
  2171. }
  2172. if (!($start1 || $end2)) {
  2173. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
  2174. $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
  2175. $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
  2176. DB::getPDO()->query($query);
  2177. }
  2178. }
  2179. }
  2180. }
  2181. class BiAuditRefTables {
  2182. public static function getRefTable($tableFrom, $tableTo, $returnException = false) {
  2183. static $refTables = [];
  2184. static $tempRefTables = [];
  2185. if (is_array($tableTo)) {
  2186. if (!$tableTo) throw new Exception('BiAuditRefTables::getRefTable - bad parameter $tableTo');
  2187. if (count($tableTo) == 1) return self::getRefTable($tableFrom, reset($tableTo), $returnException);
  2188. $key = implode("__", $tableTo);
  2189. if (!isset($tempRefTables[$tableFrom][$key])) {
  2190. try {
  2191. $_tableFrom = $tableFrom;
  2192. foreach ($tableTo as $_tableTo) {
  2193. $_refTables[] = self::getRefTable($_tableFrom, $_tableTo, true);
  2194. $_tableFrom = $_tableTo;
  2195. }
  2196. $name = "TEMP__#REF_TABLE__" . (count($tempRefTables) + 1);
  2197. $first = reset($_refTables);
  2198. $last = end($_refTables);
  2199. $prev = array_shift($_refTables);
  2200. $query = "create temporary table `{$name}` select `{$first}`.`PRIMARY_KEY`, `{$last}`.`REMOTE_PRIMARY_KEY` from `{$first}`";
  2201. while ($next = array_shift($_refTables)) {
  2202. $query .= " join `{$next}` on `{$prev}`.`REMOTE_PRIMARY_KEY` = `{$next}`.`PRIMARY_KEY`";
  2203. $prev = $next;
  2204. }
  2205. $query .= " group by `{$first}`.`PRIMARY_KEY`, `{$last}`.`REMOTE_PRIMARY_KEY`";
  2206. DB::getPDO()->query($query);
  2207. $tempRefTables[$tableFrom][$key] = $name;
  2208. } catch (Exception $e) {
  2209. if ($returnException) throw new Exception($e->getMessage());
  2210. $tempRefTables[$tableFrom][$key] = false;
  2211. }
  2212. }
  2213. return $tempRefTables[$tableFrom][$key];
  2214. } else {
  2215. if (!isset($refTables[$tableFrom][$tableTo])) {
  2216. try {
  2217. $refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
  2218. } catch (Exception $e) {
  2219. if ($returnException) throw new Exception($e->getMessage());
  2220. $refTables[$tableFrom][$tableTo] = false;
  2221. }
  2222. }
  2223. return $refTables[$tableFrom][$tableTo];
  2224. }
  2225. }
  2226. public static function getRefTables($tableFrom) {
  2227. static $refTables = [];
  2228. if (!isset($refTables[$tableFrom])) {
  2229. $namespace = "default_db/{$tableFrom}/{$tableFrom}";
  2230. try {
  2231. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  2232. if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
  2233. $fields = $item['field'];
  2234. $_refTables = [];
  2235. foreach ($fields as $field) {
  2236. list($type, $child) = explode(":", $field['xsdType'], 2);
  2237. if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) {
  2238. try {
  2239. $_refTable = ACL::getRefTable($namespace, $child);
  2240. $_refTables[] = $_refTable;
  2241. } catch (Exception $e) {
  2242. }
  2243. }
  2244. }
  2245. $refTables[$tableFrom] = $_refTables;
  2246. } catch (Exception $e) {
  2247. $refTables[$tableFrom] = [];
  2248. }
  2249. }
  2250. return $refTables[$tableFrom];
  2251. }
  2252. }
  2253. class BiAuditPowiazania {
  2254. private $minDepth;
  2255. private $maxDepth, $origMaxDepth;
  2256. private $onlyTargets;
  2257. private $ID;
  2258. private $nodes = [];
  2259. private $endNodes;
  2260. private $path = [];
  2261. private $results = [];
  2262. private $items_results = [];
  2263. private $relations = [];
  2264. private $srcTables = ['BI_audit_ENERGA_PRACOWNICY']; //, ['BI_audit_POWIAZANIA_OD', 'BI_audit_POWIAZANIA_OBIEKTY']];
  2265. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person']; //, ['BI_audit_POWIAZANIA_DO', 'BI_audit_POWIAZANIA_OBIEKTY']];
  2266. private $step = 0;
  2267. private $tasksDirLocation;
  2268. private $progressFile;
  2269. private $progress = [
  2270. 'summary' => [
  2271. 'count' => 0,
  2272. 'message' => 'Inicjacja',
  2273. 'ts' => null,
  2274. 'step' => 'initialize',
  2275. 'reportsCount' => 0,
  2276. 'reportsCreated' => 0,
  2277. ],
  2278. 'details' => [],
  2279. ];
  2280. private $lastProgress = 0;
  2281. private $lastProgress_slowCheck = 0;
  2282. private $lastResults = 0;
  2283. private $startTimestamp = null;
  2284. private $lastTimestamp = null;
  2285. private $lowProgressCount = 0;
  2286. private $count, $i;
  2287. private $splittedResults = [];
  2288. private $maxResults = 1000000;
  2289. private $fidRow = [];
  2290. private $itemID = 0;
  2291. private $reverseSearch = false;
  2292. private $query = "";
  2293. private static function generateJson($type, $data) {
  2294. return json_encode(['ts' => microtime(true), 'type' => $type, 'data' => $data]);
  2295. }
  2296. public static function saveToLog($message) {
  2297. $messageJson = self::generateJson('message', ['message' => $message]);
  2298. echo $messageJson . "\n";
  2299. }
  2300. private static function exec($cmd) {
  2301. $path = 'export PATH=$PATH:/usr/sbin;';
  2302. $cmd = "{$path} {$cmd}";
  2303. echo "CMD :: {$cmd}\n";
  2304. shell_exec($cmd);
  2305. }
  2306. private function saveProgress($args = []) {
  2307. $timestamp = microtime(true);
  2308. if (isset($args['progress']) && $this->i) {
  2309. $elapsed = $timestamp - $this->startTimestamp;
  2310. if ($args['progress']) {
  2311. $estimated = ($elapsed * (1 - $args['progress'])) / $args['progress'];
  2312. } else $estimated = "N/A";
  2313. $this->lastProgress = $args['progress'];
  2314. $this->lastTimestamp = $timestamp;
  2315. $progressJson = self::generateJson('progress', ['progress' => $args['progress'], 'item' => $this->i . "/" . $this->count, 'results' => count($this->results), 'step' => $this->step, 'elapsed' => $elapsed, 'estimated' => $estimated]);
  2316. echo $progressJson . "\n";
  2317. $this->progress['details'][$this->itemID] = ['progress' => $args['progress'], 'results' => (count($this->results) - $this->lastResults), 'elapsed' => $elapsed, 'estimated' => $estimated];
  2318. }
  2319. if (isset($args['message'])) $this->progress['summary']['message'] = $args['message'];
  2320. if (isset($args['step'])) $this->progress['summary']['step'] = $args['step'];
  2321. if (isset($args['reportsCreated'])) $this->progress['summary']['reportsCreated'] = round($this->progress['summary']['reportsCreated'] + $args['reportsCreated'], 2);
  2322. $this->progress['summary']['ts'] = $timestamp;
  2323. file_put_contents($this->progressFile, json_encode($this->progress));
  2324. }
  2325. private static function throwException($message) {
  2326. self::saveToLog($message);
  2327. throw new Exception($message);
  2328. }
  2329. public function __construct($ID = 0, $tasksDirLocation = null) {
  2330. if (!$ID) self::throwException("Wrong ID parameter");
  2331. if (!$tasksDirLocation) self::throwException("Wrong directory of tasks location");
  2332. $this->ID = $ID;
  2333. $this->tasksDirLocation = $tasksDirLocation;
  2334. $this->progressFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.progress";
  2335. $this->saveProgress();
  2336. }
  2337. public function run() {
  2338. $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')";
  2339. $result = DB::getPDO()->fetchAll($query);
  2340. if (!$result) self::throwException("Błąd danych");
  2341. if ($this->loadResults()) {
  2342. $this->splitResults();
  2343. return;
  2344. }
  2345. self::saveToLog("Wczytuję parametry wyszukiwania powiązań");
  2346. $this->minDepth = (int) $result[0]['BI_analiza_minDepth'];
  2347. $this->maxDepth = (int) $result[0]['BI_analiza_maxDepth'];
  2348. $this->onlyTargets = ($result[0]['BI_analiza_onlyTargets'] != 'N');
  2349. if (!$this->minDepth) $this->minDepth = 1;
  2350. if (!$this->maxDepth) self::throwException("Błąd danych - nieokreślono maksymalnej głębokości analizy");
  2351. if ($this->minDepth > $this->maxDepth) self::throwException("Wartość minimalnej głębokości analizy jest większa od wartości maksymalnej głębokości analizy");
  2352. $subQueries = [];
  2353. $resultDest = [];
  2354. foreach ($this->destTables as $destTable) {
  2355. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $destTable)) {
  2356. $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}'";
  2357. }
  2358. }
  2359. if ($subQueries) {
  2360. $query = implode(" union ", $subQueries) . " order by `ID` asc";
  2361. $resultDest = DB::getPDO()->fetchAll($query);
  2362. }
  2363. if ((!$resultDest) && $this->onlyTargets) self::throwException("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  2364. $subQueries = [];
  2365. $resultSrc = [];
  2366. foreach ($this->srcTables as $srcTable) {
  2367. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $srcTable)) {
  2368. $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}'";
  2369. }
  2370. }
  2371. if ($subQueries) {
  2372. $query = implode(" union ", $subQueries) . " order by `ID` asc";
  2373. $resultSrc = DB::getPDO()->fetchAll($query);
  2374. }
  2375. if (!$resultSrc) self::throwException("Błąd danych - nie zdefinowano żadnego początkowego obiektu");
  2376. if (count($resultSrc) <= count($resultDest) || (!$this->onlyTargets)) {
  2377. $result = $resultSrc;
  2378. $this->endNodes = array_map('reset', $resultDest);
  2379. $this->reverseSearch = false;
  2380. $this->query = "select ref.ID2 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID1";
  2381. } else {
  2382. $result = $resultDest;
  2383. $this->endNodes = array_map('reset', $resultSrc);
  2384. $this->reverseSearch = true;
  2385. $this->query = "select ref.ID1 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID2";
  2386. self::saveToLog("Docelowych obiektów jest mniej, niż początkowych - włączono mechanizm odwrotnego przeszukiwania");
  2387. }
  2388. self::saveToLog("Rozpoczynam wyszukiwanie powiązań");
  2389. $this->count = count($result);
  2390. $this->progress['summary']['count'] = $this->count;
  2391. $this->origMaxDepth = $this->maxDepth;
  2392. $this->saveProgress(['step' => 'relations']);
  2393. try {
  2394. foreach ($result as $i => $row) {
  2395. $this->i = $i + 1;
  2396. $this->itemID = DB::getPDO()->fetchValue("select `REMOTE_ID` from `BI_audit_ALL` where `ID` = :ID", [":ID" => $row['ID']]);
  2397. $this->startTimestamp = microtime(true);
  2398. $this->lastProgress = 0;
  2399. $this->lastProgress_slowCheck = 0;
  2400. $this->saveProgress(['progress' => 0, 'message' => "Wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
  2401. if ($this->maxDepth != $this->origMaxDepth) {
  2402. $this->maxDepth = $this->origMaxDepth;
  2403. self::saveToLog("Przywrócono oryginalną maksymalną głębokość przeszukiwania ({$this->origMaxDepth})");
  2404. }
  2405. $this->findPowiazania($row['ID']);
  2406. $this->saveProgress(['progress' => 1, 'message' => "Zakończono wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
  2407. $this->lastResults = count($this->results);
  2408. }
  2409. } catch (Exception $e) {
  2410. if ($this->i < $this->count) {
  2411. $this->startTimestamp = microtime(true);
  2412. $this->lastProgress = 0;
  2413. $this->lastResults = count($this->results);
  2414. while (++$this->i <= $this->count) $this->saveProgress(['progress' => 0]);
  2415. }
  2416. if ($message = $e->getMessage()) self::saveToLog("Wystąpił błąd podczas wyszukiwania powiązań - {$message}");
  2417. }
  2418. $this->nodes = [];
  2419. self::saveToLog("Zakończono wyszukiwanie powiązań");
  2420. $this->sortResults();
  2421. $this->saveResults();
  2422. //$this->saveToDb(); 2017-12-14 - przerobiono na zapisywanie danych do bazy w locie
  2423. $this->splitResults();
  2424. }
  2425. private static function reversePath($path) {
  2426. $arr = array_reverse($path, true);
  2427. $keys = array_keys($arr);
  2428. array_unshift($arr, array_pop($arr));
  2429. return array_combine($keys, $arr);
  2430. }
  2431. private function addResult($progress) {
  2432. if (count($this->results) == $this->maxResults) {
  2433. $message = "Przerwano wyszukiwanie powiązań - osiągnięto maksymalną liczbę wyników {$this->maxResults}";
  2434. self::saveToLog($message);
  2435. $this->saveProgress(['progress' => $progress, 'message' => $message]);
  2436. throw new Exception('');
  2437. }
  2438. if ($this->reverseSearch) $path = self::reversePath($this->path);
  2439. else $path = $this->path;
  2440. $this->results[] = $path;
  2441. $this->saveToDb($path);
  2442. }
  2443. private static function weightCalc($n) {
  2444. if ($n < 21) return 1;
  2445. if ($n < 41) return 2;
  2446. if ($n < 81) return 3;
  2447. if ($n < 161) return 4;
  2448. if ($n < 321) return 5;
  2449. if ($n < 641) return 6;
  2450. if ($n < 1281) return 7;
  2451. if ($n < 2561) return 8;
  2452. if ($n < 5121) return 9;
  2453. return 10;
  2454. }
  2455. public function findPowiazania($ID, $progress = 0, $steps = 1, $relation = "", $weight = 0) {
  2456. $this->step++;
  2457. if ($this->maxDepth > $this->minDepth) {
  2458. if (($this->step % 1000000) == 0) {
  2459. $progressDiff = $progress - $this->lastProgress_slowCheck;
  2460. if ($progressDiff < 0.00005) {
  2461. $this->lowProgressCount++;
  2462. if ($this->lowProgressCount == 10) {
  2463. $this->maxDepth--;
  2464. self::saveToLog("Zbyt dużo rekurencji, zmniejszono maksymalną głębokość poszukiwań do {$this->maxDepth} dla bieżącego obiektu");
  2465. $this->lowProgressCount = 0;
  2466. }
  2467. } else $this->lowProgressCount = 0;
  2468. $this->lastProgress_slowCheck = $progress;
  2469. }
  2470. }
  2471. if ((($this->step) % 100000) == 0) {
  2472. $this->saveProgress(['progress' => $progress]);
  2473. }
  2474. if ((($this->step) % 10000) == 0) {
  2475. if (memory_get_usage(true) > 3000000000) {
  2476. $this->nodes = [];
  2477. self::saveToLog("Oczyszczam podręczny cache - zajmuje zbyt dużo pamięci");
  2478. }
  2479. }
  2480. if (isset($this->path[$ID])) return false;
  2481. $this->path[$ID] = $relation;
  2482. if (!$relation) $relation = 0;
  2483. if (in_array($ID, $this->endNodes)) {
  2484. if (count($this->path) > $this->minDepth) $this->addResult($progress);
  2485. array_pop($this->path);
  2486. return;
  2487. }
  2488. if (count($this->path) > $this->maxDepth) {
  2489. if (!$this->onlyTargets) $this->addResult($progress);
  2490. array_pop($this->path);
  2491. return;
  2492. }
  2493. if (!isset($this->nodes[$ID][$relation])) {
  2494. $where = $relation ? "and ({$relation} & ref.RELATION_ID) = 0" : "";
  2495. $query = "{$this->query} = {$ID} {$where}";
  2496. $this->nodes[$ID][$relation] = DB::getPDO()->fetchAll($query);
  2497. }
  2498. $nodes = array_values(array_filter($this->nodes[$ID][$relation], function ($node) {
  2499. if (isset($this->path[$node['ID']])) return false;
  2500. return true;
  2501. }));
  2502. $count = count($nodes);
  2503. $weight += self::weightCalc($count);
  2504. if ($weight <= $this->maxDepth) {
  2505. foreach ($nodes as $i => $node) $this->findPowiazania($node['ID'], ($progress + ($i / ($count * $steps))), ($count * $steps), $node['RELATION_ID'], $weight);
  2506. }
  2507. array_pop($this->path);
  2508. }
  2509. private function sortResults() {
  2510. if (!$this->results) return;
  2511. uasort($this->results, function ($a, $b) {
  2512. $ca = count($a);
  2513. $cb = count($b);
  2514. $c = min($ca, $cb);
  2515. $ka = array_keys($a);
  2516. $kb = array_keys($b);
  2517. for ($i = 0; $i < $c; $i++) {
  2518. if ($ka[$i] < $kb[$i]) return -1;
  2519. if ($ka[$i] > $kb[$i]) return 1;
  2520. }
  2521. if ($ca < $cb) return -1;
  2522. if ($ca > $cb) return 1;
  2523. return 0;
  2524. });
  2525. }
  2526. private function saveResults() {
  2527. self::saveToLog("Zapisuję wyliczone dane do pliku");
  2528. // if (!$this->results) {
  2529. // self::saveToLog("Brak wyliczonych danych - niczego nie zapisaono");
  2530. // return false;
  2531. // }
  2532. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  2533. $data = base64_encode(gzcompress(json_encode(['results' => $this->results, 'fidRow' => $this->fidRow])));
  2534. file_put_contents($dataFile, $data);
  2535. self::saveToLog("Zapisano wyliczone dane do pliku");
  2536. return true;
  2537. }
  2538. private function loadResults() {
  2539. self::saveToLog("Próbuję wczytać wcześniej wyliczone dane");
  2540. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  2541. if (!file_exists($dataFile)) {
  2542. self::saveToLog("Nie znaleziono pliku z wyliczonymi danymi");
  2543. return false;
  2544. }
  2545. $data = file_get_contents($dataFile);
  2546. $results = @json_decode(gzuncompress(base64_decode($data)), true);
  2547. if (!$results) {
  2548. self::saveToLog("Wystąpił błąd wczytywania wcześniej wyliczonych danych");
  2549. return false;
  2550. }
  2551. if (isset($results['results'])) {
  2552. $this->results = $results['results'];
  2553. if (isset($results['fidRow'])) $this->fidRow = $results['fidRow'];
  2554. } else $this->results = $results;
  2555. self::saveToLog("Wczytano wcześniej wyliczone dane");
  2556. return true;
  2557. }
  2558. private function relationName($ID) {
  2559. if (!$ID) return '';
  2560. if (!isset($this->relations[$ID])) {
  2561. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  2562. $result = DB::getPDO()->fetchAll($query);
  2563. $rels = array_map('reset', $result);
  2564. $this->relations[$ID] = implode(", ", $rels);
  2565. }
  2566. return $this->relations[$ID];
  2567. }
  2568. private function splitResults() {
  2569. $MAX = 1000;
  2570. $countBySource = [];
  2571. $resultsKeys = [];
  2572. foreach ($this->results as $resultKey => $result) {
  2573. $_keys = array_keys($result);
  2574. $countBySource[reset($_keys)][] = $resultKey;
  2575. }
  2576. foreach ($countBySource as $resultKeys) {
  2577. if (count($resultKeys) > $MAX) {
  2578. $countByDest = [];
  2579. foreach ($resultKeys as $resultKey) {
  2580. $_keys = array_keys($this->results[$resultKey]);
  2581. $countByDest[end($_keys)][] = $resultKey;
  2582. }
  2583. foreach ($countByDest as $resultKeys2) $resultsKeys = array_merge($resultsKeys, array_chunk($resultKeys2, $MAX));
  2584. } else $resultsKeys[] = $resultKeys;
  2585. }
  2586. $results = [];
  2587. while ($resultsKeys) {
  2588. $resultKeys = array_shift($resultsKeys);
  2589. while ($next = current($resultsKeys)) {
  2590. if (count($resultKeys) + count($next) <= $MAX) {
  2591. $resultKeys = array_merge($resultKeys, $next);
  2592. unset($resultsKeys[key($resultsKeys)]);
  2593. } else break; //next($resultsKeys);
  2594. }
  2595. $_results = [];
  2596. foreach ($resultKeys as $key) $_results[$key] = $this->results[$key];
  2597. $results[] = $_results;
  2598. // $results[] = array_map(function ($resultKey) {return $this->results[$resultKey];}, $resultKeys);
  2599. }
  2600. if ($results) $this->splittedResults = $results;
  2601. else $this->splittedResults[] = $this->results;
  2602. $this->progress['summary']['reportsCount'] = count($results);
  2603. }
  2604. public function getPartsCount() {
  2605. return count($this->splittedResults);
  2606. }
  2607. private function generateItemsResults($resultsPart = null) {
  2608. if ($resultsPart === null) self::saveToLog("Generuję dane na potrzeby utworzenia pojedynczego pliku XML");
  2609. else {
  2610. self::saveToLog("Generuję dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  2611. if ($resultsPart >= $this->getPartsCount()) throw new Exception("generateItemsResults() error - bad part number");
  2612. }
  2613. $xmlTask = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  2614. $xmlRow = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  2615. $xmlObject = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object";
  2616. $items_kontrahenci = [];
  2617. $items_kw_person = [];
  2618. $kontrahenci = [];
  2619. $kw_person = [];
  2620. $_items_results = [];
  2621. $refUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  2622. $refKwRequestedToKwRequestedPerson = BiAuditRefTables::getRefTable('BI_audit_KW_requested', 'BI_audit_KW_requested_person', true);
  2623. $this->items_results[$resultsPart] = [];
  2624. $this->items_results[$resultsPart]['@attributes'] = ['xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd'];
  2625. $this->items_results[$resultsPart][$xmlTask]['@attributes'] = ['fid' => "{$xmlTask}.{$this->ID}"];
  2626. if ($resultsPart === null) {
  2627. $results = $this->results;
  2628. } else {
  2629. $results = (!empty($this->splittedResults[$resultsPart])) ? $this->splittedResults[$resultsPart] : [];
  2630. $this->items_results[$resultsPart][$xmlTask]['@attributes']['system_cache__dita:part'] = ($resultsPart + 1);
  2631. }
  2632. foreach ($results as $key => $result) {
  2633. if ($this->fidRow) $item_results = ['@attributes' => ['fid' => "{$xmlRow}.{$this->fidRow[$key]['fid']}"]];
  2634. foreach ($result as $ID => $rel) {
  2635. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  2636. $row = DB::getPDO()->fetchFirst($query);
  2637. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  2638. $obj = DB::fetch(DB::query($query));
  2639. $item_result = [];
  2640. if ($this->fidRow) {
  2641. $item_result['@attributes'] = ['fid' => "{$xmlObject}.{$this->fidRow[$key]['obj'][$ID]}"];
  2642. }
  2643. $item_result[$row['REMOTE_TABLE']] = array_merge(['@attributes' => ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"]], (array) $obj);
  2644. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_operational_raport_note', $row['REMOTE_TABLE'], false)) {
  2645. $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']}'";
  2646. if ($notes = DB::getPDO()->fetchAll($query)) $item_result[$row['REMOTE_TABLE']]['BI_audit_operational_raport_note'] = $notes;
  2647. }
  2648. if ($refTable = BiAuditRefTables::getRefTable($row['REMOTE_TABLE'], 'BI_audit_taxpayer', false)) {
  2649. $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']}'";
  2650. if ($taxpayer = DB::getPDO()->fetchFirst($query)) {
  2651. $item_result[$row['REMOTE_TABLE']]['BI_audit_taxpayer'] = array_merge(['@attributes' => ['fid' => "BI_audit_taxpayer.{$taxpayer['ID']}"]], $taxpayer);
  2652. }
  2653. }
  2654. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  2655. $item_results[$xmlObject][] = $item_result;
  2656. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  2657. $kontrahenci[] = $row['REMOTE_ID'];
  2658. $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']}'";
  2659. $res = DB::query($query);
  2660. if (mysql_num_rows($res)) {
  2661. $umowy = [];
  2662. while ($obj = DB::fetch($res)) {
  2663. $umowa = (array) $obj;
  2664. $umowa = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_RUM_UMOWY.{$umowa['ID']}"]], $umowa);
  2665. $umowy[] = $umowa;
  2666. }
  2667. $item_kontrahenci['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
  2668. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  2669. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  2670. $items_kontrahenci[] = $item_kontrahenci;
  2671. }
  2672. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  2673. $kw_person[] = $row['REMOTE_ID'];
  2674. $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']}'";
  2675. $res = DB::query($query);
  2676. if (mysql_num_rows($res)) {
  2677. $kws = [];
  2678. while ($obj = DB::fetch($res)) {
  2679. $kw = (array) $obj;
  2680. $kw = array_merge(['@attributes' => ['fid' => "BI_audit_KW_requested.{$kw['ID']}"]], $kw);
  2681. $kws[] = $kw;
  2682. }
  2683. $item_kw_person['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
  2684. $item_kw_person['ID'] = $row['REMOTE_ID'];
  2685. $item_kw_person['BI_audit_KW_requested'] = $kws;
  2686. $items_kw_person[] = $item_kw_person;
  2687. }
  2688. }
  2689. }
  2690. $this->items_results[$resultsPart][$xmlTask][$xmlRow][] = $item_results;
  2691. }
  2692. $this->items_results[$resultsPart][$xmlTask]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  2693. $this->items_results[$resultsPart][$xmlTask]['BI_audit_KW_requested_person'] = $items_kw_person;
  2694. self::saveToLog("Wygenerowano dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  2695. }
  2696. private function saveToDb($result = null, $key = null) {
  2697. if ($result === null) {
  2698. self::saveToLog("Zapisuję wyliczone dane do bazy");
  2699. if (!$this->results) {
  2700. self::saveToLog("Brak wyliczonych danych - nie zapisaono niczego do bazy");
  2701. return null;
  2702. }
  2703. foreach ($this->results as $key => $result) $this->saveToDb($result, $key);
  2704. self::saveToLog("Zapisano wyliczone dane do bazy");
  2705. } else {
  2706. if ($key === null) {
  2707. end($this->results);
  2708. $key = key($this->results);
  2709. }
  2710. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  2711. $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
  2712. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  2713. $fidObj = [];
  2714. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  2715. foreach ($result as $ID => $rel) {
  2716. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  2717. $object = DB::getPDO()->fetchFirst($query);
  2718. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relationName($rel)]);
  2719. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  2720. $ref = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', $object['REMOTE_TABLE'], true);
  2721. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  2722. $fidObj[$ID] = $idPowiazaniaRowObject;
  2723. }
  2724. $this->fidRow[$key] = [
  2725. 'fid' => $IdPowiazaniaRow,
  2726. 'obj' => $fidObj,
  2727. ];
  2728. }
  2729. }
  2730. public function saveXml($resultsPart = null) {
  2731. if ($this->getPartsCount()) {
  2732. if ($resultsPart === null) {
  2733. self::saveToLog("Generuję pliki XML (liczba plików do wygenerowania: {$this->getPartsCount()})");
  2734. for ($i =0; $i < $this->getPartsCount(); $i++) {
  2735. $partNo = str_pad($i + 1, 6, '0', STR_PAD_LEFT);
  2736. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  2737. file_put_contents($xmlFile, $this->asXml($i));
  2738. }
  2739. self::saveToLog("Zakończono generowanie plików XML");
  2740. } else {
  2741. if ($resultsPart >= $this->getPartsCount()) {
  2742. self::saveToLog("saveXml() error - bad result number");
  2743. return;
  2744. }
  2745. $partNo = str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  2746. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  2747. file_put_contents($xmlFile, $this->asXml($resultsPart));
  2748. }
  2749. } else {
  2750. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
  2751. file_put_contents($xmlFile, $this->asXml());
  2752. }
  2753. }
  2754. public function asXml($resultsPart = null) {
  2755. self::saveToLog("Generuję plik XML ({$resultsPart})");
  2756. if (!$this->results) {
  2757. self::saveToLog("Brak wyników (#1), wygenerowano pusty plik XML ({$resultsPart})");
  2758. // self::saveToLog("Brak wyników (#1), nie wygenerowano pliku XML ({$resultsPart})");
  2759. // return null;
  2760. }
  2761. if (!isset($this->items_results[$resultsPart])) $this->generateItemsResults($resultsPart);
  2762. if (!isset($this->items_results[$resultsPart])) {
  2763. self::saveToLog("Brak wyników (#2), nie wygenerowano pliku XML ({$resultsPart})");
  2764. return null;
  2765. }
  2766. $xmlRoot = "RelatedFeatureRoot";
  2767. $return = V::arrayToXML($this->items_results[$resultsPart], true, $xmlRoot);
  2768. self::saveToLog("Wygenerowano plik XML ({$resultsPart})");
  2769. return $return;
  2770. }
  2771. public function asArray($resultsPart = null, $subArray = null) {
  2772. if (!$this->results) return null;
  2773. if (!$this->items_results[$resultsPart]) $this->generateItemsResults($resultsPart);
  2774. if (!$this->items_results[$resultsPart]) return null;
  2775. if ($subArray) {
  2776. if (isset($this->items_results[$resultsPart][$subArray])) return $this->items_results[$subArray];
  2777. else return [];
  2778. } else return $this->items_results[$resultsPart];
  2779. }
  2780. public function powiazaniaFound() {
  2781. if ($this->results) return true;
  2782. else return false;
  2783. }
  2784. public function generatePdfAndHtml() {
  2785. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  2786. if (!file_exists($antDir)) mkdir($antDir, 0770, true);
  2787. if (!is_dir($antDir)) {
  2788. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików PDF i HTML";
  2789. self::saveToLog("Nie wygenerowano plików PDF oraz HTML - problem z utworzeniem katalogu dla ant ({$resultsPart})");
  2790. $this->saveProgress(['reportsCreated' => 1]);
  2791. return;
  2792. }
  2793. $this->saveProgress(['step' => 'reports']);
  2794. if ($this->getPartsCount()) {
  2795. self::saveToLog("Generuję raporty w plikach PDF oraz HTML (liczba raportów do wygenerowania: {$this->getPartsCount()})");
  2796. for ($i =0; $i < $this->getPartsCount(); $i++) $this->_generatePdfAndHtml($i);
  2797. self::saveToLog("Zakończono generowanie raportów w plikach PDF oraz HTML");
  2798. } else $this->_generatePdfAndHtml();
  2799. }
  2800. private function _generatePdfAndHtml($resultsPart = null) {
  2801. $id_part = $resultsPart === null ? $this->ID : $this->ID . "_" . str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  2802. self::saveToLog("Generuję raport w pliku PDF oraz HTML ({$resultsPart})");
  2803. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.xml";
  2804. $pdfDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.pdf";
  2805. $htmlDestDir = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.html";
  2806. $htmlZipDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.zip";
  2807. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  2808. $antXmlFilename = "relations-{$id_part}.out_task.dita.final_with_RelatedFeatureLoop.xml";
  2809. $antXmlFile = $antDir . "/" . $antXmlFilename;
  2810. $ditamapFile = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}/relations-{$id_part}.ditamap";
  2811. $pdfFile = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}/pdf/relations-{$id_part}.pdf";
  2812. $htmlDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}/html";
  2813. $htmlFile = "{$htmlDir}/relations-{$id_part}.html";
  2814. //if (!file_exists($xmlFile))
  2815. $this->saveXml($resultsPart);
  2816. if (!file_exists($xmlFile)) {
  2817. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików XML, PDF i HTML";
  2818. self::saveToLog("Nie wygenerowano plików XML, PDF oraz HTML - problem z wygenerowaniem pliku XML ({$resultsPart})");
  2819. $this->saveProgress(['reportsCreated' => 1]);
  2820. return;
  2821. }
  2822. $this->saveProgress(['reportsCreated' => 0.05]);
  2823. copy($xmlFile, $antXmlFile);
  2824. self::saveToLog("Generuję plik przejściowy do wygenerowania plików PDF i HTML ({$resultsPart})");
  2825. 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}");
  2826. if (file_exists($ditamapFile))
  2827. {
  2828. self::saveToLog("Wygenerowano plik przejściowy");
  2829. $this->saveProgress(['reportsCreated' => 0.15]);
  2830. } else {
  2831. self::saveToLog("Nie udało się wygenerować pliku przejściowego, przerywm");
  2832. $this->saveProgress(['reportsCreated' => 1]);
  2833. return;
  2834. }
  2835. self::saveToLog("Generuję plik PDF ({$resultsPart})");
  2836. self::exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o pdf -i relations-{$id_part}.ditamap -f pdf");
  2837. if (file_exists($pdfFile)) {
  2838. rename($pdfFile, $pdfDestFile);
  2839. self::saveToLog("Wygenerowano plik PDF ({$resultsPart})");
  2840. } else self::saveToLog("Nie udało się wygenerować pliku PDF ({$resultsPart})");
  2841. $this->saveProgress(['reportsCreated' => 0.45]);
  2842. self::saveToLog("Generuję pliki HTML ({$resultsPart})");
  2843. self::exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o html -i relations-{$id_part}.ditamap -f tocjs");
  2844. if (file_exists($htmlDir) && is_dir($htmlDir) && file_exists($htmlFile)) {
  2845. self::exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}\" && zip -r \"{$htmlZipDestFile}\" html");
  2846. if (file_exists($htmlDestDir)) self::exec("rm -rf \"{$htmlDestDir}\"");
  2847. self::exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
  2848. self::saveToLog("Wygenerowano pliki HTML ({$resultsPart})");
  2849. } else self::saveToLog("Nie udało się wygenerować plików HTML {$resultsPart})");
  2850. $this->saveProgress(['reportsCreated' => 0.35]);
  2851. }
  2852. }