BiAuditGenerate.php 108 KB

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