BiAuditGenerate.php 107 KB

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