BiAuditGenerate.php 78 KB

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