BiAuditGenerate.php 116 KB

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