BiAuditGenerate.php 87 KB

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