BiAuditGenerate.php 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844
  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. public function handleAuth() {
  22. if (!User::logged()) {
  23. User::authByRequest();
  24. }
  25. }
  26. private static function getDirectory($table, $id) {
  27. $folderConf = FoldersConfig::getAll($table.'_COLUMN');
  28. $record = new stdClass;
  29. $record->ID = $id;
  30. $uploader = new FileUploader($table.'_COLUMN', $record);
  31. $errMsg = "";
  32. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
  33. $uploader->findFolder();
  34. return $uploader->getDestLocalPath(true);
  35. }
  36. private static function getUrl($table, $id) {
  37. $folderConf = FoldersConfig::getAll($table.'_COLUMN');
  38. $record = new stdClass;
  39. $record->ID = $id;
  40. $uploader = new FileUploader($table.'_COLUMN', $record);
  41. $errMsg = "";
  42. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
  43. return $uploader->getFolderWeb() . "/" . $uploader->getDestFolder(true);
  44. }
  45. private static function getMainDirectory() {
  46. $folderConf = FoldersConfig::getAll('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_COLUMN');
  47. if (!isset($folderConf['mount_point'])) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
  48. return $folderConf['mount_point'];
  49. }
  50. private static function parseNipRegon($string) {
  51. $nip = null; $regon = null;
  52. preg_match('/^(.*[^[:digit:]])?([[:digit:]]{10})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
  53. if (!empty($matches[2])) $nip = trim($matches[2]);
  54. if ($nip && !V::isNip($nip)) $nip = null;
  55. preg_match('/^(.*[^[:digit:]])?([[:digit:]]{9})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
  56. if (!empty($matches[2])) $regon = trim($matches[2]);
  57. if ($regon && !V::isRegon($regon)) $regon = null;
  58. return [$nip, $regon];
  59. }
  60. private function initializePowiazaniaForm() {
  61. ?>
  62. <div class="container" style="margin-top:20px">
  63. <form class="form-horizontal" method="post">
  64. <legend>
  65. Generowanie powiązań :: <?=$this->powiazanie['L_APPOITMENT_INFO']?>
  66. <span class="pull-right"># <?=$this->powiazanie['ID']?></span>
  67. </legend>
  68. <div class="form-group">
  69. <div class="col-sm-12">
  70. <h4>Wybierz pracowników, dla których mają zostać wyszukane powiązania</h4>
  71. <table class="table table-bordered table-hover table-striped" height=5>
  72. <thead>
  73. <tr style="text-align:center; background-color:lightgray">
  74. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  75. <td width=1>ID</td>
  76. <td>Imiona</td>
  77. <td>Nazwisko</td>
  78. <td>Pesel</td>
  79. <td>NIP</td>
  80. <td>Regon</td>
  81. <td>source</td>
  82. </tr>
  83. </thead>
  84. <tbody>
  85. <?php
  86. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
  87. $queryFeatures = $acl->buildQuery(['limit' => 0]);
  88. $pracownicy = $queryFeatures->getItems();
  89. foreach ($pracownicy as $pracownik) {
  90. ?>
  91. <tr>
  92. <td><input type="checkbox" name="prID[]" value="<?=$pracownik['ID']?>" onClick="toggle(this)"/></td>
  93. <td align="right"><?=$pracownik['ID']?></td>
  94. <td><?=$pracownik['imiona']?></td>
  95. <td><?=$pracownik['nazwisko']?></td>
  96. <td><?=$pracownik['pesel']?></td>
  97. <td><?=$pracownik['nip']?></td>
  98. <td><?=$pracownik['regon']?></td>
  99. <td><?=$pracownik['source']?></td>
  100. </tr>
  101. <?php
  102. }
  103. ?>
  104. </tbody>
  105. </table>
  106. </div>
  107. </div>
  108. <div class="form-group">
  109. <label class="col-sm-2 control-label">
  110. Odśwież cache
  111. </label>
  112. <div class="col-sm-2">
  113. <select name="reloadCache" class="form-control">
  114. <option value="No" selected>Nie</option>
  115. <!-- <option value="Part">Częściowe</option>-->
  116. <option value="Full">Pełne</option>
  117. </select>
  118. </div>
  119. </div>
  120. <div class="form-group">
  121. <div class="col-sm-offset-2 col-sm-10">
  122. <!-- Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>-->
  123. Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów.<br/>
  124. Uwaga! Jeżeli aktywne są inne zadania, te zadanie zostanie wstrzymane do momentu ich ukończenia.
  125. </div>
  126. </div>
  127. <div class="form-group">
  128. <div class="col-sm-12">
  129. <div class="containter" style="text-align:center">
  130. <button type="submit" class="btn btn-primary" name="action" value="initialize">Generuj</button>
  131. <a href="<?=$this->REFERER?>" class="btn btn-default">Anuluj</a>
  132. </div>
  133. </div>
  134. </div>
  135. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  136. </form>
  137. </div>
  138. <script language="JavaScript">
  139. <!--
  140. function toggleAll(source) {
  141. checkboxes = document.getElementsByName('prID[]');
  142. for(var i=0, n=checkboxes.length;i<n;i++) checkboxes[i].checked = source.checked;
  143. }
  144. function toggle(source) {
  145. checkboxes = document.getElementsByName('prID[]');
  146. all = true;
  147. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked == false) all = false;
  148. source.form['checkAll'].checked = all;
  149. }
  150. -->
  151. </script>
  152. <?php
  153. }
  154. private function initializePowiazaniaSave() {
  155. $prID = V::get('prID', array(), $_POST);
  156. if (!$prID) throw new Exception("Nie wybrano żadnego pracownika!");
  157. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
  158. $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
  159. $kontrahenci = $queryFeatures->getItems();
  160. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_KW_requested_person/BI_audit_KW_requested_person');
  161. $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
  162. $requestedPersons = $queryFeatures->getItems();
  163. if (!($kontrahenci || $requestedPersons)) throw new Exception("Nie znaleziono żadnego obiektu końcowego");
  164. $sqlUpdate = ['FILE_STATUS' => 'TO_GENERATE'];
  165. $reloadCache = V::get('reloadCache', 'No', $_POST);
  166. $reloadCacheAvailable = ['Full', 'Part', 'No'];
  167. if (!in_array($reloadCache, $reloadCacheAvailable)) throw new Exception("Błąd formularza!");
  168. $sqlUpdate['BI_analiza_reloadCache'] = $reloadCache;
  169. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part')";
  170. $result = DB::getPDO()->fetchValue($query);
  171. if ($result) $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache (wymagane dla innego rekordu)';
  172. elseif ($reloadCache != 'No') $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache';
  173. else $sqlUpdate['FILE_STATUS_info'] = "Oczekuje na wygenerowanie powiązań";
  174. if ($this->powiazanie) { // wyzwolone z poziomu tabeli BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA - aktualizujemy istniejący rekord
  175. $powiazanieID = $this->powiazanie['ID'];
  176. } else { // wyzwolone z poziomu tabeli BI_audit_ENERGA_PRACOWNICY - dodajemy nowy rekord
  177. if (count($prID) != 1) throw new Exception("Błąd formularza!");
  178. if (!($lAppoitmentInfo = V::get('info', false, $_POST))) throw new Exception("Błąd formularza!");
  179. if (!($BiAnalizaMinDepth = V::get('minDepth', false, $_POST))) throw new Exception("Błąd formularza!");
  180. if (!($BiAnalizaMaxDepth = V::get('maxDepth', false, $_POST))) throw new Exception("Błąd formularza!");
  181. if (!($BiAnalizaOnlyTargets = V::get('onlyTargets', false, $_POST))) throw new Exception("Błąd formularza!");
  182. $query = "select * from BI_audit_ENERGA_PRACOWNICY where ID='{$prID[0]}'";
  183. $result = DB::getPDO()->fetchFirst($query);
  184. if (!$result) throw new Exception("Błąd formularza!");
  185. $sqlInsert = [
  186. 'L_APPOITMENT_INFO' => $lAppoitmentInfo,
  187. 'A_STATUS' => 'NORMAL',
  188. 'A_STATUS_INFO' => 'Dodane przez BiAuditGenerate z poziomu tabeli BI_audit_ENERGA_PRACOWNICY',
  189. 'A_ADM_COMPANY' => $result['A_ADM_COMPANY'],
  190. 'A_CLASSIFIED' => $result['A_CLASSIFIED'],
  191. 'FILE_STATUS' => 'NONE',
  192. 'FILE_STATUS_info' => 'Oczekuję na zdefiniowanie danych wejściowych',
  193. 'BI_analiza_reloadCache' => $sqlUpdate['BI_analiza_reloadCache'],
  194. 'BI_analiza_minDepth' => $BiAnalizaMinDepth,
  195. 'BI_analiza_maxDepth' => $BiAnalizaMaxDepth,
  196. 'BI_analiza_onlyTargets' => $BiAnalizaOnlyTargets,
  197. ];
  198. $powiazanieID = DB::getDB()->ADD_NEW_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', (object)$sqlInsert);
  199. if ($powiazanieID) SE_Layout::alert('success','Dodano rekord do wygenerowania powiązań');
  200. else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  201. }
  202. $sqlUpdate['ID'] = $powiazanieID;
  203. self::truncatePowiazaniaFromDB($powiazanieID);
  204. $refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
  205. foreach ($prID as $v) DB::getPDO()->insert($refPowiazaniaToPracownicy, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $v]);
  206. $refPowiazaniaToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  207. foreach ($kontrahenci as $kontrahent) DB::getPDO()->insert($refPowiazaniaToKontrahenci, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $kontrahent['ID']]);
  208. $refPowiazaniaToKwRequestedPreson = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_KW_requested_person', true);
  209. foreach ($requestedPersons as $requestedPerson) DB::getPDO()->insert($refPowiazaniaToKwRequestedPreson, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $requestedPerson['ID']]);
  210. $affected = DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlUpdate);
  211. if ($affected) {
  212. if ($this->powiazanie) {
  213. SE_Layout::alert('success','Oznaczono rekord do wygenerowania powiązań');
  214. ?>
  215. <div class="container" style="text-align:center">
  216. <a href="<?=$this->REFERER?>" class="btn btn-primary">Powrót</a>
  217. </div>
  218. <?php
  219. }
  220. } else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  221. }
  222. private function initializePowiazania() {
  223. switch (V::get('action', '', $_POST)) {
  224. case "initialize":
  225. $this->initializePowiazaniaSave();
  226. break;
  227. default:
  228. $this->initializePowiazaniaForm();
  229. }
  230. }
  231. private function showPowiazania() {
  232. // echo "Statystyki znalezionych powiązań [TODO]";
  233. $dir = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  234. $url = self::getUrl('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  235. $reports = [
  236. 'pdf' => [
  237. 'files' => glob("{$dir}/relations*.pdf"),
  238. 'label' => 'Raporty PDF:<br/>&nbsp;',
  239. 'button' => 'Pokaż raport PDF',
  240. 'regex' => "/^relations(-{$this->powiazanie['ID']})?_([[:digit:]]+)\.pdf$/",
  241. 'parentDir' => false,
  242. ],
  243. 'html' => [
  244. 'files' => glob("{$dir}/html*/relations-{$this->powiazanie['ID']}*.html"),
  245. 'label' => 'Raporty HTML<br/>do przeglądania:',
  246. 'button' => 'Pokaż raport HTML',
  247. 'regex' => "/^relations-({$this->powiazanie['ID']})_([[:digit:]]+)\.html$/",
  248. 'parentDir' => true,
  249. ],
  250. 'htmlZip' => [
  251. 'files' => glob("{$dir}/html*.zip"),
  252. 'label' => 'Raporty HTML<br/>do pobrania:',
  253. 'button' => 'Pobież raport HTML',
  254. 'regex' => "/^html(-{$this->powiazanie['ID']})?_([[:digit:]]+)\.zip$/",
  255. 'parentDir' => false,
  256. ],
  257. ];
  258. ?>
  259. <div class="container" style="margin-top:20px">
  260. <legend>
  261. Wygenerowany raport nr <?=$this->powiazanie['ID']?>
  262. </legend>
  263. <div class="form-group" style="text-align: center;">
  264. <?php
  265. array_walk($reports, function ($report) use ($url) {
  266. echo "<div class=\"col-sm-2\"><h4>{$report['label']}</h4>";
  267. $hrefs = array_filter(array_map(function ($path) use ($url, $report) {
  268. if (!is_file($path)) return false;
  269. $file = basename($path);
  270. if (preg_match($report['regex'], $file, $matches)) $i = " (" . ltrim($matches[2], '0') . ")";
  271. else $i = '';
  272. if ($report['parentDir']) $file = basename(dirname($path)) . "/" . $file;
  273. return "<a href=\"{$url}/{$file}\" target=\"_blank\" class=\"btn btn-primary\">{$report['button']}{$i}</a>";
  274. }, $report['files']));
  275. if ($hrefs) echo implode('<br/><br/>', $hrefs);
  276. else echo "<h5>Nie znaleziono</h5>";
  277. echo "</div>\n";
  278. });
  279. ?>
  280. </div>
  281. <div class="form-group">
  282. <div class="col-sm-12">
  283. <br/><br/><a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  284. </div>
  285. </div>
  286. </div>
  287. <?php
  288. }
  289. private function showPowiazaniaList() {
  290. switch (V::get('action', '', $_POST)) {
  291. case "initialize":
  292. $this->initializePowiazaniaSave();
  293. break;
  294. }
  295. $this->showPowiazaniaListForm();
  296. }
  297. private function showPowiazaniaListForm() {
  298. if (!$this->SOURCE['ID']) throw new Exception("Błąd danych");
  299. elseif ($this->SOURCE['TABLE'] != 'BI_audit_ENERGA_PRACOWNICY') throw new Exception("Błąd danych");
  300. $query = "select * from `{$this->SOURCE['TABLE']}` where ID = '{$this->SOURCE['ID']}'";
  301. $pracownik = DB::getPDO()->fetchFirst($query);
  302. if (!$pracownik) throw new Exception("Błąd danych");
  303. ?>
  304. <div class="container" style="margin-top:20px">
  305. <legend>
  306. Lista wygenerowanych powiązań :: <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>
  307. <span class="pull-right"># <?=$pracownik['ID']?></span>
  308. </legend>
  309. <div class="form-group">
  310. <div class="col-sm-12">
  311. <h4>Lista wygenerowanych powiązań, w których znajduje się pracownik</h4>
  312. <table class="table table-bordered table-hover table-striped" height=5>
  313. <thead>
  314. <tr style="text-align:center; background-color:lightgray">
  315. <td width=1>ID</td>
  316. <td>Adnotacje</td>
  317. <td>Minimalna głębokość analizy</td>
  318. <td>Maksymalna głębokość analizy</td>
  319. <td>Powiązania tylko do celów</td>
  320. <td>Status raportu</td>
  321. <td>Status raportu - informacje</td>
  322. <td>Indywidualny raport</td>
  323. <td width=1></td>
  324. </tr>
  325. </thead>
  326. <tbody>
  327. <?php
  328. $refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
  329. $query = "select `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.*
  330. from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  331. join `{$refPowiazaniaToPracownicy}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPracownicy}`.`PRIMARY_KEY`
  332. where `REMOTE_PRIMARY_KEY` = '{$this->SOURCE['ID']}'";
  333. $result = DB::getPDO()->fetchAll($query);
  334. if (!$result) echo '<tr><td align="center" colspan="9">Brak znalezionych powiązań</td></tr>';
  335. else {
  336. foreach ($result as $row) {
  337. $query = "select count(*) from `{$refPowiazaniaToPracownicy}` where `PRIMARY_KEY` = '{$row['ID']}'";
  338. $count = DB::getPDO()->fetchValue($query);
  339. ?>
  340. <tr>
  341. <td align="right"><?=$row['ID']?></td>
  342. <td><?=$row['L_APPOITMENT_INFO']?></td>
  343. <td><?=$row['BI_analiza_minDepth']?></td>
  344. <td><?=$row['BI_analiza_maxDepth']?></td>
  345. <td><?=($row['BI_analiza_onlyTargets'] == 'N' ? "Nie" : "Tak")?></td>
  346. <td><?=$row['FILE_STATUS']?></td>
  347. <td><?=$row['FILE_STATUS_info']?></td>
  348. <td><?=($count > 1 ? 'Nie' : 'Tak')?></td>
  349. <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>
  350. </tr>
  351. <?php
  352. }
  353. }
  354. ?>
  355. </tbody>
  356. </table>
  357. </div>
  358. </div>
  359. <div class="form-group">
  360. <div class="col-sm-12">
  361. <h4>Dodaj nowe zadanie generowania powiazań dla tego pracownika</h4>
  362. </div>
  363. </div>
  364. <form class="form-horizontal" method="post">
  365. <div class="form-group">
  366. <label class="col-sm-4 control-label">Minimalna głębokość poszukiwań (liczba rekurencji)</label>
  367. <div class="col-sm-1">
  368. <input type="number" class="form-control" name="minDepth" id="minDepth" data-bind="value:replyNumber" min="1" max="9" value="1" required/>
  369. </div>
  370. </div>
  371. <div class="form-group">
  372. <label class="col-sm-4 control-label">Maksymalna głębokość poszukiwań (liczba rekurencji)</label>
  373. <div class="col-sm-1">
  374. <input type="number" class="form-control" name="maxDepth" id="maxDepth" data-bind="value:replyNumber" min="1" max="9" value="6" required/>
  375. </div>
  376. </div>
  377. <div class="form-group">
  378. <label class="col-sm-4 control-label">Czy zwracać tylko wyniki ze znalezionymi obiektami docelowymi (z tabeli kontrahentów)?</label>
  379. <div class="col-sm-1">
  380. <select name="onlyTargets" class="form-control">
  381. <option value="Y" selected>Tak</option>
  382. <option value="N">Nie</option>
  383. </select>
  384. </div>
  385. </div>
  386. <div class="form-group">
  387. <label class="col-sm-4 control-label">Adnotacje</label>
  388. <div class="col-sm-4">
  389. <input type="text" class="form-control" name="info" value="Indywidualnie dla <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>" required/>
  390. </div>
  391. </div>
  392. <div class="form-group">
  393. <label class="col-sm-4 control-label">
  394. Odśwież cache
  395. </label>
  396. <div class="col-sm-2">
  397. <select name="reloadCache" class="form-control">
  398. <option value="No" selected>Nie</option>
  399. <!-- <option value="Part">Częściowe</option>-->
  400. <option value="Full">Pełne</option>
  401. </select>
  402. </div>
  403. </div>
  404. <div class="form-group">
  405. <div class="col-sm-offset-4 col-sm-8">
  406. <!-- Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>-->
  407. Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów.<br/>
  408. Uwaga! Jeżeli aktywne są inne zadania, te zadanie zostanie wstrzymane do momentu ich ukończenia.
  409. </div>
  410. </div>
  411. <div class="form-group">
  412. <div class="col-sm-12">
  413. <div class="containter" style="text-align:center">
  414. <button type="submit" class="btn btn-primary" name="action" value="initialize" onClick="return validate()">Generuj</button>
  415. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  416. </div>
  417. </div>
  418. </div>
  419. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  420. <input type="hidden" name="prID[]" value="<?=$pracownik['ID']?>">
  421. </form>
  422. </div>
  423. <script language="JavaScript">
  424. <!--
  425. function validate() {
  426. result = (document.getElementById('minDepth').value <= document.getElementById('maxDepth').value);
  427. if (!result) alert('Wartość minimalnej głębokości analizy nie może być większa od wartości maksymalnej głębokości analizy!');
  428. return result;
  429. }
  430. -->
  431. </script>
  432. <?php
  433. }
  434. private function powiazania() {
  435. try {
  436. if (!$this->SOURCE) throw new Exception("Błąd danych");
  437. elseif (!(isset($this->SOURCE['TABLE']) && isset($this->SOURCE['ID']))) throw new Exception("Błąd danych");
  438. switch ($this->SOURCE['TABLE']) {
  439. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  440. $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->SOURCE['ID']}'");
  441. if (!$powiazania) throw new Exception("Błąd danych");
  442. $this->powiazanie = $powiazania[0];
  443. switch ($this->powiazanie['FILE_STATUS']) {
  444. case "NONE":
  445. $this->initializePowiazania();
  446. break;
  447. case "GENERATED":
  448. $this->showPowiazania();
  449. break;
  450. default: throw new Exception("Błędny status rekordu");
  451. }
  452. break;
  453. case "BI_audit_ENERGA_PRACOWNICY":
  454. $this->showPowiazaniaList();
  455. break;
  456. case "BI_audit_KRS":
  457. $this->importKrsToPracownicySearch($this->SOURCE['ID']);
  458. break;
  459. case "BI_audit_KRS_person":
  460. $this->showKrsForKrsPerson();
  461. break;
  462. default: throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate");
  463. }
  464. } catch (Exception $e) {
  465. SE_Layout::alert('danger',$e->getMessage());
  466. $_SESSION['REFERER'] = $this->REFERER;
  467. ?>
  468. <div class="container" style="text-align:center">
  469. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
  470. </div>
  471. <?php
  472. }
  473. }
  474. private function importKrsToPracownicy() {
  475. $action = V::get('action', '', $_POST);
  476. switch ($action) {
  477. case "search":
  478. $this->importKrsToPracownicySearch();
  479. break;
  480. default: $this->importKrsToPracownicyForm();
  481. }
  482. }
  483. private function importKrsToPracownicyForm() {
  484. ?>
  485. <div class="container" style="margin-top:20px">
  486. <legend>
  487. Importowanie podmiotów z KRS do tabel kontrahentów i pracowników
  488. </legend>
  489. <div class="form-group">
  490. <div class="col-sm-12">
  491. <h4>Znajdź podmiot</h4>
  492. </div>
  493. </div>
  494. <form class="form-horizontal" method="post">
  495. <div class="form-group">
  496. <label class="col-sm-1 control-label">Nazwa</label>
  497. <div class="col-sm-4">
  498. <input type="text" class="form-control" name="nazwa" title="Podaj nazwę podmiotu">
  499. </div>
  500. </div>
  501. <div class="form-group">
  502. <label class="col-sm-1 control-label">KRS</label>
  503. <div class="col-sm-2">
  504. <input type="text" class="form-control" name="krs" pattern="^[0-9]{0,10}$" title="Podaj KRS"/>
  505. </div>
  506. </div>
  507. <div class="form-group">
  508. <label class="col-sm-1 control-label">NIP</label>
  509. <div class="col-sm-2">
  510. <input type="text" class="form-control" name="nip" pattern="^[0-9]{0,10}$" title="Podaj NIP (bez kresek i bez oznaczenia kraju)"/>
  511. </div>
  512. </div>
  513. <div class="form-group">
  514. <label class="col-sm-1 control-label">Regon</label>
  515. <div class="col-sm-2">
  516. <input type="text" class="form-control" name="regon" pattern="^[0-9]{0,9}$" title="Podaj regon"/>
  517. </div>
  518. </div>
  519. <div class="form-group">
  520. <div class="col-sm-offset-1 col-sm-11">
  521. <button type="submit" class="btn btn-primary" name="action" value="search">Szukaj</button>
  522. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  523. </div>
  524. </div>
  525. </form>
  526. </div>
  527. <?php
  528. }
  529. private function importKrsToPracownicySearch($krsId = null) {
  530. $formItems = [
  531. "nazwa" => 'like',
  532. "krs" => '=',
  533. "nip" => '=',
  534. "regon" => '=',
  535. ];
  536. try {
  537. $subaction = V::get('subaction', '', $_POST);
  538. switch ($subaction) {
  539. case "listKrsPerson":
  540. $krsId = V::get('krsId', 0, $_POST, int);
  541. break;
  542. case "addKrsPersonToPracownicy":
  543. $krsId = V::get('krsId', 0, $_POST, int);
  544. $personId = V::get('personId', [], $_POST);
  545. if (!$personId) throw new Exception("Błąd formularza");
  546. $query = "insert into BI_audit_ENERGA_PRACOWNICY (source, imiona, nazwisko, pesel) select 'KRS', imiona, nazwisko, pesel from BI_audit_KRS_person where ID in (" . implode(", ", $personId) . ")";
  547. DB::getPDO()->query($query);
  548. SE_Layout::alert('success', "Pomyślnie zaimportowano " . count($personId) . " pracownik" . ((count($personId) == 1) ? "a" : "ów"));
  549. break;
  550. case "addKrsToKontrahenci":
  551. $krsId = V::get('krsId', 0, $_POST, int);
  552. if (!$krsId) throw new Exception("Błąd formularza");
  553. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI kh join BI_audit_KRS krs on (kh.NIP = krs.nip or kh.REGON = krs.regon or kh.KRS = krs.krs) where krs.ID = '{$krsId}'";
  554. $kontrahentExists = DB::getPDO()->fetchValue($query);
  555. if ($kontrahentExists) throw new Exception("Podmiot znajduje się już w tabeli kontrahentów");
  556. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (Tytul_dokumentu, Pelna_nazwa_kontrahenta, REGON, NIP, KRS) select 'ZaImportowano z KRS', nazwa, regon, nip, krs from BI_audit_KRS where ID = ".$krsId." ";
  557. DB::getPDO()->query($query);
  558. SE_Layout::alert('success', "Pomyślnie zaimportowano kontrahenta");
  559. break;
  560. }
  561. if ($krsId) {
  562. $where = ["ID = '{$krsId}'"];
  563. } else {
  564. $form = [];
  565. foreach ($formItems as $item => $type) {
  566. if ($param = V::get($item, '', $_POST)) {
  567. if ($type == 'like') $param = "%{$param}%";
  568. $form[$item] = DB::getPDO()->quote($param);
  569. }
  570. }
  571. if (!$form) throw new Exception("Nie wypełniono żadnego pola wyszukiwania!");
  572. $where = [];
  573. foreach ($form as $name => $value) $where[] = "`{$name}` {$formItems[$name]} {$value}";
  574. }
  575. } catch (Exception $e) {
  576. SE_Layout::alert('danger', $e->getMessage());
  577. $this->importKrsToPracownicyForm();
  578. return;
  579. }
  580. $query = "select * from `BI_audit_KRS` where " . implode(" and ", $where) . "order by ID limit 1001";
  581. $result = DB::getPDO()->fetchAll($query);
  582. if (count($result) == 1001) {
  583. SE_Layout::alert('danger', 'Znaleziono zbyt wiele wyników. Doprecyzuj parametry wyszukiwania.');
  584. $this->importKrsToPracownicyForm();
  585. return;
  586. } elseif (count($result) == 1) {
  587. $krsId = $result[0]['ID'];
  588. }
  589. ?>
  590. <div class="container" style="margin-top:20px">
  591. <form method="post">
  592. <legend>
  593. Importowanie podmiotów z KRS do tabel kontrahentów i pracowników
  594. </legend>
  595. <div class="form-group">
  596. <div class="col-sm-12">
  597. <h4>Znalezione podmioty:</h4>
  598. </div>
  599. </div>
  600. <div class="form-group">
  601. <div class="col-sm-12">
  602. <table class="table table-bordered table-hover table-striped" height=5>
  603. <thead>
  604. <tr style="text-align:center; background-color:lightgray">
  605. <td width=1>Lp.</td>
  606. <td>Nazwa</td>
  607. <td>Adres</td>
  608. <td>KRS</td>
  609. <td>NIP</td>
  610. <td>Regon</td>
  611. <?php
  612. if (count($result) > 1) {
  613. ?>
  614. <td width=1>Wybierz</td>
  615. <?php
  616. }
  617. ?>
  618. </tr>
  619. </thead>
  620. <tbody>
  621. <?php
  622. if (!$result) echo '<tr><td align="center" colspan="6">Nie znaleziono podmiotu</td></tr>';
  623. else {
  624. $lp = 1;
  625. foreach ($result as $row) {
  626. $adres = $row['A_miejscowosc'];
  627. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  628. if ($row['A_nrDomu']) {
  629. $adres .= " {$row['A_nrDomu']}";
  630. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  631. }
  632. ?>
  633. <tr>
  634. <td align="right"><?=$lp++?></td>
  635. <td><?=htmlspecialchars($row['nazwa'])?></td>
  636. <td><?=htmlspecialchars($adres)?></td>
  637. <td><?=$row['krs']?></td>
  638. <td><?=$row['nip']?></td>
  639. <td><?=$row['regon']?></td>
  640. <?php
  641. if (count($result) > 1) {
  642. ?>
  643. <td align="center">
  644. <input type="radio" name="krsId" value="<?=$row['ID']?>"/>
  645. </td>
  646. <?php
  647. }
  648. ?>
  649. </tr>
  650. <?php
  651. }
  652. }
  653. ?>
  654. </tbody>
  655. </table>
  656. </div>
  657. </div>
  658. <?php
  659. if (count($result) > 1) {
  660. ?>
  661. <div class="form-group">
  662. <div class="col-sm-12">
  663. <?php
  664. foreach (array_keys($formItems) as $item) {
  665. ?>
  666. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  667. <?php
  668. }
  669. ?>
  670. <input type="hidden" name="back" value="search"/>
  671. <div class="containter" style="text-align:center">
  672. <button type="submit" class="btn btn-primary" name="subaction" value="listKrsPerson" onClick="return validateCompany(this)">Wybierz zaznaczony podmiot</button>
  673. <a href="" class="btn btn-default">Powrót</a>
  674. </div>
  675. </div>
  676. </div>
  677. <?php
  678. } elseif ($krsId) {
  679. ?>
  680. <div class="form-group">
  681. <div class="col-sm-12">
  682. <h4>Znalezione osoby:</h4>
  683. </div>
  684. </div>
  685. <div class="form-group">
  686. <div class="col-sm-12">
  687. <table class="table table-bordered table-hover table-striped" height=5>
  688. <thead>
  689. <tr style="text-align:center; background-color:lightgray">
  690. <td width=1>Lp.</td>
  691. <td>Nazwisko</td>
  692. <td>Imiona</td>
  693. <td>Pesel</td>
  694. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  695. </tr>
  696. </thead>
  697. <tbody>
  698. <?php
  699. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI kh join BI_audit_KRS krs on (kh.NIP = krs.nip or kh.REGON = krs.regon or kh.KRS = krs.krs) where krs.ID = '{$krsId}'";
  700. $kontrahentExists = DB::getPDO()->fetchValue($query);
  701. $refKrsToKrsPerson = BiAuditRefTables::getRefTable('BI_audit_KRS', 'BI_audit_KRS_person', true);
  702. $query = "select person.*, pracownicy.ID as pracownicyId from `{$refKrsToKrsPerson}` ref join `BI_audit_KRS_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}'";
  703. $result = DB::getPDO()->fetchAll($query);
  704. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono osób powiązanych z podmiotem</td></tr>';
  705. else {
  706. $lp = 1;
  707. foreach ($result as $row) {
  708. ?>
  709. <tr<?=($row['pracownicyId'] ? ' style="color:darkgrey"' : '')?>>
  710. <td align="right"><?=$lp++?></td>
  711. <td><?=$row['nazwisko']?></td>
  712. <td><?=$row['imiona']?></td>
  713. <td><?=$row['pesel']?></td>
  714. <td><input type="checkbox" name="personId[]" value="<?=$row['ID']?>" onClick="toggle(this)" <?=($row['pracownicyId'] ? "disabled" : "")?>/></td>
  715. </tr>
  716. <?php
  717. }
  718. }
  719. ?>
  720. </tbody>
  721. </table>
  722. </div>
  723. </div>
  724. <!-- <div class="form-group">
  725. <div class="col-sm-12">
  726. <label class="col-sm-4 control-label">Opis/źródło</label>
  727. <div class="col-sm-4">
  728. <input type="text" class="form-control" name="source" placeholder="KRS"/>
  729. </div>
  730. </div>
  731. </div>-->
  732. <div class="form-group">
  733. <div class="col-sm-12" style="text-align: center;">
  734. <button type="submit" class="btn btn-primary" name="subaction" value="addKrsToKontrahenci"<?=($kontrahentExists ? " disabled" : "")?>>Dodaj firmę do tabeli kontrahentów</button>
  735. <button type="submit" class="btn btn-primary" name="subaction" value="addKrsPersonToPracownicy" onClick="return validatePerson(this)">Dodaj zaznaczone osoby do tabeli pracowników</button>
  736. <input type="hidden" name="krsId" value="<?=$krsId?>"/>
  737. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  738. <?php
  739. if (V::get('back', '', $_POST) == 'search') {
  740. foreach (array_keys($formItems) as $item) {
  741. ?>
  742. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  743. <?php
  744. }
  745. ?>
  746. <button type="submit" class="btn btn-default" name="action" value="search">Powrót</button>
  747. <?php
  748. } else {
  749. ?>
  750. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  751. <?php
  752. }
  753. ?>
  754. </div>
  755. </div>
  756. <?php
  757. }
  758. ?>
  759. <input type="hidden" name="action" value="search">
  760. </form>
  761. </div>
  762. <script language="JavaScript">
  763. <!--
  764. function toggleAll(source) {
  765. checkboxes = document.getElementsByName('personId[]');
  766. checked = false;
  767. for(var i=0, n=checkboxes.length;i<n;i++) {
  768. if (!checkboxes[i].disabled) {
  769. checkboxes[i].checked = source.checked;
  770. checked = true;
  771. }
  772. }
  773. if (source.checked && (!checked)) source.checked = false;
  774. }
  775. function toggle(source) {
  776. checkboxes = document.getElementsByName('personId[]');
  777. all = true;
  778. for(var i=0, n=checkboxes.length;i<n;i++) if(!checkboxes[i].disabled && checkboxes[i].checked == false) all = false;
  779. source.form['checkAll'].checked = all;
  780. }
  781. function validatePerson(source) {
  782. checkboxes = document.getElementsByName('personId[]');
  783. checked = false;
  784. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked) checked = true;
  785. if (!checked) alert('Nie wybrano żadnej osoby!');
  786. return checked;
  787. }
  788. function validateCompany(source) {
  789. radios = document.getElementsByName('krsId');
  790. checked = false;
  791. for(var i=0, n=radios.length;i<n;i++) if(radios[i].checked) checked = true;
  792. if (!checked) alert('Nie wybrano żadnej firmy!');
  793. return checked;
  794. }
  795. -->
  796. </script>
  797. <?php
  798. }
  799. private function showKrsForKrsPerson() {
  800. $query = "select * from BI_audit_KRS_person where ID = '{$this->SOURCE['ID']}'";
  801. $result = DB::getPDO()->fetchFirst($query);
  802. ?>
  803. <div class="container" style="margin-top:20px">
  804. <legend>
  805. Lista podmiotów, w których występuje <?="{$result['nazwisko']} {$result['imiona']}" . ($result['pesel'] ? " (PESEL: {$result['pesel']})" : "")?>
  806. </legend>
  807. <div class="form-group">
  808. <div class="col-sm-12">
  809. <table class="table table-bordered table-hover table-striped" height=5>
  810. <thead>
  811. <tr style="text-align:center; background-color:lightgray">
  812. <td width=1>Lp.</td>
  813. <td>Nazwa</td>
  814. <td>Adres</td>
  815. <td>KRS</td>
  816. <td>NIP</td>
  817. <td>Regon</td>
  818. <td width=1></td>
  819. </tr>
  820. </thead>
  821. <tbody>
  822. <?php
  823. $refKrsToKrsPerson = BiAuditRefTables::getRefTable('BI_audit_KRS', 'BI_audit_KRS_person', true);
  824. $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']}'";
  825. $result = DB::getPDO()->fetchAll($query);
  826. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono powiązanych podmiotów</td></tr>';
  827. else {
  828. $lp = 1;
  829. foreach ($result as $row) {
  830. $adres = $row['A_miejscowosc'];
  831. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  832. if ($row['A_nrDomu']) {
  833. $adres .= " {$row['A_nrDomu']}";
  834. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  835. }
  836. ?>
  837. <tr>
  838. <td align="right"><?=$lp++?></td>
  839. <td><?=htmlspecialchars($row['nazwa'])?></td>
  840. <td><?=htmlspecialchars($adres)?></td>
  841. <td><?=$row['krs']?></td>
  842. <td><?=$row['nip']?></td>
  843. <td><?=$row['regon']?></td>
  844. <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>
  845. </tr>
  846. <?php
  847. }
  848. }
  849. ?>
  850. </tbody>
  851. </table>
  852. </div>
  853. </div>
  854. <div class="form-group">
  855. <div class="col-sm-12">
  856. <div class="containter" style="text-align:center">
  857. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-default">Powrót</a>
  858. </div>
  859. </div>
  860. </div>
  861. </div>
  862. <?php
  863. }
  864. public function defaultAction() {
  865. SE_Layout::gora();
  866. SE_Layout::menu();
  867. if (isset($_SESSION['REFERER'])) {
  868. $this->REFERER = $_SESSION['REFERER'];
  869. unset($_SESSION['REFERER']);
  870. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  871. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  872. if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
  873. elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
  874. elseif (($ID = V::get('ID_BI_audit_KRS', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  875. elseif (($ID = V::get('ID_BI_audit_KRS_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS_person';
  876. if ($this->SOURCE) {
  877. $this->SOURCE['ID'] = $ID;
  878. $this->powiazania();
  879. }
  880. elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
  881. switch ($TABLE) {
  882. case "default_db/BI_audit_ENERGA_PRACOWNICY":
  883. $this->importKrsToPracownicy();
  884. break;
  885. default: SE_Layout::alert('danger', 'Błąd parametru');
  886. }
  887. }
  888. else SE_Layout::alert('danger', 'Błąd parametru');
  889. SE_Layout::dol();
  890. }
  891. private static function truncatePowiazaniaFromDB($ID) {
  892. $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  893. if (!$refTables) return null;
  894. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  895. $refTables = array_diff($refTables, [$refPowiazaniaToPowiazaniaRow]);
  896. $query = "delete from `" . implode("`, `", $refTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  897. foreach ($refTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  898. $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  899. DB::getPDO()->query($query);
  900. }
  901. private static function deleteResultsFromDB($ID) {
  902. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  903. $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
  904. $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  905. $sqlDeleteFrom = "delete from
  906. `{$refPowiazaniaToPowiazaniaRow}`,
  907. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
  908. `{$refPowiazaniaRowToPowiazaniaRowObject}`,
  909. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
  910. $sqlUsing = "
  911. using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  912. join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
  913. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
  914. join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
  915. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
  916. $sqlWhere = "
  917. where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  918. foreach ($refTables as $refTable) {
  919. $sqlDeleteFrom .= ",\n`{$refTable}`";
  920. $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  921. }
  922. $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
  923. DB::getPDO()->query($query);
  924. }
  925. public function doGenerate() {
  926. $generatePhpScript = function($function) {
  927. return '<?php
  928. ini_set("memory_limit", "4G");
  929. define("DS", DIRECTORY_SEPARATOR);
  930. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  931. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  932. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  933. ini_set("display_startup_errors", "0");
  934. ini_set("display_errors", "1");
  935. ini_set("log_errors", "1");
  936. ini_set("error_log", "/var/log/apache2/error_log");
  937. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  938. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  939. date_default_timezone_set("Europe/Warsaw");
  940. Lib::loadClass("Router");
  941. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  942. ';
  943. };
  944. try {
  945. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  946. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  947. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  948. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  949. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  950. ### Ustawienie zmiennych
  951. $powiazaniaDirLocation = self::getMainDirectory();
  952. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  953. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  954. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  955. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  956. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  957. ### Utworzenie niezbędnych katalogów i plików
  958. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0770, true);
  959. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  960. ### Wyłączenie wcześniej używanego mechanizmu wymuszania częściowego odświeżania cache - teraz działa to z automatu
  961. $sqlArr = [
  962. 'BI_analiza_reloadCache' => 'No',
  963. ];
  964. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Part') and FILE_STATUS = 'TO_GENERATE'";
  965. $result = DB::getPDO()->fetchAll($query);
  966. foreach ($result as $row) {
  967. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  968. }
  969. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  970. $doGenerate = true;
  971. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full') and FILE_STATUS = 'TO_GENERATE'";
  972. $result = DB::getPDO()->fetchAll($query);
  973. if ($result) {
  974. $doGenerate = false;
  975. $sqlArr = [];
  976. if (file_exists($reloadCachePhpFile)) {
  977. if (file_exists($reloadCacheResultFile)) {
  978. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  979. if ($reloadCacheResult == "ok") {
  980. $sqlArr = [
  981. 'FILE_STATUS_info' => 'Ukończono pełne Odświeżenie cache, oczekiwanie na wygenerowanie powiązań',
  982. 'BI_analiza_reloadCache' => 'No',
  983. ];
  984. $doGenerate = true;
  985. } else {
  986. $sqlArr = [
  987. 'FILE_STATUS' => 'ERROR',
  988. 'FILE_STATUS_info' => "Wystąpił błąd podczas pełnego odświeżania cache ({$reloadCacheResult})",
  989. ];
  990. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  991. $result = DB::getPDO()->fetchAll($query);
  992. }
  993. unlink($reloadCachePhpFile);
  994. unlink($reloadCachePidFile);
  995. unlink($reloadCacheResultFile);
  996. } elseif (file_exists($reloadCachePidFile)) {
  997. $pid = file_get_contents($reloadCachePidFile);
  998. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  999. $processShouldBeRunning = "php {$reloadCachePhpFile}";
  1000. if ($processRunning != $processShouldBeRunning) {
  1001. if (!file_exists($reloadCacheResultFile)) {
  1002. $sqlArr = [
  1003. 'FILE_STATUS' => 'ERROR',
  1004. 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas pełnego odświeżania cache - nie znaleziono procesu potomnego",
  1005. ];
  1006. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  1007. $result = DB::getPDO()->fetchAll($query);
  1008. unlink($reloadCachePhpFile);
  1009. unlink($reloadCachePidFile);
  1010. unlink($reloadCacheResultFile);
  1011. }
  1012. }
  1013. }
  1014. } else {
  1015. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1016. $result2 = DB::getPDO()->fetchValue($query);
  1017. if ($result2) {
  1018. $sqlArr = [
  1019. 'FILE_STATUS_info' => 'Wstrzymano pełne odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  1020. ];
  1021. } else {
  1022. $sqlArr = [
  1023. 'FILE_STATUS_info' => 'W trakcie pełnego odświeżania cache',
  1024. ];
  1025. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
  1026. $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
  1027. file_put_contents($reloadCachePhpFile, $generatePhpScript("doReloadCache({$fullReloadCache})"));
  1028. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  1029. }
  1030. }
  1031. if ($sqlArr) {
  1032. foreach ($result as $row) {
  1033. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  1034. }
  1035. }
  1036. }
  1037. ### Generowanie powiązań
  1038. if ($doGenerate) {
  1039. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
  1040. $result = DB::getPDO()->fetchAll($query);
  1041. foreach ($result as $row) {
  1042. $sqlArr = [
  1043. 'ID' => $row['ID'],
  1044. 'FILE_STATUS' => 'IN_PROGRESS',
  1045. 'FILE_STATUS_info' => 'W trakcie generowania powiązań',
  1046. ];
  1047. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1048. self::deleteResultsFromDB($row['ID']);
  1049. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1050. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1051. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  1052. $generatePowiazaniaProgressFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.progress";
  1053. if (file_exists($generatePowiazaniaResultFile)) unlink ($generatePowiazaniaResultFile);
  1054. if (file_exists($generatePowiazaniaProgressFile)) unlink ($generatePowiazaniaProgressFile);
  1055. file_put_contents($generatePowiazaniaPhpFile, $generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  1056. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  1057. }
  1058. }
  1059. ### Weryfikacja świeżo wygenerowanych powiązań
  1060. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1061. $result = DB::getPDO()->fetchAll($query);
  1062. foreach ($result as $row) {
  1063. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1064. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  1065. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1066. $error = false;
  1067. $success = false;
  1068. $sqlArr = [];
  1069. if (file_exists($generatePowiazaniaResultFile)) {
  1070. $generatePowiazaniaResult = json_decode(file_get_contents($generatePowiazaniaResultFile), true);
  1071. if ($generatePowiazaniaResult['result'] == "ok") {
  1072. $powiazanieDirLocation = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  1073. if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0770, false);
  1074. if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
  1075. else $success = true;
  1076. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult['message']})";
  1077. } elseif (file_exists($generatePowiazaniaPidFile)) {
  1078. $pid = file_get_contents($generatePowiazaniaPidFile);
  1079. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1080. $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
  1081. if ($processRunning != $processShouldBeRunning) {
  1082. if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
  1083. }
  1084. }
  1085. if ($error) {
  1086. $sqlArr = [
  1087. 'FILE_STATUS' => 'ERROR',
  1088. 'FILE_STATUS_info' => $error,
  1089. ];
  1090. self::deleteResultsFromDB($row['ID']);
  1091. //if (file_exists($xmlFile)) unlink($xmlFile);
  1092. } elseif ($success) {
  1093. $sqlArr = [
  1094. 'FILE_STATUS' => 'GENERATED',
  1095. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  1096. ];
  1097. if ($generatePowiazaniaResult['parts']) {
  1098. for ($i = 1; $i <= $generatePowiazaniaResult['parts']; $i++) {
  1099. $partNo = str_pad($i, 6, '0', STR_PAD_LEFT);
  1100. $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}_{$partNo}";
  1101. $generatePowiazaniaXmlFile = "{$generateFilesName}.xml";
  1102. $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
  1103. $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
  1104. $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
  1105. $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.xml";
  1106. $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.pdf";
  1107. $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}";
  1108. $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}.zip";
  1109. if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
  1110. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1111. if (file_exists($generatePowiazaniaHtmlDir)) {
  1112. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1113. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1114. }
  1115. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1116. }
  1117. } else {
  1118. $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}";
  1119. $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
  1120. $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
  1121. $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
  1122. $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.xml";
  1123. $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.pdf";
  1124. $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}";
  1125. $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}.zip";
  1126. if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
  1127. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1128. if (file_exists($generatePowiazaniaHtmlDir)) {
  1129. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1130. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1131. }
  1132. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1133. }
  1134. }
  1135. if ($sqlArr) {
  1136. $sqlArr['ID'] = $row['ID'];
  1137. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1138. if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
  1139. if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
  1140. if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
  1141. }
  1142. }
  1143. } catch (Exception $e) {
  1144. echo $e->getMessage()."\n";
  1145. }
  1146. }
  1147. private static function importPracownicy() { //TODO
  1148. $fields = [
  1149. 'BI_audit_ENERGA_PRACOWNICY' => [
  1150. 'PERNR',
  1151. 'imiona',
  1152. 'nazwisko',
  1153. 'pesel',
  1154. 'nr_konta',
  1155. 'jednostka_organizacyjna',
  1156. 'nip',
  1157. 'regon',
  1158. 'krs',
  1159. 'source',
  1160. ],
  1161. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1162. 'kodPocztowy',
  1163. 'miejscowosc',
  1164. 'ulica',
  1165. 'nrBudynku',
  1166. 'nrLokalu',
  1167. ],
  1168. ];
  1169. $query = "select * from `BI_audit_ENERGA_PRACOWNICY_import` where `importResult` = 'none'";
  1170. $pracownicy = DB::getPDO()->query($query);
  1171. while ($pracownik = $pracownicy->fetch()) {
  1172. $ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `pesel` = '{$pracownik['pesel']}'");
  1173. $sqlArr = [];
  1174. foreach ($fields['BI_audit_ENERGA_PRACOWNICY'] as $field) $sqlArr[$field] = trim($pracownik[$field]);
  1175. if ($ID_pracownik) DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY', 'ID', $ID, $sqlArr);
  1176. else $ID_pracownik = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', $sqlArr);
  1177. $sqlArr = [];
  1178. foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $field) {
  1179. $sqlArr[$field] = trim($pracownik[$field]);
  1180. if (!$sqlArr[$field]) unset($sqlArr[$field]);
  1181. }
  1182. if (!$sqlArr) break;
  1183. $sql = [];
  1184. // foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $field) {
  1185. // if (isset($sqlArr[$field])) $sql[] = "`{$field}` = " . DUPA;
  1186. // }
  1187. }
  1188. }
  1189. private static function reloadCache_parseUmowy($full = false) {
  1190. $fields = [
  1191. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1192. 'Tytul_dokumentu',
  1193. 'Pelna_nazwa_kontrahenta',
  1194. 'NIP',
  1195. 'REGON',
  1196. 'KRS',
  1197. 'Kraj',
  1198. 'Kod_pocztowy',
  1199. 'Miejscowosc',
  1200. 'Ulica',
  1201. 'Numer_budynku',
  1202. 'Numer_mieszkania_lokalu',
  1203. 'TERYT_SYM',
  1204. 'TERYT_SYM_UL',
  1205. ],
  1206. 'BI_audit_KRS' => [
  1207. '"Zaimportowanoz KRS na podstawie umowy"',
  1208. 'nazwa',
  1209. 'nip',
  1210. 'regon',
  1211. 'krs',
  1212. 'A_kraj',
  1213. 'A_kod',
  1214. 'A_miejscowosc',
  1215. 'A_ulica',
  1216. 'A_nrDomu',
  1217. 'A_nrLokalu',
  1218. 'TERYT_SYM',
  1219. 'TERYT_SYM_UL',
  1220. ],
  1221. 'BI_audit_CEIDG' => [
  1222. '"Zaimportowano z CEiDG na podstawie umowy"',
  1223. 'firma',
  1224. 'nip',
  1225. 'regon',
  1226. 'null',
  1227. 'kraj',
  1228. 'kodPocztowy',
  1229. 'miejscowosc',
  1230. 'ulica',
  1231. 'budynek',
  1232. 'lokal',
  1233. 'TERYT_SYM',
  1234. 'TERYT_SYM_UL',
  1235. ],
  1236. ];
  1237. $refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  1238. if ($full) {
  1239. DB::getPDO()->query("truncate table `{$refTable}`");
  1240. DB::getPDO()->query("update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
  1241. }
  1242. $query = <<<SQL
  1243. update `BI_audit_ENERGA_RUM_UMOWY` set `Wartosc` = replace(
  1244. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_`,
  1245. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_`,
  1246. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_`,
  1247. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_`,
  1248. if(`Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_`, 0))))),
  1249. ',', '.') where `A_STATUS` = 'WAITING';
  1250. SQL;
  1251. DB::getPDO()->query($query);
  1252. $query = "select `ID`, `Strony_umowy` from `BI_audit_ENERGA_RUM_UMOWY` where `A_STATUS` = 'WAITING'";
  1253. $result = DB::getPDO()->fetchAll($query);
  1254. foreach ($result as $row) {
  1255. $ID = $row['ID'];
  1256. $strony = array_map('trim', explode("|", $row['Strony_umowy']));
  1257. $K_IDs = [];
  1258. foreach ($strony as $item) {
  1259. $strona = array_map('trim', explode(";", $item));
  1260. $nr = null;
  1261. if (count($strona) == 3) $i = 1;//$nr = $strona[1];
  1262. elseif (count($strona) == 4) $i = 2;//$nr = $strona[2];
  1263. elseif (count($strona) >= 5 && count($strona) <= 6) $i = 3;//$nr = $strona[3];
  1264. else $i = null;
  1265. if ($i) $nr = $strona[$i];
  1266. $notFound = false;
  1267. if (is_numeric($nr)) {
  1268. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Numer_kontrahenta = '{$nr}'";
  1269. if ($K_ID = DB::getPDO()->fetchValue($query)) {
  1270. $K_IDs[] = $K_ID;
  1271. } else {
  1272. $nazwa = $strona[$i+1];
  1273. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Pelna_nazwa_kontrahenta = '" . addslashes($nazwa) . "'";
  1274. if ($result2 = DB::getPDO()->fetchAll($query)) {
  1275. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1276. } else $notFound = true;
  1277. }
  1278. } else $notFound = true;
  1279. if ($notFound) {
  1280. list($nip, $regon) = self::parseNipRegon($item);
  1281. if ($nip || $regon) {
  1282. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where NIP = '{$nip}' or REGON = '{$regon}'";
  1283. if ($result2 = DB::getPDO()->fetchall($query)) {
  1284. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1285. } else {
  1286. $query = "select ID from BI_audit_KRS where nip = '{$nip}' or regon = '{$regon}'";
  1287. if ($result2 = DB::getPDO()->fetchall($query)) {
  1288. foreach ($result2 as $item) {
  1289. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1290. " select " . implode(', ', $fields['BI_audit_KRS']) . " from BI_audit_KRS where ID = '{$item['ID']}'";
  1291. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1292. }
  1293. } else {
  1294. $query = "select ID from BI_audit_CEIDG where nip = '{$nip}' or regon = '{$regon}'";
  1295. if ($result2 = DB::getPDO()->fetchall($query)) {
  1296. foreach ($result2 as $item) {
  1297. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1298. " select " . implode(', ', $fields['BI_audit_CEIDG']) .
  1299. " from BI_audit_CEIDG where ID = '{$item['ID']}'";
  1300. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1301. }
  1302. }
  1303. }
  1304. }
  1305. }
  1306. }
  1307. }
  1308. foreach ($K_IDs as $K_ID) {
  1309. if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
  1310. DB::getPDO()->query("insert into `{$refTable}` (PRIMARY_KEY, REMOTE_PRIMARY_KEY) values ({$ID}, {$K_ID})");
  1311. }
  1312. }
  1313. DB::getPDO()->update('BI_audit_ENERGA_RUM_UMOWY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
  1314. }
  1315. $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";
  1316. $result = DB::getPDO()->fetchAll($query);
  1317. foreach ($result as $row) {
  1318. $query = "select nip, regon, krs from BI_audit_KRS where nip = '{$row['NIP']}' or regon = '{$row['REGON']}' or krs = '{$row['KRS']}'";
  1319. if ($items = DB::getPDO()->fetchAll($query)) {
  1320. list($nip, $regon, $krs) = [$items[0]["nip"], $items[0]["regon"], $items[0]["krs"]];
  1321. if (count($items) > 1) {
  1322. for ($i = 1; $i < count($items); $i++) {
  1323. if ($nip != $items[$i]["nip"]) $nip = null;
  1324. if ($regon != $items[$i]["regon"]) $regon = null;
  1325. if ($krs != $items[$i]["krs"]) $krs = null;
  1326. }
  1327. }
  1328. $set = [];
  1329. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  1330. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  1331. if ($krs && $krs != $row['KRS']) $set[] = "KRS = '{$krs}'";
  1332. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row['ID']}'");
  1333. }
  1334. }
  1335. $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";
  1336. $result = DB::getPDO()->fetchAll($query);
  1337. foreach ($result as $row) {
  1338. $query = "select nip, regon from BI_audit_CEIDG where nip = '{$row['NIP']}' or regon = '{$row['REGON']}'";
  1339. if ($items = DB::getPDO()->fetchAll($query)) {
  1340. list($nip, $regon) = [$items[0]["nip"], $items[0]["regon"]];
  1341. if (count($items) > 1) {
  1342. for ($i = 1; $i < count($items); $i++) {
  1343. if ($nip != $items[$i]["nip"]) $nip = null;
  1344. if ($regon != $items[$i]["regon"]) $regon = null;
  1345. }
  1346. }
  1347. $set = [];
  1348. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  1349. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  1350. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row->ID}'");
  1351. }
  1352. }
  1353. }
  1354. public static function reloadCache_reTeryt($full = false, $forceAll = false) {
  1355. Lib::loadClass('Teryt');
  1356. $tables = [
  1357. 'BI_audit_CEIDG' => [
  1358. 'fields' => [
  1359. 'wojewodztwo' => 'wojewodztwo',
  1360. 'powiat' => 'powiat',
  1361. 'gmina' => 'gmina',
  1362. 'miejscowosc' => 'miejscowosc',
  1363. 'ulica' => 'ulica',
  1364. 'kodPocztowy' => 'kodPocztowy',
  1365. ],
  1366. 'fieldsTeryt' => [
  1367. 'TERYT_SYM' => 'TERYT_SYM',
  1368. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1369. 'nrDomu' => 'budynek',
  1370. 'nrLokalu' => 'lokal',
  1371. ],
  1372. 'base' => '1',
  1373. ],
  1374. 'BI_audit_CEIDG_pelnomocnicy' => [
  1375. 'fields' => [
  1376. 'wojewodztwo' => 'wojewodztwo',
  1377. 'powiat' => 'powiat',
  1378. 'gmina' => 'gmina',
  1379. 'miejscowosc' => 'miejscowosc',
  1380. 'ulica' => 'ulica',
  1381. 'kodPocztowy' => 'kodPocztowy',
  1382. ],
  1383. 'fieldsTeryt' => [
  1384. 'TERYT_SYM' => 'TERYT_SYM',
  1385. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1386. 'nrDomu' => 'budynek',
  1387. 'nrLokalu' => 'lokal',
  1388. ],
  1389. 'base' => '1',
  1390. ],
  1391. 'BI_audit_ENERGA_PRACOWNICY' => [
  1392. 'fields' => [
  1393. 'miejscowosc' => 'miejscowosc',
  1394. 'kodPocztowy' => 'kodPocztowy',
  1395. 'ulica' => 'ulica',
  1396. ],
  1397. 'fieldsTeryt' => [
  1398. 'TERYT_SYM' => 'TERYT_SYM',
  1399. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1400. 'nrDomu' => 'nr',
  1401. 'nrLokalu' => 'nrLokalu',
  1402. ],
  1403. 'base' => '0',
  1404. ],
  1405. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1406. 'fields' => [
  1407. 'kodPocztowy' => 'kodPocztowy',
  1408. 'miejscowosc' => 'miejscowosc',
  1409. 'ulica' => 'ulica',
  1410. ],
  1411. 'fieldsTeryt' => [
  1412. 'TERYT_SYM' => 'TERYT_SYM',
  1413. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1414. 'nrDomu' => 'nrBudynku',
  1415. 'nrLokalu' => 'nrLokalu',
  1416. ],
  1417. 'base' => '0',
  1418. ],
  1419. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1420. 'fields' => [
  1421. 'kodPocztowy' => 'Kod_pocztowy',
  1422. 'miejscowosc' => 'Miejscowosc',
  1423. 'ulica' => 'Ulica',
  1424. ],
  1425. 'fieldsTeryt' => [
  1426. 'TERYT_SYM' => 'TERYT_SYM',
  1427. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1428. 'nrDomu' => 'Numer_budynku',
  1429. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  1430. ],
  1431. 'base' => '0',
  1432. ],
  1433. 'BI_audit_KRS' => [
  1434. 'fields' => [
  1435. 'wojewodztwo' => 'S_wojewodztwo',
  1436. 'powiat' => 'S_powiat',
  1437. 'gmina' => 'S_gmina',
  1438. 'miejscowosc' => 'A_miejscowosc',
  1439. 'ulica' => 'A_ulica',
  1440. 'kodPocztowy' => 'A_kod',
  1441. ],
  1442. 'fieldsTeryt' => [
  1443. 'TERYT_SYM' => 'TERYT_SYM',
  1444. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1445. 'nrDomu' => 'A_nrDomu',
  1446. 'nrLokalu' => 'A_nrLokalu',
  1447. ],
  1448. 'base' => '1',
  1449. ],
  1450. 'BI_audit_KRS_address' => [
  1451. 'fields' => [
  1452. 'wojewodztwo' => 'S_wojewodztwo',
  1453. 'powiat' => 'S_powiat',
  1454. 'gmina' => 'S_gmina',
  1455. 'miejscowosc' => 'A_miejscowosc',
  1456. 'ulica' => 'A_ulica',
  1457. 'kodPocztowy' => 'A_kod',
  1458. ],
  1459. 'fieldsTeryt' => [
  1460. 'TERYT_SYM' => 'TERYT_SYM',
  1461. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1462. 'nrDomu' => 'A_nrDomu',
  1463. 'nrLokalu' => 'A_nrLokalu',
  1464. ],
  1465. 'base' => '1',
  1466. ],
  1467. 'BI_audit_MSIG_address' => [
  1468. 'fields' => [
  1469. 'wojewodztwo' => 'S_wojewodztwo',
  1470. 'powiat' => 'S_powiat',
  1471. 'gmina' => 'S_gmina',
  1472. 'miejscowosc' => 'A_miejscowosc',
  1473. 'ulica' => 'A_ulica',
  1474. 'kodPocztowy' => 'A_kod',
  1475. ],
  1476. 'fieldsTeryt' => [
  1477. 'TERYT_SYM' => 'TERYT_SYM',
  1478. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1479. 'nrDomu' => 'A_nrDomu',
  1480. 'nrLokalu' => 'A_nrLokalu',
  1481. ],
  1482. 'base' => '1',
  1483. ],
  1484. ];
  1485. foreach ($tables as $table => $tableConf) {
  1486. DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrDomu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrDomu']}`) = ''");
  1487. DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrLokalu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrLokalu']}`) = ''");
  1488. $where = ($full && ($forceAll || (!$tableConf['base']))) ? "" : "where `TERYT_SYM` is null and `cached` = 0";
  1489. $query = "select * from `{$table}` {$where}";
  1490. $refTable = BiAuditRefTables::getRefTable($table, 'TERYT_adresy', true);
  1491. $terytJoinArr = [];
  1492. foreach ($tableConf['fieldsTeryt'] as $terytField => $tableField) {
  1493. $terytJoinArr[] = (
  1494. $terytField == 'nrLokalu'
  1495. ? "coalesce(`teryt`.`{$terytField}`, '') = coalesce(`table`.`{$tableField}`, '')"
  1496. : "`teryt`.`{$terytField}` = `table`.`{$tableField}`"
  1497. );
  1498. }
  1499. $terytJoin = implode(" and ", $terytJoinArr);
  1500. $insertFields = "`" . implode("`, `", array_keys($tableConf['fieldsTeryt'])) . "`";
  1501. $selectFields = "`" . implode("`, `", $tableConf['fieldsTeryt']) . "`";
  1502. $adresy = DB::getPDO()->query($query);
  1503. while ($adres = $adresy->fetch()) {
  1504. DB::getPDO()->query("delete from `{$refTable}` where `PRIMARY_KEY` = '{$adres['ID']}'");
  1505. if (!($forceAll and $adres['TERYT_SYM'])) {
  1506. $search = [];
  1507. foreach ($tableConf['fields'] as $field => $param) if (!empty($adres[$param])) $search[$field] = $adres[$param];
  1508. try {
  1509. $teryt = Teryt::search($search);
  1510. } catch (Exception $e) {
  1511. continue;
  1512. }
  1513. if (empty($teryt['SYM'])) continue;
  1514. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  1515. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  1516. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  1517. }
  1518. if (!trim($adres[$tableConf['fieldsTeryt']['nrDomu']])) continue;
  1519. $terytID = DB::getPDO()->fetchValue("select `teryt`.`ID` from `TERYT_adresy` as `teryt` join `{$table}` as `table` on {$terytJoin} where `table`.`ID` = '{$adres['ID']}'");
  1520. if (!$terytID) {
  1521. if (DB::getPDO()->query("insert into `TERYT_adresy` ({$insertFields}) select {$selectFields} from `{$table}` where `ID` = '{$adres['ID']}'")) {
  1522. if (!($terytID = DB::getPDO()->lastInsertId())) {
  1523. throw new Exception("Błąd dodania rekordu do TERYT_adresy #1");
  1524. }
  1525. } else {
  1526. throw new Exception("Błąd dodania rekordu do TERYT_adresy #2");
  1527. }
  1528. }
  1529. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $adres['ID'], 'REMOTE_PRIMARY_KEY' => $terytID]);
  1530. }
  1531. }
  1532. }
  1533. private static function reloadCache_updateAll($full, $onlyBase) {
  1534. $tablesConf = [
  1535. 'BI_audit_CEIDG' => [
  1536. 'fields' => [
  1537. 'nip' => 'nip',
  1538. 'regon' => 'regon',
  1539. ],
  1540. 'base' => '1',
  1541. ],
  1542. 'BI_audit_CEIDG_pelnomocnicy' => [
  1543. 'fields' => [
  1544. 'nip' => 'nip',
  1545. ],
  1546. 'base' => '1',
  1547. ],
  1548. 'BI_audit_CEIDG_powiazania' => [
  1549. 'fields' => [
  1550. 'nip' => 'nip',
  1551. 'regon' => 'regon',
  1552. ],
  1553. 'base' => '1',
  1554. ],
  1555. 'BI_audit_ENERGA_PRACOWNICY' => [
  1556. 'fields' => [
  1557. 'nip' => 'nip',
  1558. 'regon' => 'regon',
  1559. 'pesel' => 'pesel',
  1560. 'krs' => 'krs',
  1561. ],
  1562. 'base' => '0',
  1563. //'where' => '',
  1564. ],
  1565. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1566. 'fields' => [],
  1567. 'base' => '0',
  1568. //'where' => '',
  1569. ],
  1570. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1571. 'fields' => [
  1572. 'krs' => 'KRS',
  1573. 'nip' => 'NIP',
  1574. 'regon' => 'REGON',
  1575. 'pesel' => 'PESEL',
  1576. ],
  1577. 'base' => '0',
  1578. 'where' => "and ownCompany != 'Y'",
  1579. ],
  1580. 'BI_audit_KRS' => [
  1581. 'fields' => [
  1582. 'krs' => 'krs',
  1583. 'nip' => 'nip',
  1584. 'regon' => 'regon',
  1585. ],
  1586. 'base' => '1',
  1587. ],
  1588. 'BI_audit_KRS_address' => [
  1589. 'fields' => [],
  1590. 'base' => '1',
  1591. ],
  1592. 'BI_audit_KRS_company' => [
  1593. 'fields' => [
  1594. 'regon' => 'regon',
  1595. 'krs' => 'krs',
  1596. ],
  1597. 'base' => '1',
  1598. ],
  1599. 'BI_audit_KRS_person' => [
  1600. 'fields' => [
  1601. 'pesel' => 'pesel',
  1602. ],
  1603. 'base' => '1',
  1604. ],
  1605. 'BI_audit_MSIG' => [
  1606. 'fields' => [
  1607. 'krs' => 'krs',
  1608. 'nip' => 'nip',
  1609. 'regon' => 'regon',
  1610. ],
  1611. 'base' => '1',
  1612. ],
  1613. 'BI_audit_MSIG_address' => [
  1614. 'fields' => [],
  1615. 'base' => '1',
  1616. ],
  1617. 'BI_audit_MSIG_company' => [
  1618. 'fields' => [
  1619. 'regon' => 'regon',
  1620. 'krs' => 'krs',
  1621. ],
  1622. 'base' => '1',
  1623. ],
  1624. 'BI_audit_MSIG_person' => [
  1625. 'fields' => [
  1626. 'pesel' => 'pesel',
  1627. ],
  1628. 'base' => '1',
  1629. ],
  1630. // 'BI_audit_KW_requested_person' => [
  1631. // 'fields' => [
  1632. // 'pesel' => 'Seller_person_pesel',
  1633. // 'krs' => 'Seller_person_KRS',
  1634. // 'nip' => 'Seller_person_NIP',
  1635. // 'regon' => 'Seller_person_REGON',
  1636. // ],
  1637. // 'base' => '0',
  1638. // //'where' => '',
  1639. // ],
  1640. 'TERYT_adresy' => [
  1641. 'fields' => [],
  1642. 'base' => '1',
  1643. ],
  1644. ];
  1645. $refTablesConf = [
  1646. 'BI_audit_CEIDG' => [
  1647. 'refTablesTo' => [
  1648. 'BI_audit_CEIDG_pelnomocnicy',
  1649. 'BI_audit_CEIDG_powiazania',
  1650. 'TERYT_adresy',
  1651. ],
  1652. 'base' => 1,
  1653. ],
  1654. 'BI_audit_CEIDG_pelnomocnicy' => [
  1655. 'refTablesTo' => [
  1656. 'TERYT_adresy',
  1657. ],
  1658. 'base' => 1,
  1659. ],
  1660. 'BI_audit_ENERGA_PRACOWNICY' => [
  1661. 'refTablesTo' => [
  1662. 'BI_audit_ENERGA_PRACOWNICY_adresy',
  1663. 'TERYT_adresy',
  1664. ],
  1665. 'base' => 0,
  1666. ],
  1667. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1668. 'refTablesTo' => [
  1669. 'TERYT_adresy',
  1670. ],
  1671. 'base' => 0,
  1672. ],
  1673. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1674. 'refTablesTo' => [
  1675. 'TERYT_adresy',
  1676. ],
  1677. 'base' => 0,
  1678. ],
  1679. 'BI_audit_KRS' => [
  1680. 'refTablesTo' => [
  1681. 'BI_audit_KRS_address',
  1682. 'BI_audit_KRS_company',
  1683. 'BI_audit_KRS_person',
  1684. 'TERYT_adresy',
  1685. ],
  1686. 'base' => 1,
  1687. ],
  1688. 'BI_audit_KRS_address' => [
  1689. 'refTablesTo' => [
  1690. 'TERYT_adresy',
  1691. ],
  1692. 'base' => 1,
  1693. ],
  1694. 'BI_audit_MSIG' => [
  1695. 'refTablesTo' => [
  1696. 'BI_audit_MSIG_address',
  1697. 'BI_audit_MSIG_company',
  1698. 'BI_audit_MSIG_person',
  1699. ],
  1700. 'base' => 1,
  1701. ],
  1702. 'BI_audit_MSIG_address' => [
  1703. 'refTablesTo' => [
  1704. 'TERYT_adresy',
  1705. ],
  1706. 'base' => 1,
  1707. ],
  1708. ];
  1709. $sourceTables = ['BI_audit_ENERGA_PRACOWNICY'];
  1710. if ($full) {
  1711. foreach ($tablesConf as $table => $tableConf) if (!$tableConf['base']) $queries[] = "update `{$table}` set `cached` = 0";
  1712. $queries[] = "delete from `BI_audit_ALL` where `BASE` = 0";
  1713. // $queries[] = "optimize table `BI_audit_ALL`";
  1714. $queries[] = "delete from `BI_audit_ALL_ref` where `BASE` = 0";
  1715. // $queries[] = "optimize table `BI_audit_ALL_ref`";
  1716. $allTables = [];
  1717. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  1718. $allTables[] = $refTableFrom;
  1719. // if ($refTableConf['base']) continue;
  1720. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  1721. $allTables[] = $refTableTo;
  1722. if ($refTableConf['base']) continue;
  1723. $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
  1724. $queries[] = "update `{$refTable}` set `A_STATUS` = 'WAITNG' where `A_STATUS` = 'NORMAL'";
  1725. // $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}'";
  1726. }
  1727. }
  1728. $allTables = array_unique($allTables);
  1729. foreach ($allTables as $refTableFrom) {
  1730. foreach ($allTables as $refTableTo) {
  1731. if ($refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, false)) {
  1732. $queries[] = "delete from `{$refTable}` where `TRANSACTION_ID` = '-1'";
  1733. $queries[] = "optimize table `{$refTable}`";
  1734. $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";
  1735. }
  1736. }
  1737. }
  1738. }
  1739. foreach ($tablesConf as $table => $tableConf) {
  1740. if ($onlyBase && (!$tableConf['base'])) continue;
  1741. $where = "where `cached` = 0";
  1742. if (!empty($tableConf['where'])) $where .= " {$tableConf['where']}";
  1743. // $queries[] = "insert into `BI_audit_ALL` (`REMOTE_TABLE`, `REMOTE_ID`, `BASE`, " . implode(", ", array_keys($tableConf['fields'])) .
  1744. // ") select '{$table}', ID, '{$tableConf['base']}', " . implode(", ", $tableConf['fields']) . " from `{$table}` {$where}";
  1745. $fields = ["`REMOTE_TABLE`", "`REMOTE_ID`", "`BASE`"];
  1746. foreach (array_keys($tableConf['fields']) as $field) $fields[] = "`{$field}`";
  1747. $values = ["'{$table}'", "`ID`", "'{$tableConf['base']}'"];
  1748. foreach ($tableConf['fields'] as $value) $values[] = "`{$value}`";
  1749. $queries[] = "insert into `BI_audit_ALL` (" . implode(", ", $fields) . ") select " . implode(", ", $values) . " from `{$table}` {$where}";
  1750. $queries[] = "update `{$table}` set `cached` = 1 {$where}";
  1751. }
  1752. $queries[] = "update `BI_audit_ALL` set `nip` = null where `nip` = 0";
  1753. $queries[] = "update `BI_audit_ALL` set `regon` = null where `regon` = 0";
  1754. $queries[] = "update `BI_audit_ALL` set `krs` = null where `krs` = 0";
  1755. $queries[] = "update `BI_audit_ALL` set `pesel` = null where `pesel` = 0";
  1756. $queries[] = "set @var = (select round(coalesce(max(`ID`), '0.5'), 1) from `BI_audit_ALL_ref_RELATIONS`)";
  1757. $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";
  1758. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  1759. if ($onlyBase && (!$tableConf['base'])) continue;
  1760. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  1761. $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
  1762. $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`";
  1763. if (!in_array($refTableFrom, $sourceTables)) {
  1764. $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`";
  1765. }
  1766. if ($backRefTable = BiAuditRefTables::getRefTable($refTableTo, $refTableFrom, false)) {
  1767. $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'";
  1768. }
  1769. $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'";
  1770. }
  1771. }
  1772. foreach ($queries as $query) {
  1773. echo "SQL: {$query}\n";
  1774. DB::getPDO()->query($query);
  1775. }
  1776. $BiAuditRelations = new BiAuditRelations();
  1777. $result = DB::getPDO()->query("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
  1778. while ($row = $result->fetch()) $BiAuditRelations->findRelations($row['ID']);
  1779. DB::getPDO()->query("update `BI_audit_ALL` set `reffed` = 1");
  1780. }
  1781. public function doReloadCache($full = false) {
  1782. if ($full === 'base') {
  1783. $onlyBase = true;
  1784. $full = false;
  1785. } else {
  1786. $onlyBase = false;
  1787. }
  1788. $powiazaniaDirLocation = self::getMainDirectory();
  1789. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1790. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1791. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1792. if ($full) file_put_contents($reloadCachePidFile, getmypid());
  1793. try {
  1794. //self::importPracownicy(); //TODO
  1795. error_log('now: self::reloadCache_parseUmowy');
  1796. self::reloadCache_parseUmowy($full);
  1797. error_log('now: self::reloadCache_reTeryt');
  1798. self::reloadCache_reTeryt($full);
  1799. error_log('now: self::reloadCache_updateAll');
  1800. self::reloadCache_updateAll($full, $onlyBase);
  1801. if ($full) file_put_contents($reloadCacheResultFile, "ok");
  1802. } catch (Exception $e) {
  1803. var_dump($e);
  1804. if ($full) file_put_contents($reloadCacheResultFile, $e->getMessage());
  1805. else throw new Exception($e->getMessage());
  1806. }
  1807. }
  1808. public function doGeneratePowiazania($ID) {
  1809. $powiazaniaDirLocation = self::getMainDirectory();
  1810. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1811. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  1812. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  1813. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  1814. file_put_contents($pidFile, getmypid());
  1815. $tablesConf = [
  1816. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  1817. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  1818. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  1819. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  1820. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  1821. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  1822. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  1823. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  1824. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  1825. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  1826. ];
  1827. try {
  1828. $BiAuditPowiazania = new BiAuditPowiazania($ID, $tasksDirLocation);
  1829. $query = "select count(*) from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` where `FILE_STATUS` = 'IN_PROGRESS' and `BI_analiza_reloadCache` = 'Part' and ID != ${ID}";
  1830. $sqlArr = [
  1831. 'BI_analiza_reloadCache' => 'Part',
  1832. 'FILE_STATUS_info' => 'Odświeżam częściowo cache',
  1833. ];
  1834. do {
  1835. DB::getPDO()->query("lock tables `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` write");
  1836. $activeReloadingCache = DB::getPDO()->fetchValue($query);
  1837. if (!$activeReloadingCache) DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  1838. DB::getPDO()->query("unlock tables");
  1839. if ($activeReloadingCache) {
  1840. BiAuditPowiazania::saveToLog("Czekam na zakończenie częściowego odświeżania cache przez inne zadanie");
  1841. sleep(30);
  1842. }
  1843. } while ($activeReloadingCache);
  1844. BiAuditPowiazania::saveToLog("Uruchamiam częściowe odświeżenie cache");
  1845. $this->doReloadCache(); //DUPA testowe wylaczanie
  1846. BiAuditPowiazania::saveToLog("Odświeżono częściowo cache");
  1847. $sqlArr = [
  1848. 'BI_analiza_reloadCache' => 'No',
  1849. 'FILE_STATUS_info' => 'Szukam powiązań',
  1850. ];
  1851. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  1852. $BiAuditPowiazania->run();
  1853. if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  1854. //file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  1855. $sqlArr = ['FILE_STATUS_info' => 'Generuję raporty PDF i HTML'];
  1856. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  1857. //$BiAuditPowiazania->saveXml();
  1858. $BiAuditPowiazania->generatePdfAndHtml();
  1859. file_put_contents($resultFile, json_encode(['result' => 'ok', 'parts' => $BiAuditPowiazania->getPartsCount()]));
  1860. } catch (Exception $e) {
  1861. file_put_contents($resultFile, json_encode(['result' => 'error', 'message' => $e->getMessage()]));
  1862. }
  1863. }
  1864. public function reinstallAction() {
  1865. $this->reinstall();
  1866. die('OK');
  1867. }
  1868. public function reinstall() {
  1869. $sqlList = array();
  1870. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  1871. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  1872. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  1873. SQL;
  1874. $sqlList['ChangeStructure1'] = <<<SQL
  1875. 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';
  1876. SQL;
  1877. $sqlList['ChangeStructure2'] = <<<SQL
  1878. UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
  1879. SQL;
  1880. $sqlList['ChangeStructure3'] = <<<SQL
  1881. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
  1882. SQL;
  1883. $sqlList['ChangeStructure4'] = <<<SQL
  1884. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_depth` `BI_analiza_maxDepth` INT(2) NULL DEFAULT '9';
  1885. SQL;
  1886. $sqlList['ChangeStructure5'] = <<<SQL
  1887. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_minDepth` INT(2) NOT NULL DEFAULT '0' AFTER `FILE_STATUS_info`;
  1888. SQL;
  1889. $sqlList['ChangeStructure6'] = <<<SQL
  1890. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_onlyTargets` ENUM('Y','N') NOT NULL DEFAULT 'Y' AFTER `BI_analiza_maxDepth`;
  1891. SQL;
  1892. $db = DB::getDB();
  1893. if ($db->has_errors()) {
  1894. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  1895. }
  1896. foreach ($sqlList as $sqlName => $sql) {
  1897. $res = $db->query($sql);
  1898. if ($db->has_errors()) {
  1899. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  1900. }
  1901. }
  1902. }
  1903. }
  1904. class BiAuditRelations {
  1905. private $RELATIONS_ID = [];
  1906. private $relations = [
  1907. 'nip' => ['nip'],
  1908. 'regon' => ['regon'],
  1909. 'krs' => ['krs'],
  1910. 'pesel' => ['pesel'],
  1911. ];
  1912. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1913. private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  1914. public function __construct() {
  1915. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  1916. $result = DB::getPDO()->fetchAll($query);
  1917. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  1918. }
  1919. private function getRelationID($name) {
  1920. if (!isset($this->RELATIONS_ID[$name])) {
  1921. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  1922. $newID = DB::getPDO()->fetchValue($query);
  1923. $this->RELATIONS_ID[$name] = $newID;
  1924. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  1925. DB::getPDO()->query($query);
  1926. }
  1927. return $this->RELATIONS_ID[$name];
  1928. }
  1929. private function addToRefTable($fromTable, $toTable, $fromID, $toID) {
  1930. if ($refTable = BiAuditRefTables::getRefTable($fromTable, $toTable, false)) {
  1931. if (!DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = '{$fromID}' and `REMOTE_PRIMARY_KEY` = '{$toID}' and `A_STATUS` != 'DELETED'")) {
  1932. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $fromID, 'REMOTE_PRIMARY_KEY' => $toID, 'A_STATUS' => 'NORMAL', 'TRANSACTION_ID' => '-1']);
  1933. }
  1934. }
  1935. }
  1936. public function findRelations($ID) {
  1937. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  1938. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  1939. $row = $result[0];
  1940. $joins = [];
  1941. $items = '';
  1942. foreach ($this->relations as $name => $columns) {
  1943. $ok = 0;
  1944. $join = [];
  1945. foreach ($columns as $column) {
  1946. $join[] = "t1.{$column} = t2.{$column}";
  1947. if ($row[$column] !== null) $ok++;
  1948. }
  1949. if ($ok / count($columns) > 0.5) {
  1950. $joins[] = "(" . implode(" and ", $join) . ")";
  1951. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  1952. }
  1953. }
  1954. if (!$joins) return false;
  1955. $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 " .
  1956. "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})";
  1957. $result = DB::getPDO()->fetchAll($query);
  1958. foreach ($result as $row) {
  1959. $relationID = 0;
  1960. foreach ($this->relations as $name => $v) {
  1961. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  1962. }
  1963. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  1964. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  1965. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  1966. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  1967. if (!($start2 || $end1)) {
  1968. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
  1969. $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
  1970. $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
  1971. DB::getPDO()->query($query);
  1972. }
  1973. if (!($start1 || $end2)) {
  1974. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
  1975. $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
  1976. $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
  1977. DB::getPDO()->query($query);
  1978. }
  1979. }
  1980. }
  1981. }
  1982. class BiAuditRefTables {
  1983. public static function getRefTable($tableFrom, $tableTo, $returnException = false) {
  1984. static $refTables = [];
  1985. static $tempRefTables = [];
  1986. if (is_array($tableTo)) {
  1987. if (!$tableTo) throw new Exception('BiAuditRefTables::getRefTable - bad parameter $tableTo');
  1988. if (count($tableTo) == 1) return self::getRefTable($tableFrom, reset($tableTo), $returnException);
  1989. $key = implode("__", $tableTo);
  1990. if (!isset($tempRefTables[$tableFrom][$key])) {
  1991. try {
  1992. $_tableFrom = $tableFrom;
  1993. foreach ($tableTo as $_tableTo) {
  1994. $_refTables[] = self::getRefTable($_tableFrom, $_tableTo, true);
  1995. $_tableFrom = $_tableTo;
  1996. }
  1997. $name = "TEMP__#REF_TABLE__" . (count($tempRefTables) + 1);
  1998. $first = reset($_refTables);
  1999. $last = end($_refTables);
  2000. $prev = array_shift($_refTables);
  2001. $query = "create temporary table `{$name}` select `{$first}`.`PRIMARY_KEY`, `{$last}`.`REMOTE_PRIMARY_KEY` from `{$first}`";
  2002. while ($next = array_shift($_refTables)) {
  2003. $query .= " join `{$next}` on `{$prev}`.`REMOTE_PRIMARY_KEY` = `{$next}`.`PRIMARY_KEY`";
  2004. $prev = $next;
  2005. }
  2006. $query .= " group by `{$first}`.`PRIMARY_KEY`, `{$last}`.`REMOTE_PRIMARY_KEY`";
  2007. DB::getPDO()->query($query);
  2008. $tempRefTables[$tableFrom][$key] = $name;
  2009. } catch (Exception $e) {
  2010. if ($returnException) throw new Exception($e->getMessage());
  2011. $tempRefTables[$tableFrom][$key] = false;
  2012. }
  2013. }
  2014. return $tempRefTables[$tableFrom][$key];
  2015. } else {
  2016. if (!isset($refTables[$tableFrom][$tableTo])) {
  2017. try {
  2018. $refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
  2019. } catch (Exception $e) {
  2020. if ($returnException) throw new Exception($e->getMessage());
  2021. $refTables[$tableFrom][$tableTo] = false;
  2022. }
  2023. }
  2024. return $refTables[$tableFrom][$tableTo];
  2025. }
  2026. }
  2027. public static function getRefTables($tableFrom) {
  2028. static $refTables = [];
  2029. if (!isset($refTables[$tableFrom])) {
  2030. $namespace = "default_db/{$tableFrom}/{$tableFrom}";
  2031. try {
  2032. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  2033. if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
  2034. $fields = $item['field'];
  2035. $_refTables = [];
  2036. foreach ($fields as $field) {
  2037. list($type, $child) = explode(":", $field['xsdType'], 2);
  2038. if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) {
  2039. try {
  2040. $_refTable = ACL::getRefTable($namespace, $child);
  2041. $_refTables[] = $_refTable;
  2042. } catch (Exception $e) {
  2043. }
  2044. }
  2045. }
  2046. $refTables[$tableFrom] = $_refTables;
  2047. } catch (Exception $e) {
  2048. $refTables[$tableFrom] = [];
  2049. }
  2050. }
  2051. return $refTables[$tableFrom];
  2052. }
  2053. }
  2054. class BiAuditPowiazania {
  2055. private $minDepth;
  2056. private $maxDepth, $origMaxDepth;
  2057. private $onlyTargets;
  2058. private $ID;
  2059. private $nodes = [];
  2060. private $endNodes;
  2061. private $path = [];
  2062. private $results = [];
  2063. private $items_results = [];
  2064. private $relations = [];
  2065. private $srcTables = ['BI_audit_ENERGA_PRACOWNICY', ['BI_audit_POWIAZANIA_OD', 'BI_audit_POWIAZANIA_OBIEKTY']];
  2066. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person', ['BI_audit_POWIAZANIA_DO', 'BI_audit_POWIAZANIA_OBIEKTY']];
  2067. private $step = 0;
  2068. private $tasksDirLocation;
  2069. private $progressFile;
  2070. private $progress = [
  2071. 'summary' => [
  2072. 'count' => 0,
  2073. 'message' => 'Inicjacja',
  2074. 'ts' => null,
  2075. 'step' => 'initialize',
  2076. 'reportsCount' => 0,
  2077. 'reportsCreated' => 0,
  2078. ],
  2079. 'details' => [],
  2080. ];
  2081. private $lastProgress = 0;
  2082. private $lastResults = 0;
  2083. private $startTimestamp = null;
  2084. private $lastTimestamp = null;
  2085. private $lowProgressCount = 0;
  2086. private $count, $i;
  2087. private $splittedResults = [];
  2088. private $maxResults = 1000000;
  2089. private $fidRow = [];
  2090. private $itemID = 0;
  2091. private $reverseSearch = false;
  2092. private $query = "";
  2093. private static function generateJson($type, $data) {
  2094. return json_encode(['ts' => microtime(true), 'type' => $type, 'data' => $data]);
  2095. }
  2096. public static function saveToLog($message) {
  2097. $messageJson = self::generateJson('message', ['message' => $message]);
  2098. echo $messageJson . "\n";
  2099. }
  2100. private static function exec($cmd) {
  2101. $path = 'export PATH=$PATH:/usr/sbin;';
  2102. $cmd = "{$path} {$cmd}";
  2103. echo "CMD :: {$cmd}\n";
  2104. shell_exec($cmd);
  2105. }
  2106. private function saveProgress($args = []) {
  2107. $timestamp = microtime(true);
  2108. if (isset($args['progress']) && $this->i) {
  2109. $elapsed = $timestamp - $this->startTimestamp;
  2110. if ($args['progress']) {
  2111. $estimated = ($elapsed * (1 - $args['progress'])) / $args['progress'];
  2112. } else $estimated = "N/A";
  2113. $this->lastProgress = $args['progress'];
  2114. $this->lastTimestamp = $timestamp;
  2115. $progressJson = self::generateJson('progress', ['progress' => $args['progress'], 'item' => $this->i . "/" . $this->count, 'results' => count($this->results), 'step' => $this->step, 'elapsed' => $elapsed, 'estimated' => $estimated]);
  2116. echo $progressJson . "\n";
  2117. $this->progress['details'][$this->itemID] = ['progress' => $args['progress'], 'results' => (count($this->results) - $this->lastResults), 'elapsed' => $elapsed, 'estimated' => $estimated];
  2118. }
  2119. if (isset($args['message'])) $this->progress['summary']['message'] = $args['message'];
  2120. if (isset($args['step'])) $this->progress['summary']['step'] = $args['step'];
  2121. if (isset($args['reportsCreated'])) $this->progress['summary']['reportsCreated'] = round($this->progress['summary']['reportsCreated'] + $args['reportsCreated'], 2);
  2122. $this->progress['summary']['ts'] = $timestamp;
  2123. file_put_contents($this->progressFile, json_encode($this->progress));
  2124. }
  2125. private static function throwException($message) {
  2126. self::saveToLog($message);
  2127. throw new Exception($message);
  2128. }
  2129. public function __construct($ID = 0, $tasksDirLocation = null) {
  2130. if (!$ID) self::throwException("Wrong ID parameter");
  2131. if (!$tasksDirLocation) self::throwException("Wrong directory of tasks location");
  2132. $this->ID = $ID;
  2133. $this->tasksDirLocation = $tasksDirLocation;
  2134. $this->progressFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.progress";
  2135. $this->saveProgress();
  2136. }
  2137. public function run() {
  2138. $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')";
  2139. $result = DB::getPDO()->fetchAll($query);
  2140. if (!$result) self::throwException("Błąd danych");
  2141. if ($this->loadResults()) {
  2142. $this->splitResults();
  2143. return;
  2144. }
  2145. self::saveToLog("Wczytuję parametry wyszukiwania powiązań");
  2146. $this->minDepth = (int) $result[0]['BI_analiza_minDepth'];
  2147. $this->maxDepth = (int) $result[0]['BI_analiza_maxDepth'];
  2148. $this->onlyTargets = ($result[0]['BI_analiza_onlyTargets'] != 'N');
  2149. if (!$this->minDepth) $this->minDepth = 1;
  2150. if (!$this->maxDepth) self::throwException("Błąd danych - nieokreślono maksymalnej głębokości analizy");
  2151. if ($this->minDepth > $this->maxDepth) self::throwException("Wartość minimalnej głębokości analizy jest większa od wartości maksymalnej głębokości analizy");
  2152. $subQueries = [];
  2153. $resultDest = [];
  2154. foreach ($this->destTables as $destTable) {
  2155. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $destTable)) {
  2156. $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}'";
  2157. }
  2158. }
  2159. if ($subQueries) {
  2160. $query = implode(" union ", $subQueries) . " order by `ID` asc";
  2161. $resultDest = DB::getPDO()->fetchAll($query);
  2162. }
  2163. if ((!$resultDest) && $this->onlyTargets) self::throwException("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  2164. $subQueries = [];
  2165. $resultSrc = [];
  2166. foreach ($this->srcTables as $srcTable) {
  2167. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $srcTable)) {
  2168. $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}'";
  2169. }
  2170. }
  2171. if ($subQueries) {
  2172. $query = implode(" union ", $subQueries) . " order by `ID` asc";
  2173. $resultSrc = DB::getPDO()->fetchAll($query);
  2174. }
  2175. if (!$resultSrc) self::throwException("Błąd danych - nie zdefinowano żadnego początkowego obiektu");
  2176. if (count($resultSrc) <= count($resultDest) || (!$this->onlyTargets)) {
  2177. $result = $resultSrc;
  2178. $this->endNodes = array_map('reset', $resultDest);
  2179. $this->reverseSearch = false;
  2180. $this->query = "select ref.ID2 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID1";
  2181. } else {
  2182. $result = $resultDest;
  2183. $this->endNodes = array_map('reset', $resultSrc);
  2184. $this->reverseSearch = true;
  2185. $this->query = "select ref.ID1 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID2";
  2186. self::saveToLog("Docelowych obiektów jest mniej, niż początkowych - włączono mechanizm odwrotnego przeszukiwania");
  2187. }
  2188. self::saveToLog("Rozpoczynam wyszukiwanie powiązań");
  2189. $this->count = count($result);
  2190. $this->progress['summary']['count'] = $this->count;
  2191. $this->origMaxDepth = $this->maxDepth;
  2192. $this->saveProgress(['step' => 'relations']);
  2193. try {
  2194. foreach ($result as $i => $row) {
  2195. $this->i = $i + 1;
  2196. $this->itemID = DB::getPDO()->fetchValue("select `REMOTE_ID` from `BI_audit_ALL` where `ID` = :ID", [":ID" => $row['ID']]);
  2197. $this->startTimestamp = microtime(true);
  2198. $this->lastProgress = 0;
  2199. $this->saveProgress(['progress' => 0, 'message' => "Wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
  2200. if ($this->maxDepth != $this->origMaxDepth) {
  2201. $this->maxDepth = $this->origMaxDepth;
  2202. self::saveToLog("Przywrócono oryginalną maksymalną głębokość przeszukiwania ({$this->origMaxDepth})");
  2203. }
  2204. $this->findPowiazania($row['ID']);
  2205. $this->saveProgress(['progress' => 1, 'message' => "Zakończono wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
  2206. $this->lastResults = count($this->results);
  2207. }
  2208. } catch (Exception $e) {
  2209. if ($this->i < $this->count) {
  2210. $this->startTimestamp = microtime(true);
  2211. $this->lastProgress = 0;
  2212. $this->lastResults = count($this->results);
  2213. while (++$this->i <= $this->count) $this->saveProgress(['progress' => 0]);
  2214. }
  2215. if ($message = $e->getMessage()) self::saveToLog("Wystąpił błąd podczas wyszukiwania powiązań - {$message}");
  2216. }
  2217. $this->nodes = [];
  2218. self::saveToLog("Zakończono wyszukiwanie powiązań");
  2219. $this->sortResults();
  2220. $this->saveResults();
  2221. //$this->saveToDb(); 2017-12-14 - przerobiono na zapisywanie danych do bazy w locie
  2222. $this->splitResults();
  2223. }
  2224. private static function reversePath($path) {
  2225. $arr = array_reverse($path, true);
  2226. $keys = array_keys($arr);
  2227. array_unshift($arr, array_pop($arr));
  2228. return array_combine($keys, $arr);
  2229. }
  2230. private function addResult($progress) {
  2231. if (count($this->results) == $this->maxResults) {
  2232. $message = "Przerwano wyszukiwanie powiązań - osiągnięto maksymalną liczbę wyników {$this->maxResults}";
  2233. self::saveToLog($message);
  2234. $this->saveProgress(['progress' => $progress, 'message' => $message]);
  2235. throw new Exception('');
  2236. }
  2237. if ($this->reverseSearch) $path = self::reversePath($this->path);
  2238. else $path = $this->path;
  2239. $this->results[] = $path;
  2240. $this->saveToDb($path);
  2241. }
  2242. public function findPowiazania($ID, $progress = 0, $steps = 1, $relation = "") {
  2243. if (((++$this->step) % 1000000) == 0) {
  2244. $progressDiff = $progress - $this->lastProgress;
  2245. if ($progressDiff < 0.00005) {
  2246. $this->lowProgressCount++;
  2247. if ($this->lowProgressCount == 10) {
  2248. $this->maxDepth--;
  2249. self::saveToLog("Zbyt dużo rekurencji, zmniejszono maksymalną głębokość poszukiwań do {$this->maxDepth} dla bieżącego obiektu");
  2250. }
  2251. } else $this->lowProgressCount = 0;
  2252. }
  2253. if ((($this->step) % 100000) == 0) {
  2254. $this->saveProgress(['progress' => $progress]);
  2255. }
  2256. if ((($this->step) % 10000) == 0) {
  2257. if (memory_get_usage(true) > 3000000000) {
  2258. $this->nodes = [];
  2259. self::saveToLog("Oczyszczam podręczny cache - zajmuje zbyt dużo pamięci");
  2260. }
  2261. }
  2262. if (isset($this->path[$ID])) return false;
  2263. $this->path[$ID] = $relation;
  2264. if (!$relation) $relation = 0;
  2265. if (in_array($ID, $this->endNodes)) {
  2266. if (count($this->path) > $this->minDepth) $this->addResult($progress);
  2267. array_pop($this->path);
  2268. return;
  2269. }
  2270. if (count($this->path) > $this->maxDepth) {
  2271. if (!$this->onlyTargets) $this->addResult($progress);
  2272. array_pop($this->path);
  2273. return;
  2274. }
  2275. if (!isset($this->nodes[$ID][$relation])) {
  2276. $where = $relation ? "and ({$relation} & ref.RELATION_ID) = 0" : "";
  2277. $query = "{$this->query} = {$ID} {$where}";
  2278. $this->nodes[$ID][$relation] = DB::getPDO()->fetchAll($query);
  2279. }
  2280. $nodes = array_values(array_filter($this->nodes[$ID][$relation], function ($node) {
  2281. if (isset($this->path[$node['ID']])) return false;
  2282. return true;
  2283. }));
  2284. $count = count($nodes);
  2285. foreach ($nodes as $i => $node) $this->findPowiazania($node['ID'], ($progress + ($i / ($count * $steps))), ($count * $steps), $node['RELATION_ID']);
  2286. array_pop($this->path);
  2287. }
  2288. private function sortResults() {
  2289. if (!$this->results) return;
  2290. uasort($this->results, function ($a, $b) {
  2291. $ca = count($a);
  2292. $cb = count($b);
  2293. $c = min($ca, $cb);
  2294. $ka = array_keys($a);
  2295. $kb = array_keys($b);
  2296. for ($i = 0; $i < $c; $i++) {
  2297. if ($ka[$i] < $kb[$i]) return -1;
  2298. if ($ka[$i] > $kb[$i]) return 1;
  2299. }
  2300. if ($ca < $cb) return -1;
  2301. if ($ca > $cb) return 1;
  2302. return 0;
  2303. });
  2304. }
  2305. private function saveResults() {
  2306. self::saveToLog("Zapisuję wyliczone dane do pliku");
  2307. if (!$this->results) {
  2308. self::saveToLog("Brak wyliczonych danych - niczego nie zapisaono");
  2309. return false;
  2310. }
  2311. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  2312. $data = base64_encode(gzcompress(json_encode(['results' => $this->results, 'fidRow' => $this->fidRow])));
  2313. file_put_contents($dataFile, $data);
  2314. self::saveToLog("Zapisano wyliczone dane do pliku");
  2315. return true;
  2316. }
  2317. private function loadResults() {
  2318. self::saveToLog("Próbuję wczytać wcześniej wyliczone dane");
  2319. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  2320. if (!file_exists($dataFile)) {
  2321. self::saveToLog("Nie znaleziono pliku z wyliczonymi danymi");
  2322. return false;
  2323. }
  2324. $data = file_get_contents($dataFile);
  2325. $results = @json_decode(gzuncompress(base64_decode($data)), true);
  2326. if (!$results) {
  2327. self::saveToLog("Wystąpił błąd wczytywania wcześniej wyliczonych danych");
  2328. return false;
  2329. }
  2330. if (isset($results['results'])) {
  2331. $this->results = $results['results'];
  2332. if (isset($results['fidRow'])) $this->fidRow = $results['fidRow'];
  2333. } else $this->results = $results;
  2334. self::saveToLog("Wczytano wcześniej wyliczone dane");
  2335. return true;
  2336. }
  2337. private function relationName($ID) {
  2338. if (!$ID) return '';
  2339. if (!isset($this->relations[$ID])) {
  2340. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  2341. $result = DB::getPDO()->fetchAll($query);
  2342. $rels = array_map('reset', $result);
  2343. $this->relations[$ID] = implode(", ", $rels);
  2344. }
  2345. return $this->relations[$ID];
  2346. }
  2347. private function splitResults() {
  2348. $MAX = 1000;
  2349. $countBySource = [];
  2350. $resultsKeys = [];
  2351. foreach ($this->results as $resultKey => $result) {
  2352. $_keys = array_keys($result);
  2353. $countBySource[reset($_keys)][] = $resultKey;
  2354. }
  2355. foreach ($countBySource as $resultKeys) {
  2356. if (count($resultKeys) > $MAX) {
  2357. $countByDest = [];
  2358. foreach ($resultKeys as $resultKey) {
  2359. $_keys = array_keys($this->results[$resultKey]);
  2360. $countByDest[end($_keys)][] = $resultKey;
  2361. }
  2362. foreach ($countByDest as $resultKeys2) $resultsKeys = array_merge($resultsKeys, array_chunk($resultKeys2, $MAX));
  2363. } else $resultsKeys[] = $resultKeys;
  2364. }
  2365. $results = [];
  2366. while ($resultsKeys) {
  2367. $resultKeys = array_shift($resultsKeys);
  2368. while ($next = current($resultsKeys)) {
  2369. if (count($resultKeys) + count($next) <= $MAX) {
  2370. $resultKeys = array_merge($resultKeys, $next);
  2371. unset($resultsKeys[key($resultsKeys)]);
  2372. } else break; //next($resultsKeys);
  2373. }
  2374. $_results = [];
  2375. foreach ($resultKeys as $key) $_results[$key] = $this->results[$key];
  2376. $results[] = $_results;
  2377. // $results[] = array_map(function ($resultKey) {return $this->results[$resultKey];}, $resultKeys);
  2378. }
  2379. $this->splittedResults = $results;
  2380. $this->progress['summary']['reportsCount'] = count($results);
  2381. }
  2382. public function getPartsCount() {
  2383. return count($this->splittedResults);
  2384. }
  2385. private function generateItemsResults($resultsPart = null) {
  2386. if ($resultsPart === null) self::saveToLog("Generuję dane na potrzeby utworzenia pojedynczego pliku XML");
  2387. else {
  2388. self::saveToLog("Generuję dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  2389. if ($resultsPart >= $this->getPartsCount()) throw new Exception("generateItemsResults() error - bad part number");
  2390. }
  2391. $xmlTask = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  2392. $xmlRow = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  2393. $xmlObject = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object";
  2394. $items_kontrahenci = [];
  2395. $items_kw_person = [];
  2396. $kontrahenci = [];
  2397. $kw_person = [];
  2398. $_items_results = [];
  2399. $refUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  2400. $refKwRequestedToKwRequestedPerson = BiAuditRefTables::getRefTable('BI_audit_KW_requested', 'BI_audit_KW_requested_person', true);
  2401. $this->items_results[$resultsPart] = [];
  2402. $this->items_results[$resultsPart]['@attributes'] = ['xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd'];
  2403. $this->items_results[$resultsPart][$xmlTask]['@attributes'] = ['fid' => "{$xmlTask}.{$this->ID}"];
  2404. if ($resultsPart === null) {
  2405. $results = $this->results;
  2406. } else {
  2407. $results = (!empty($this->splittedResults[$resultsPart])) ? $this->splittedResults[$resultsPart] : [];
  2408. $this->items_results[$resultsPart][$xmlTask]['@attributes']['system_cache__dita:part'] = ($resultsPart + 1);
  2409. }
  2410. foreach ($results as $key => $result) {
  2411. if ($this->fidRow) $item_results = ['@attributes' => ['fid' => "{$xmlRow}.{$this->fidRow[$key]['fid']}"]];
  2412. foreach ($result as $ID => $rel) {
  2413. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  2414. $row = DB::getPDO()->fetchFirst($query);
  2415. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  2416. $obj = DB::fetch(DB::query($query));
  2417. $item_result = [];
  2418. if ($this->fidRow) {
  2419. $item_result['@attributes'] = ['fid' => "{$xmlObject}.{$this->fidRow[$key]['obj'][$ID]}"];
  2420. }
  2421. $item_result[$row['REMOTE_TABLE']] = array_merge(['@attributes' => ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"]], (array) $obj);
  2422. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_operational_raport_note', $row['REMOTE_TABLE'], false)) {
  2423. $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']}'";
  2424. if ($notes = DB::getPDO()->fetchAll($query)) $item_result[$row['REMOTE_TABLE']]['BI_audit_operational_raport_note'] = $notes;
  2425. }
  2426. if ($refTable = BiAuditRefTables::getRefTable($row['REMOTE_TABLE'], 'BI_audit_taxpayer', false)) {
  2427. $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']}'";
  2428. if ($taxpayer = DB::getPDO()->fetchFirst($query)) {
  2429. $item_result[$row['REMOTE_TABLE']]['BI_audit_taxpayer'] = array_merge(['@attributes' => ['fid' => "BI_audit_taxpayer.{$taxpayer['ID']}"]], $taxpayer);
  2430. }
  2431. }
  2432. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  2433. $item_results[$xmlObject][] = $item_result;
  2434. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  2435. $kontrahenci[] = $row['REMOTE_ID'];
  2436. $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']}'";
  2437. $res = DB::query($query);
  2438. if (mysql_num_rows($res)) {
  2439. $umowy = [];
  2440. while ($obj = DB::fetch($res)) {
  2441. $umowa = (array) $obj;
  2442. $umowa = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_RUM_UMOWY.{$umowa['ID']}"]], $umowa);
  2443. $umowy[] = $umowa;
  2444. }
  2445. $item_kontrahenci['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
  2446. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  2447. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  2448. $items_kontrahenci[] = $item_kontrahenci;
  2449. }
  2450. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  2451. $kw_person[] = $row['REMOTE_ID'];
  2452. $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']}'";
  2453. $res = DB::query($query);
  2454. if (mysql_num_rows($res)) {
  2455. $kws = [];
  2456. while ($obj = DB::fetch($res)) {
  2457. $kw = (array) $obj;
  2458. $kw = array_merge(['@attributes' => ['fid' => "BI_audit_KW_requested.{$kw['ID']}"]], $kw);
  2459. $kws[] = $kw;
  2460. }
  2461. $item_kw_person['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
  2462. $item_kw_person['ID'] = $row['REMOTE_ID'];
  2463. $item_kw_person['BI_audit_KW_requested'] = $kws;
  2464. $items_kw_person[] = $item_kw_person;
  2465. }
  2466. }
  2467. }
  2468. $this->items_results[$resultsPart][$xmlTask][$xmlRow][] = $item_results;
  2469. }
  2470. $this->items_results[$resultsPart][$xmlTask]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  2471. $this->items_results[$resultsPart][$xmlTask]['BI_audit_KW_requested_person'] = $items_kw_person;
  2472. self::saveToLog("Wygenerowano dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  2473. }
  2474. private function saveToDb($result = null, $key = null) {
  2475. if ($result === null) {
  2476. self::saveToLog("Zapisuję wyliczone dane do bazy");
  2477. if (!$this->results) {
  2478. self::saveToLog("Brak wyliczonych danych - nie zapisaono niczego do bazy");
  2479. return null;
  2480. }
  2481. foreach ($this->results as $key => $result) $this->saveToDb($result, $key);
  2482. self::saveToLog("Zapisano wyliczone dane do bazy");
  2483. } else {
  2484. if ($key === null) {
  2485. end($this->results);
  2486. $key = key($this->results);
  2487. }
  2488. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  2489. $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
  2490. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  2491. $fidObj = [];
  2492. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  2493. foreach ($result as $ID => $rel) {
  2494. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  2495. $object = DB::getPDO()->fetchFirst($query);
  2496. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relationName($rel)]);
  2497. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  2498. $ref = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', $object['REMOTE_TABLE'], true);
  2499. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  2500. $fidObj[$ID] = $idPowiazaniaRowObject;
  2501. }
  2502. $this->fidRow[$key] = [
  2503. 'fid' => $IdPowiazaniaRow,
  2504. 'obj' => $fidObj,
  2505. ];
  2506. }
  2507. }
  2508. public function saveXml($resultsPart = null) {
  2509. if ($this->getPartsCount()) {
  2510. if ($resultsPart === null) {
  2511. self::saveToLog("Generuję pliki XML (liczba plików do wygenerowania: {$this->getPartsCount()})");
  2512. for ($i =0; $i < $this->getPartsCount(); $i++) {
  2513. $partNo = str_pad($i + 1, 6, '0', STR_PAD_LEFT);
  2514. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  2515. file_put_contents($xmlFile, $this->asXml($i));
  2516. }
  2517. self::saveToLog("Zakończono generowanie plików XML");
  2518. } else {
  2519. if ($resultsPart >= $this->getPartsCount()) {
  2520. self::saveToLog("saveXml() error - bad result number");
  2521. return;
  2522. }
  2523. $partNo = str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  2524. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  2525. file_put_contents($xmlFile, $this->asXml($resultsPart));
  2526. }
  2527. } else {
  2528. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
  2529. file_put_contents($xmlFile, $this->asXml());
  2530. }
  2531. }
  2532. public function asXml($resultsPart = null) {
  2533. self::saveToLog("Generuję plik XML ({$resultsPart})");
  2534. if (!$this->results) {
  2535. self::saveToLog("Brak wyników (#1), nie wygenerowano pliku XML ({$resultsPart})");
  2536. return null;
  2537. }
  2538. if (!isset($this->items_results[$resultsPart])) $this->generateItemsResults($resultsPart);
  2539. if (!isset($this->items_results[$resultsPart])) {
  2540. self::saveToLog("Brak wyników (#2), nie wygenerowano pliku XML ({$resultsPart})");
  2541. return null;
  2542. }
  2543. $xmlRoot = "RelatedFeatureRoot";
  2544. $return = V::arrayToXML($this->items_results[$resultsPart], true, $xmlRoot);
  2545. self::saveToLog("Wygenerowano plik XML ({$resultsPart})");
  2546. return $return;
  2547. }
  2548. public function asArray($resultsPart = null, $subArray = null) {
  2549. if (!$this->results) return null;
  2550. if (!$this->items_results[$resultsPart]) $this->generateItemsResults($resultsPart);
  2551. if (!$this->items_results[$resultsPart]) return null;
  2552. if ($subArray) {
  2553. if (isset($this->items_results[$resultsPart][$subArray])) return $this->items_results[$subArray];
  2554. else return [];
  2555. } else return $this->items_results[$resultsPart];
  2556. }
  2557. public function powiazaniaFound() {
  2558. if ($this->results) return true;
  2559. else return false;
  2560. }
  2561. public function generatePdfAndHtml() {
  2562. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  2563. if (!file_exists($antDir)) mkdir($antDir, 0770, true);
  2564. if (!is_dir($antDir)) {
  2565. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików PDF i HTML";
  2566. self::saveToLog("Nie wygenerowano plików PDF oraz HTML - problem z utworzeniem katalogu dla ant ({$resultsPart})");
  2567. $this->saveProgress(['reportsCreated' => 1]);
  2568. return;
  2569. }
  2570. $this->saveProgress(['step' => 'reports']);
  2571. if ($this->getPartsCount()) {
  2572. self::saveToLog("Generuję raporty w plikach PDF oraz HTML (liczba raportów do wygenerowania: {$this->getPartsCount()})");
  2573. for ($i =0; $i < $this->getPartsCount(); $i++) $this->_generatePdfAndHtml($i);
  2574. self::saveToLog("Zakończono generowanie raportów w plikach PDF oraz HTML");
  2575. } else $this->_generatePdfAndHtml();
  2576. }
  2577. private function _generatePdfAndHtml($resultsPart = null) {
  2578. $id_part = $resultsPart === null ? $this->ID : $this->ID . "_" . str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  2579. self::saveToLog("Generuję raport w pliku PDF oraz HTML ({$resultsPart})");
  2580. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.xml";
  2581. $pdfDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.pdf";
  2582. $htmlDestDir = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.html";
  2583. $htmlZipDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.zip";
  2584. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  2585. $antXmlFilename = "relations-{$id_part}.out_task.dita.final_with_RelatedFeatureLoop.xml";
  2586. $antXmlFile = $antDir . "/" . $antXmlFilename;
  2587. $ditamapFile = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}/relations-{$id_part}.ditamap";
  2588. $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";
  2589. $htmlDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}/html";
  2590. if (!file_exists($xmlFile)) $this->saveXml($resultsPart);
  2591. if (!file_exists($xmlFile)) {
  2592. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików XML, PDF i HTML";
  2593. self::saveToLog("Nie wygenerowano plików XML, PDF oraz HTML - problem z wygenerowaniem pliku XML ({$resultsPart})");
  2594. $this->saveProgress(['reportsCreated' => 1]);
  2595. return;
  2596. }
  2597. $this->saveProgress(['reportsCreated' => 0.05]);
  2598. copy($xmlFile, $antXmlFile);
  2599. self::saveToLog("Generuję plik przejściowy do wygenerowania plików PDF i HTML ({$resultsPart})");
  2600. 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}");
  2601. if (file_exists($ditamapFile))
  2602. {
  2603. self::saveToLog("Wygenerowano plik przejściowy");
  2604. $this->saveProgress(['reportsCreated' => 0.15]);
  2605. } else {
  2606. self::saveToLog("Nie udało się wygenerować pliku przejściowego, przerywm");
  2607. $this->saveProgress(['reportsCreated' => 1]);
  2608. return;
  2609. }
  2610. self::saveToLog("Generuję plik PDF ({$resultsPart})");
  2611. 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");
  2612. if (file_exists($pdfFile)) {
  2613. rename($pdfFile, $pdfDestFile);
  2614. self::saveToLog("Wygenerowano plik PDF ({$resultsPart})");
  2615. } else self::saveToLog("Nie udało się wygenerować pliku PDF ({$resultsPart})");
  2616. $this->saveProgress(['reportsCreated' => 0.45]);
  2617. self::saveToLog("Generuję pliki HTML ({$resultsPart})");
  2618. 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");
  2619. if (file_exists($htmlDir) && is_dir($htmlDir)) {
  2620. 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");
  2621. if (file_exists($htmlDestDir)) self::exec("rm -rf \"{$htmlDestDir}\"");
  2622. self::exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
  2623. self::saveToLog("Wygenerowano pliki HTML ({$resultsPart})");
  2624. } else self::saveToLog("Nie udało się wygenerować plików HTML {$resultsPart})");
  2625. $this->saveProgress(['reportsCreated' => 0.35]);
  2626. }
  2627. }