BiAuditGenerate.php 106 KB

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