BiAuditGenerate.php 106 KB

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