BiAuditGenerate.php 97 KB

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