BiAuditGenerate.php 103 KB

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