BiAuditGenerate.php 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798
  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. 'source',
  1159. ],
  1160. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1161. 'kodPocztowy',
  1162. 'miejscowosc',
  1163. 'ulica',
  1164. 'nrBudynku',
  1165. 'nrLokalu',
  1166. ],
  1167. ];
  1168. $query = "select * from `BI_audit_ENERGA_PRACOWNICY_import` where `importResult` = 'none'";
  1169. $pracownicy = DB::getPDO()->query($query);
  1170. while ($pracownik = $pracownicy->fetch()) {
  1171. $ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `pesel` = '{$pracownik['pesel']}'");
  1172. $sqlArr = [];
  1173. foreach ($fields['BI_audit_ENERGA_PRACOWNICY'] as $field) $sqlArr[$field] = trim($pracownik[$field]);
  1174. if ($ID_pracownik) DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY', 'ID', $ID, $sqlArr);
  1175. else $ID_pracownik = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', $sqlArr);
  1176. $sqlArr = [];
  1177. foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $field) {
  1178. $sqlArr[$field] = trim($pracownik[$field]);
  1179. if (!$sqlArr[$field]) unset($sqlArr[$field]);
  1180. }
  1181. if (!$sqlArr) break;
  1182. $sql = [];
  1183. // foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $field) {
  1184. // if (isset($sqlArr[$field])) $sql[] = "`{$field}` = " . DUPA;
  1185. // }
  1186. }
  1187. }
  1188. private static function reloadCache_parseUmowy($full = false) {
  1189. $fields = [
  1190. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1191. 'Tytul_dokumentu',
  1192. 'Pelna_nazwa_kontrahenta',
  1193. 'NIP',
  1194. 'REGON',
  1195. 'KRS',
  1196. 'Kraj',
  1197. 'Kod_pocztowy',
  1198. 'Miejscowosc',
  1199. 'Ulica',
  1200. 'Numer_budynku',
  1201. 'Numer_mieszkania_lokalu',
  1202. 'TERYT_SYM',
  1203. 'TERYT_SYM_UL',
  1204. ],
  1205. 'BI_audit_KRS' => [
  1206. '"Zaimportowanoz KRS na podstawie umowy"',
  1207. 'nazwa',
  1208. 'nip',
  1209. 'regon',
  1210. 'krs',
  1211. 'A_kraj',
  1212. 'A_kod',
  1213. 'A_miejscowosc',
  1214. 'A_ulica',
  1215. 'A_nrDomu',
  1216. 'A_nrLokalu',
  1217. 'TERYT_SYM',
  1218. 'TERYT_SYM_UL',
  1219. ],
  1220. 'BI_audit_CEIDG' => [
  1221. '"Zaimportowano z CEiDG na podstawie umowy"',
  1222. 'firma',
  1223. 'nip',
  1224. 'regon',
  1225. 'null',
  1226. 'kraj',
  1227. 'kodPocztowy',
  1228. 'miejscowosc',
  1229. 'ulica',
  1230. 'budynek',
  1231. 'lokal',
  1232. 'TERYT_SYM',
  1233. 'TERYT_SYM_UL',
  1234. ],
  1235. ];
  1236. $refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  1237. if ($full) {
  1238. DB::getPDO()->query("truncate table `{$refTable}`");
  1239. DB::getPDO()->query("update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
  1240. }
  1241. $query = <<<SQL
  1242. update `BI_audit_ENERGA_RUM_UMOWY` set `Wartosc` = replace(
  1243. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_`,
  1244. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_`,
  1245. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_`,
  1246. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_`,
  1247. if(`Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_`, 0))))),
  1248. ',', '.') where `A_STATUS` = 'WAITING';
  1249. SQL;
  1250. DB::getPDO()->query($query);
  1251. $query = "select `ID`, `Strony_umowy` from `BI_audit_ENERGA_RUM_UMOWY` where `A_STATUS` = 'WAITING'";
  1252. $result = DB::getPDO()->fetchAll($query);
  1253. foreach ($result as $row) {
  1254. $ID = $row['ID'];
  1255. $strony = array_map('trim', explode("|", $row['Strony_umowy']));
  1256. $K_IDs = [];
  1257. foreach ($strony as $item) {
  1258. $strona = array_map('trim', explode(";", $item));
  1259. $nr = null;
  1260. if (count($strona) == 3) $i = 1;//$nr = $strona[1];
  1261. elseif (count($strona) == 4) $i = 2;//$nr = $strona[2];
  1262. elseif (count($strona) >= 5 && count($strona) <= 6) $i = 3;//$nr = $strona[3];
  1263. else $i = null;
  1264. if ($i) $nr = $strona[$i];
  1265. $notFound = false;
  1266. if (is_numeric($nr)) {
  1267. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Numer_kontrahenta = '{$nr}'";
  1268. if ($K_ID = DB::getPDO()->fetchValue($query)) {
  1269. $K_IDs[] = $K_ID;
  1270. } else {
  1271. $nazwa = $strona[$i+1];
  1272. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Pelna_nazwa_kontrahenta = '" . addslashes($nazwa) . "'";
  1273. if ($result2 = DB::getPDO()->fetchAll($query)) {
  1274. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1275. } else $notFound = true;
  1276. }
  1277. } else $notFound = true;
  1278. if ($notFound) {
  1279. list($nip, $regon) = self::parseNipRegon($item);
  1280. if ($nip || $regon) {
  1281. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where NIP = '{$nip}' or REGON = '{$regon}'";
  1282. if ($result2 = DB::getPDO()->fetchall($query)) {
  1283. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1284. } else {
  1285. $query = "select ID from BI_audit_KRS where nip = '{$nip}' or regon = '{$regon}'";
  1286. if ($result2 = DB::getPDO()->fetchall($query)) {
  1287. foreach ($result2 as $item) {
  1288. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1289. " select " . implode(', ', $fields['BI_audit_KRS']) . " from BI_audit_KRS where ID = '{$item['ID']}'";
  1290. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1291. }
  1292. } else {
  1293. $query = "select ID from BI_audit_CEIDG where nip = '{$nip}' or regon = '{$regon}'";
  1294. if ($result2 = DB::getPDO()->fetchall($query)) {
  1295. foreach ($result2 as $item) {
  1296. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1297. " select " . implode(', ', $fields['BI_audit_CEIDG']) .
  1298. " from BI_audit_CEIDG where ID = '{$item['ID']}'";
  1299. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1300. }
  1301. }
  1302. }
  1303. }
  1304. }
  1305. }
  1306. }
  1307. foreach ($K_IDs as $K_ID) {
  1308. if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
  1309. DB::getPDO()->query("insert into `{$refTable}` (PRIMARY_KEY, REMOTE_PRIMARY_KEY) values ({$ID}, {$K_ID})");
  1310. }
  1311. }
  1312. DB::getPDO()->update('BI_audit_ENERGA_RUM_UMOWY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
  1313. }
  1314. $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";
  1315. $result = DB::getPDO()->fetchAll($query);
  1316. foreach ($result as $row) {
  1317. $query = "select nip, regon, krs from BI_audit_KRS where nip = '{$row['NIP']}' or regon = '{$row['REGON']}' or krs = '{$row['KRS']}'";
  1318. if ($items = DB::getPDO()->fetchAll($query)) {
  1319. list($nip, $regon, $krs) = [$items[0]["nip"], $items[0]["regon"], $items[0]["krs"]];
  1320. if (count($items) > 1) {
  1321. for ($i = 1; $i < count($items); $i++) {
  1322. if ($nip != $items[$i]["nip"]) $nip = null;
  1323. if ($regon != $items[$i]["regon"]) $regon = null;
  1324. if ($krs != $items[$i]["krs"]) $krs = null;
  1325. }
  1326. }
  1327. $set = [];
  1328. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  1329. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  1330. if ($krs && $krs != $row['KRS']) $set[] = "KRS = '{$krs}'";
  1331. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row['ID']}'");
  1332. }
  1333. }
  1334. $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";
  1335. $result = DB::getPDO()->fetchAll($query);
  1336. foreach ($result as $row) {
  1337. $query = "select nip, regon from BI_audit_CEIDG where nip = '{$row['NIP']}' or regon = '{$row['REGON']}'";
  1338. if ($items = DB::getPDO()->fetchAll($query)) {
  1339. list($nip, $regon) = [$items[0]["nip"], $items[0]["regon"]];
  1340. if (count($items) > 1) {
  1341. for ($i = 1; $i < count($items); $i++) {
  1342. if ($nip != $items[$i]["nip"]) $nip = null;
  1343. if ($regon != $items[$i]["regon"]) $regon = null;
  1344. }
  1345. }
  1346. $set = [];
  1347. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  1348. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  1349. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row->ID}'");
  1350. }
  1351. }
  1352. }
  1353. public static function reloadCache_reTeryt($full = false, $forceAll = false) {
  1354. Lib::loadClass('Teryt');
  1355. $tables = [
  1356. 'BI_audit_CEIDG' => [
  1357. 'fields' => [
  1358. 'wojewodztwo' => 'wojewodztwo',
  1359. 'powiat' => 'powiat',
  1360. 'gmina' => 'gmina',
  1361. 'miejscowosc' => 'miejscowosc',
  1362. 'ulica' => 'ulica',
  1363. 'kodPocztowy' => 'kodPocztowy',
  1364. ],
  1365. 'fieldsTeryt' => [
  1366. 'TERYT_SYM' => 'TERYT_SYM',
  1367. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1368. 'nrDomu' => 'budynek',
  1369. 'nrLokalu' => 'lokal',
  1370. ],
  1371. 'base' => '1',
  1372. ],
  1373. 'BI_audit_CEIDG_pelnomocnicy' => [
  1374. 'fields' => [
  1375. 'wojewodztwo' => 'wojewodztwo',
  1376. 'powiat' => 'powiat',
  1377. 'gmina' => 'gmina',
  1378. 'miejscowosc' => 'miejscowosc',
  1379. 'ulica' => 'ulica',
  1380. 'kodPocztowy' => 'kodPocztowy',
  1381. ],
  1382. 'fieldsTeryt' => [
  1383. 'TERYT_SYM' => 'TERYT_SYM',
  1384. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1385. 'nrDomu' => 'budynek',
  1386. 'nrLokalu' => 'lokal',
  1387. ],
  1388. 'base' => '1',
  1389. ],
  1390. 'BI_audit_ENERGA_PRACOWNICY' => [
  1391. 'fields' => [
  1392. 'miejscowosc' => 'miejscowosc',
  1393. 'kodPocztowy' => 'kodPocztowy',
  1394. 'ulica' => 'ulica',
  1395. ],
  1396. 'fieldsTeryt' => [
  1397. 'TERYT_SYM' => 'TERYT_SYM',
  1398. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1399. 'nrDomu' => 'nr',
  1400. 'nrLokalu' => 'nrLokalu',
  1401. ],
  1402. 'base' => '0',
  1403. ],
  1404. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1405. 'fields' => [
  1406. 'kodPocztowy' => 'kodPocztowy',
  1407. 'miejscowosc' => 'miejscowosc',
  1408. 'ulica' => 'ulica',
  1409. ],
  1410. 'fieldsTeryt' => [
  1411. 'TERYT_SYM' => 'TERYT_SYM',
  1412. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1413. 'nrDomu' => 'nrBudynku',
  1414. 'nrLokalu' => 'nrLokalu',
  1415. ],
  1416. 'base' => '0',
  1417. ],
  1418. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1419. 'fields' => [
  1420. 'kodPocztowy' => 'Kod_pocztowy',
  1421. 'miejscowosc' => 'Miejscowosc',
  1422. 'ulica' => 'Ulica',
  1423. ],
  1424. 'fieldsTeryt' => [
  1425. 'TERYT_SYM' => 'TERYT_SYM',
  1426. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1427. 'nrDomu' => 'Numer_budynku',
  1428. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  1429. ],
  1430. 'base' => '0',
  1431. ],
  1432. 'BI_audit_KRS' => [
  1433. 'fields' => [
  1434. 'wojewodztwo' => 'S_wojewodztwo',
  1435. 'powiat' => 'S_powiat',
  1436. 'gmina' => 'S_gmina',
  1437. 'miejscowosc' => 'A_miejscowosc',
  1438. 'ulica' => 'A_ulica',
  1439. 'kodPocztowy' => 'A_kod',
  1440. ],
  1441. 'fieldsTeryt' => [
  1442. 'TERYT_SYM' => 'TERYT_SYM',
  1443. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1444. 'nrDomu' => 'A_nrDomu',
  1445. 'nrLokalu' => 'A_nrLokalu',
  1446. ],
  1447. 'base' => '1',
  1448. ],
  1449. 'BI_audit_KRS_address' => [
  1450. 'fields' => [
  1451. 'wojewodztwo' => 'S_wojewodztwo',
  1452. 'powiat' => 'S_powiat',
  1453. 'gmina' => 'S_gmina',
  1454. 'miejscowosc' => 'A_miejscowosc',
  1455. 'ulica' => 'A_ulica',
  1456. 'kodPocztowy' => 'A_kod',
  1457. ],
  1458. 'fieldsTeryt' => [
  1459. 'TERYT_SYM' => 'TERYT_SYM',
  1460. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1461. 'nrDomu' => 'A_nrDomu',
  1462. 'nrLokalu' => 'A_nrLokalu',
  1463. ],
  1464. 'base' => '1',
  1465. ],
  1466. 'BI_audit_MSIG_address' => [
  1467. 'fields' => [
  1468. 'wojewodztwo' => 'S_wojewodztwo',
  1469. 'powiat' => 'S_powiat',
  1470. 'gmina' => 'S_gmina',
  1471. 'miejscowosc' => 'A_miejscowosc',
  1472. 'ulica' => 'A_ulica',
  1473. 'kodPocztowy' => 'A_kod',
  1474. ],
  1475. 'fieldsTeryt' => [
  1476. 'TERYT_SYM' => 'TERYT_SYM',
  1477. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1478. 'nrDomu' => 'A_nrDomu',
  1479. 'nrLokalu' => 'A_nrLokalu',
  1480. ],
  1481. 'base' => '1',
  1482. ],
  1483. ];
  1484. foreach ($tables as $table => $tableConf) {
  1485. DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrDomu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrDomu']}`) = ''");
  1486. DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrLokalu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrLokalu']}`) = ''");
  1487. $where = ($full && ($forceAll || (!$tableConf['base']))) ? "" : "where `TERYT_SYM` is null and `cached` = 0";
  1488. $query = "select * from `{$table}` {$where}";
  1489. $refTable = BiAuditRefTables::getRefTable($table, 'TERYT_adresy', true);
  1490. $terytJoinArr = [];
  1491. foreach ($tableConf['fieldsTeryt'] as $terytField => $tableField) {
  1492. $terytJoinArr[] = (
  1493. $terytField == 'nrLokalu'
  1494. ? "coalesce(`teryt`.`{$terytField}`, '') = coalesce(`table`.`{$tableField}`, '')"
  1495. : "`teryt`.`{$terytField}` = `table`.`{$tableField}`"
  1496. );
  1497. }
  1498. $terytJoin = implode(" and ", $terytJoinArr);
  1499. $insertFields = "`" . implode("`, `", array_keys($tableConf['fieldsTeryt'])) . "`";
  1500. $selectFields = "`" . implode("`, `", $tableConf['fieldsTeryt']) . "`";
  1501. $adresy = DB::getPDO()->query($query);
  1502. while ($adres = $adresy->fetch()) {
  1503. DB::getPDO()->query("delete from `{$refTable}` where `PRIMARY_KEY` = '{$adres['ID']}'");
  1504. if (!($forceAll and $adres['TERYT_SYM'])) {
  1505. $search = [];
  1506. foreach ($tableConf['fields'] as $field => $param) if (!empty($adres[$param])) $search[$field] = $adres[$param];
  1507. try {
  1508. $teryt = Teryt::search($search);
  1509. } catch (Exception $e) {
  1510. continue;
  1511. }
  1512. if (empty($teryt['SYM'])) continue;
  1513. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  1514. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  1515. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  1516. }
  1517. if (!trim($adres[$tableConf['fieldsTeryt']['nrDomu']])) continue;
  1518. $terytID = DB::getPDO()->fetchValue("select `teryt`.`ID` from `TERYT_adresy` as `teryt` join `{$table}` as `table` on {$terytJoin} where `table`.`ID` = '{$adres['ID']}'");
  1519. if (!$terytID) {
  1520. if (DB::getPDO()->query("insert into `TERYT_adresy` ({$insertFields}) select {$selectFields} from `{$table}` where `ID` = '{$adres['ID']}'")) {
  1521. if (!($terytID = DB::getPDO()->lastInsertId())) {
  1522. throw new Exception("Błąd dodania rekordu do TERYT_adresy #1");
  1523. }
  1524. } else {
  1525. throw new Exception("Błąd dodania rekordu do TERYT_adresy #2");
  1526. }
  1527. }
  1528. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $adres['ID'], 'REMOTE_PRIMARY_KEY' => $terytID]);
  1529. }
  1530. }
  1531. }
  1532. private static function reloadCache_updateAll($full, $onlyBase) {
  1533. $tablesConf = [
  1534. 'BI_audit_CEIDG' => [
  1535. 'fields' => [
  1536. 'nip' => 'nip',
  1537. 'regon' => 'regon',
  1538. ],
  1539. 'base' => '1',
  1540. ],
  1541. 'BI_audit_CEIDG_pelnomocnicy' => [
  1542. 'fields' => [
  1543. 'nip' => 'nip',
  1544. ],
  1545. 'base' => '1',
  1546. ],
  1547. 'BI_audit_CEIDG_powiazania' => [
  1548. 'fields' => [
  1549. 'nip' => 'nip',
  1550. 'regon' => 'regon',
  1551. ],
  1552. 'base' => '1',
  1553. ],
  1554. 'BI_audit_ENERGA_PRACOWNICY' => [
  1555. 'fields' => [
  1556. 'nip' => 'nip',
  1557. 'regon' => 'regon',
  1558. 'pesel' => 'pesel',
  1559. ],
  1560. 'base' => '0',
  1561. //'where' => '',
  1562. ],
  1563. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1564. 'fields' => [],
  1565. 'base' => '0',
  1566. //'where' => '',
  1567. ],
  1568. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1569. 'fields' => [
  1570. 'krs' => 'KRS',
  1571. 'nip' => 'NIP',
  1572. 'regon' => 'REGON',
  1573. 'pesel' => 'PESEL',
  1574. ],
  1575. 'base' => '0',
  1576. 'where' => "and ownCompany != 'Y'",
  1577. ],
  1578. 'BI_audit_KRS' => [
  1579. 'fields' => [
  1580. 'krs' => 'krs',
  1581. 'nip' => 'nip',
  1582. 'regon' => 'regon',
  1583. ],
  1584. 'base' => '1',
  1585. ],
  1586. 'BI_audit_KRS_address' => [
  1587. 'fields' => [],
  1588. 'base' => '1',
  1589. ],
  1590. 'BI_audit_KRS_company' => [
  1591. 'fields' => [
  1592. 'regon' => 'regon',
  1593. 'krs' => 'krs',
  1594. ],
  1595. 'base' => '1',
  1596. ],
  1597. 'BI_audit_KRS_person' => [
  1598. 'fields' => [
  1599. 'pesel' => 'pesel',
  1600. ],
  1601. 'base' => '1',
  1602. ],
  1603. 'BI_audit_MSIG' => [
  1604. 'fields' => [
  1605. 'krs' => 'krs',
  1606. 'nip' => 'nip',
  1607. 'regon' => 'regon',
  1608. ],
  1609. 'base' => '1',
  1610. ],
  1611. 'BI_audit_MSIG_address' => [
  1612. 'fields' => [],
  1613. 'base' => '1',
  1614. ],
  1615. 'BI_audit_MSIG_company' => [
  1616. 'fields' => [
  1617. 'regon' => 'regon',
  1618. 'krs' => 'krs',
  1619. ],
  1620. 'base' => '1',
  1621. ],
  1622. 'BI_audit_MSIG_person' => [
  1623. 'fields' => [
  1624. 'pesel' => 'pesel',
  1625. ],
  1626. 'base' => '1',
  1627. ],
  1628. // 'BI_audit_KW_requested_person' => [
  1629. // 'fields' => [
  1630. // 'pesel' => 'Seller_person_pesel',
  1631. // 'krs' => 'Seller_person_KRS',
  1632. // 'nip' => 'Seller_person_NIP',
  1633. // 'regon' => 'Seller_person_REGON',
  1634. // ],
  1635. // 'base' => '0',
  1636. // //'where' => '',
  1637. // ],
  1638. 'TERYT_adresy' => [
  1639. 'fields' => [],
  1640. 'base' => '1',
  1641. ],
  1642. ];
  1643. $refTablesConf = [
  1644. 'BI_audit_CEIDG' => [
  1645. 'refTablesTo' => [
  1646. 'BI_audit_CEIDG_pelnomocnicy',
  1647. 'BI_audit_CEIDG_powiazania',
  1648. 'TERYT_adresy',
  1649. ],
  1650. 'base' => 1,
  1651. ],
  1652. 'BI_audit_CEIDG_pelnomocnicy' => [
  1653. 'refTablesTo' => [
  1654. 'TERYT_adresy',
  1655. ],
  1656. 'base' => 1,
  1657. ],
  1658. 'BI_audit_ENERGA_PRACOWNICY' => [
  1659. 'refTablesTo' => [
  1660. 'BI_audit_ENERGA_PRACOWNICY_adresy',
  1661. 'TERYT_adresy',
  1662. ],
  1663. 'base' => 0,
  1664. ],
  1665. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1666. 'refTablesTo' => [
  1667. 'TERYT_adresy',
  1668. ],
  1669. 'base' => 0,
  1670. ],
  1671. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1672. 'refTablesTo' => [
  1673. 'TERYT_adresy',
  1674. ],
  1675. 'base' => 0,
  1676. ],
  1677. 'BI_audit_KRS' => [
  1678. 'refTablesTo' => [
  1679. 'BI_audit_KRS_address',
  1680. 'BI_audit_KRS_company',
  1681. 'BI_audit_KRS_person',
  1682. 'TERYT_adresy',
  1683. ],
  1684. 'base' => 1,
  1685. ],
  1686. 'BI_audit_KRS_address' => [
  1687. 'refTablesTo' => [
  1688. 'TERYT_adresy',
  1689. ],
  1690. 'base' => 1,
  1691. ],
  1692. 'BI_audit_MSIG' => [
  1693. 'refTablesTo' => [
  1694. 'BI_audit_MSIG_address',
  1695. 'BI_audit_MSIG_company',
  1696. 'BI_audit_MSIG_person',
  1697. ],
  1698. 'base' => 1,
  1699. ],
  1700. 'BI_audit_MSIG_address' => [
  1701. 'refTablesTo' => [
  1702. 'TERYT_adresy',
  1703. ],
  1704. 'base' => 1,
  1705. ],
  1706. ];
  1707. $sourceTables = ['BI_audit_ENERGA_PRACOWNICY'];
  1708. if ($full) {
  1709. foreach ($tablesConf as $table => $tableConf) if (!$tableConf['base']) $queries[] = "update `{$table}` set `cached` = 0";
  1710. $queries[] = "delete from `BI_audit_ALL` where `BASE` = 0";
  1711. // $queries[] = "optimize table `BI_audit_ALL`";
  1712. $queries[] = "delete from `BI_audit_ALL_ref` where `BASE` = 0";
  1713. // $queries[] = "optimize table `BI_audit_ALL_ref`";
  1714. $allTables = [];
  1715. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  1716. $allTables[] = $refTableFrom;
  1717. // if ($refTableConf['base']) continue;
  1718. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  1719. $allTables[] = $refTableTo;
  1720. if ($refTableConf['base']) continue;
  1721. $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
  1722. $queries[] = "update `{$refTable}` set `A_STATUS` = 'WAITNG' where `A_STATUS` = 'NORMAL'";
  1723. // $queries[] = "insert into `{$refTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`, `TRANSACTION_ID`, `A_STATUS`) select `all1`.`ID`, `all2`.`ID`, '-1', 'NORMAL' from `BI_audit_ALL` as `all1` join `BI_audit_ALL_ref` as `ref` on `all1`.`ID` = `ref`.`ID1` join `BI_audit_ALL` as `all2` on `ref`.`ID2` = `all2`.`ID` where `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all2`.`REMOTE_TABLE` = '{$refTableTo}'";
  1724. }
  1725. }
  1726. $allTables = array_unique($allTables);
  1727. foreach ($allTables as $refTableFrom) {
  1728. foreach ($allTables as $refTableTo) {
  1729. if ($refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, false)) {
  1730. $queries[] = "delete from `{$refTable}` where `TRANSACTION_ID` = '-1'";
  1731. $queries[] = "optimize table `{$refTable}`";
  1732. $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";
  1733. }
  1734. }
  1735. }
  1736. }
  1737. foreach ($tablesConf as $table => $tableConf) {
  1738. if ($onlyBase && (!$tableConf['base'])) continue;
  1739. $where = "where `cached` = 0";
  1740. if (!empty($tableConf['where'])) $where .= " {$tableConf['where']}";
  1741. // $queries[] = "insert into `BI_audit_ALL` (`REMOTE_TABLE`, `REMOTE_ID`, `BASE`, " . implode(", ", array_keys($tableConf['fields'])) .
  1742. // ") select '{$table}', ID, '{$tableConf['base']}', " . implode(", ", $tableConf['fields']) . " from `{$table}` {$where}";
  1743. $fields = ["`REMOTE_TABLE`", "`REMOTE_ID`", "`BASE`"];
  1744. foreach (array_keys($tableConf['fields']) as $field) $fields[] = "`{$field}`";
  1745. $values = ["'{$table}'", "`ID`", "'{$tableConf['base']}'"];
  1746. foreach ($tableConf['fields'] as $value) $values[] = "`{$value}`";
  1747. $queries[] = "insert into `BI_audit_ALL` (" . implode(", ", $fields) . ") select " . implode(", ", $values) . " from `{$table}` {$where}";
  1748. $queries[] = "update `{$table}` set `cached` = 1 {$where}";
  1749. }
  1750. $queries[] = "update `BI_audit_ALL` set `nip` = null where `nip` = 0";
  1751. $queries[] = "update `BI_audit_ALL` set `regon` = null where `regon` = 0";
  1752. $queries[] = "update `BI_audit_ALL` set `krs` = null where `krs` = 0";
  1753. $queries[] = "update `BI_audit_ALL` set `pesel` = null where `pesel` = 0";
  1754. $queries[] = "set @var = (select round(coalesce(max(`ID`), '0.5'), 1) from `BI_audit_ALL_ref_RELATIONS`)";
  1755. $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";
  1756. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  1757. if ($onlyBase && (!$tableConf['base'])) continue;
  1758. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  1759. $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
  1760. $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`";
  1761. if (!in_array($refTableFrom, $sourceTables)) {
  1762. $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`";
  1763. }
  1764. if ($backRefTable = BiAuditRefTables::getRefTable($refTableTo, $refTableFrom, false)) {
  1765. $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'";
  1766. }
  1767. $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'";
  1768. }
  1769. }
  1770. foreach ($queries as $query) {
  1771. echo "SQL: {$query}\n";
  1772. DB::getPDO()->query($query);
  1773. }
  1774. $BiAuditRelations = new BiAuditRelations();
  1775. $result = DB::getPDO()->query("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
  1776. while ($row = $result->fetch()) $BiAuditRelations->findRelations($row['ID']);
  1777. DB::getPDO()->query("update `BI_audit_ALL` set `reffed` = 1");
  1778. }
  1779. public function doReloadCache($full = false) {
  1780. if ($full === 'base') {
  1781. $onlyBase = true;
  1782. $full = false;
  1783. } else {
  1784. $onlyBase = false;
  1785. }
  1786. $powiazaniaDirLocation = self::getMainDirectory();
  1787. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1788. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1789. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1790. if ($full) file_put_contents($reloadCachePidFile, getmypid());
  1791. try {
  1792. //self::importPracownicy(); //TODO
  1793. error_log('now: self::reloadCache_parseUmowy');
  1794. self::reloadCache_parseUmowy($full);
  1795. error_log('now: self::reloadCache_reTeryt');
  1796. self::reloadCache_reTeryt($full);
  1797. error_log('now: self::reloadCache_updateAll');
  1798. self::reloadCache_updateAll($full, $onlyBase);
  1799. if ($full) file_put_contents($reloadCacheResultFile, "ok");
  1800. } catch (Exception $e) {
  1801. var_dump($e);
  1802. if ($full) file_put_contents($reloadCacheResultFile, $e->getMessage());
  1803. else throw new Exception($e->getMessage());
  1804. }
  1805. }
  1806. public function doGeneratePowiazania($ID) {
  1807. $powiazaniaDirLocation = self::getMainDirectory();
  1808. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1809. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  1810. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  1811. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  1812. file_put_contents($pidFile, getmypid());
  1813. $tablesConf = [
  1814. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  1815. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  1816. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  1817. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  1818. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  1819. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  1820. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  1821. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  1822. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  1823. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  1824. ];
  1825. try {
  1826. $BiAuditPowiazania = new BiAuditPowiazania($ID, $tasksDirLocation);
  1827. $query = "select count(*) from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` where `FILE_STATUS` = 'IN_PROGRESS' and `BI_analiza_reloadCache` = 'Part' and ID != ${ID}";
  1828. $sqlArr = [
  1829. 'BI_analiza_reloadCache' => 'Part',
  1830. 'FILE_STATUS_info' => 'Odświeżam częściowo cache',
  1831. ];
  1832. do {
  1833. DB::getPDO()->query("lock tables `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` write");
  1834. $activeReloadingCache = DB::getPDO()->fetchValue($query);
  1835. if (!$activeReloadingCache) DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  1836. DB::getPDO()->query("unlock tables");
  1837. if ($activeReloadingCache) {
  1838. BiAuditPowiazania::saveToLog("Czekam na zakończenie częściowego odświeżania cache przez inne zadanie");
  1839. sleep(30);
  1840. }
  1841. } while ($activeReloadingCache);
  1842. BiAuditPowiazania::saveToLog("Uruchamiam częściowe odświeżenie cache");
  1843. $this->doReloadCache(); //DUPA testowe wylaczanie
  1844. BiAuditPowiazania::saveToLog("Odświeżono częściowo cache");
  1845. $sqlArr = [
  1846. 'BI_analiza_reloadCache' => 'No',
  1847. 'FILE_STATUS_info' => 'Szukam powiązań',
  1848. ];
  1849. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  1850. $BiAuditPowiazania->run();
  1851. if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  1852. //file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  1853. $sqlArr = ['FILE_STATUS_info' => 'Generuję raporty PDF i HTML'];
  1854. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  1855. //$BiAuditPowiazania->saveXml();
  1856. $BiAuditPowiazania->generatePdfAndHtml();
  1857. file_put_contents($resultFile, json_encode(['result' => 'ok', 'parts' => $BiAuditPowiazania->getPartsCount()]));
  1858. } catch (Exception $e) {
  1859. file_put_contents($resultFile, json_encode(['result' => 'error', 'message' => $e->getMessage()]));
  1860. }
  1861. }
  1862. public function reinstallAction() {
  1863. $this->reinstall();
  1864. die('OK');
  1865. }
  1866. public function reinstall() {
  1867. $sqlList = array();
  1868. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  1869. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  1870. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  1871. SQL;
  1872. $sqlList['ChangeStructure1'] = <<<SQL
  1873. 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';
  1874. SQL;
  1875. $sqlList['ChangeStructure2'] = <<<SQL
  1876. UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
  1877. SQL;
  1878. $sqlList['ChangeStructure3'] = <<<SQL
  1879. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
  1880. SQL;
  1881. $sqlList['ChangeStructure4'] = <<<SQL
  1882. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_depth` `BI_analiza_maxDepth` INT(2) NULL DEFAULT '9';
  1883. SQL;
  1884. $sqlList['ChangeStructure5'] = <<<SQL
  1885. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_minDepth` INT(2) NOT NULL DEFAULT '0' AFTER `FILE_STATUS_info`;
  1886. SQL;
  1887. $sqlList['ChangeStructure6'] = <<<SQL
  1888. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_onlyTargets` ENUM('Y','N') NOT NULL DEFAULT 'Y' AFTER `BI_analiza_maxDepth`;
  1889. SQL;
  1890. $db = DB::getDB();
  1891. if ($db->has_errors()) {
  1892. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  1893. }
  1894. foreach ($sqlList as $sqlName => $sql) {
  1895. $res = $db->query($sql);
  1896. if ($db->has_errors()) {
  1897. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  1898. }
  1899. }
  1900. }
  1901. }
  1902. class BiAuditRelations {
  1903. private $RELATIONS_ID = [];
  1904. private $relations = [
  1905. 'nip' => ['nip'],
  1906. 'regon' => ['regon'],
  1907. 'krs' => ['krs'],
  1908. 'pesel' => ['pesel'],
  1909. ];
  1910. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  1911. private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  1912. public function __construct() {
  1913. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  1914. $result = DB::getPDO()->fetchAll($query);
  1915. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  1916. }
  1917. private function getRelationID($name) {
  1918. if (!isset($this->RELATIONS_ID[$name])) {
  1919. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  1920. $newID = DB::getPDO()->fetchValue($query);
  1921. $this->RELATIONS_ID[$name] = $newID;
  1922. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  1923. DB::getPDO()->query($query);
  1924. }
  1925. return $this->RELATIONS_ID[$name];
  1926. }
  1927. private function addToRefTable($fromTable, $toTable, $fromID, $toID) {
  1928. if ($refTable = BiAuditRefTables::getRefTable($fromTable, $toTable, false)) {
  1929. if (!DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = '{$fromID}' and `REMOTE_PRIMARY_KEY` = '{$toID}' and `A_STATUS` != 'DELETED'")) {
  1930. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $fromID, 'REMOTE_PRIMARY_KEY' => $toID, 'A_STATUS' => 'NORMAL', 'TRANSACTION_ID' => '-1']);
  1931. }
  1932. }
  1933. }
  1934. public function findRelations($ID) {
  1935. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  1936. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  1937. $row = $result[0];
  1938. $joins = [];
  1939. $items = '';
  1940. foreach ($this->relations as $name => $columns) {
  1941. $ok = 0;
  1942. $join = [];
  1943. foreach ($columns as $column) {
  1944. $join[] = "t1.{$column} = t2.{$column}";
  1945. if ($row[$column] !== null) $ok++;
  1946. }
  1947. if ($ok / count($columns) > 0.5) {
  1948. $joins[] = "(" . implode(" and ", $join) . ")";
  1949. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  1950. }
  1951. }
  1952. if (!$joins) return false;
  1953. $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 " .
  1954. "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})";
  1955. $result = DB::getPDO()->fetchAll($query);
  1956. foreach ($result as $row) {
  1957. $relationID = 0;
  1958. foreach ($this->relations as $name => $v) {
  1959. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  1960. }
  1961. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  1962. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  1963. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  1964. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  1965. if (!($start2 || $end1)) {
  1966. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
  1967. $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
  1968. $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
  1969. DB::getPDO()->query($query);
  1970. }
  1971. if (!($start1 || $end2)) {
  1972. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
  1973. $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
  1974. $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
  1975. DB::getPDO()->query($query);
  1976. }
  1977. }
  1978. }
  1979. }
  1980. class BiAuditRefTables {
  1981. public static function getRefTable($tableFrom, $tableTo, $returnException = false) {
  1982. static $refTables = [];
  1983. if (!isset($refTables[$tableFrom][$tableTo])) {
  1984. try {
  1985. $refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
  1986. } catch (Exception $e) {
  1987. if ($returnException) throw new Exception($e->getMessage());
  1988. $refTables[$tableFrom][$tableTo] = false;
  1989. }
  1990. }
  1991. return $refTables[$tableFrom][$tableTo];
  1992. }
  1993. public static function getRefTables($tableFrom) {
  1994. static $refTables = [];
  1995. if (!isset($refTables[$tableFrom])) {
  1996. $namespace = "default_db/{$tableFrom}/{$tableFrom}";
  1997. try {
  1998. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  1999. if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
  2000. $fields = $item['field'];
  2001. $_refTables = [];
  2002. foreach ($fields as $field) {
  2003. list($type, $child) = explode(":", $field['xsdType'], 2);
  2004. if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) {
  2005. try {
  2006. $_refTable = ACL::getRefTable($namespace, $child);
  2007. $_refTables[] = $_refTable;
  2008. } catch (Exception $e) {
  2009. }
  2010. }
  2011. }
  2012. $refTables[$tableFrom] = $_refTables;
  2013. } catch (Exception $e) {
  2014. $refTables[$tableFrom] = [];
  2015. }
  2016. }
  2017. return $refTables[$tableFrom];
  2018. }
  2019. }
  2020. class BiAuditPowiazania {
  2021. private $minDepth;
  2022. private $maxDepth, $origMaxDepth;
  2023. private $onlyTargets;
  2024. private $ID;
  2025. private $nodes = [];
  2026. private $endNodes;
  2027. private $path = [];
  2028. private $results = [];
  2029. private $items_results = [];
  2030. private $relations = [];
  2031. private $srcTables = ['BI_audit_ENERGA_PRACOWNICY'];
  2032. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  2033. private $step = 0;
  2034. private $tasksDirLocation;
  2035. private $progressFile;
  2036. private $progress = [
  2037. 'summary' => [
  2038. 'count' => 0,
  2039. 'message' => 'Inicjacja',
  2040. 'ts' => null,
  2041. 'step' => 'initialize',
  2042. 'reportsCount' => 0,
  2043. 'reportsCreated' => 0,
  2044. ],
  2045. 'details' => [],
  2046. ];
  2047. private $lastProgress = 0;
  2048. private $lastResults = 0;
  2049. private $startTimestamp = null;
  2050. private $lastTimestamp = null;
  2051. private $lowProgressCount = 0;
  2052. private $count, $i;
  2053. private $splittedResults = [];
  2054. private $maxResults = 1000000;
  2055. private $fidRow = [];
  2056. private $itemID = 0;
  2057. private $reverseSearch = false;
  2058. private $query = "";
  2059. private static function generateJson($type, $data) {
  2060. return json_encode(['ts' => microtime(true), 'type' => $type, 'data' => $data]);
  2061. }
  2062. public static function saveToLog($message) {
  2063. $messageJson = self::generateJson('message', ['message' => $message]);
  2064. echo $messageJson . "\n";
  2065. }
  2066. private static function exec($cmd) {
  2067. $path = 'export PATH=$PATH:/usr/sbin;';
  2068. $cmd = "{$path} {$cmd}";
  2069. echo "CMD :: {$cmd}\n";
  2070. shell_exec($cmd);
  2071. }
  2072. private function saveProgress($args = []) {
  2073. $timestamp = microtime(true);
  2074. if (isset($args['progress']) && $this->i) {
  2075. $elapsed = $timestamp - $this->startTimestamp;
  2076. if ($args['progress']) {
  2077. $estimated = ($elapsed * (1 - $args['progress'])) / $args['progress'];
  2078. } else $estimated = "N/A";
  2079. $this->lastProgress = $args['progress'];
  2080. $this->lastTimestamp = $timestamp;
  2081. $progressJson = self::generateJson('progress', ['progress' => $args['progress'], 'item' => $this->i . "/" . $this->count, 'results' => count($this->results), 'step' => $this->step, 'elapsed' => $elapsed, 'estimated' => $estimated]);
  2082. echo $progressJson . "\n";
  2083. $this->progress['details'][$this->itemID] = ['progress' => $args['progress'], 'results' => (count($this->results) - $this->lastResults), 'elapsed' => $elapsed, 'estimated' => $estimated];
  2084. }
  2085. if (isset($args['message'])) $this->progress['summary']['message'] = $args['message'];
  2086. if (isset($args['step'])) $this->progress['summary']['step'] = $args['step'];
  2087. if (isset($args['reportsCreated'])) $this->progress['summary']['reportsCreated'] = round($this->progress['summary']['reportsCreated'] + $args['reportsCreated'], 2);
  2088. $this->progress['summary']['ts'] = $timestamp;
  2089. file_put_contents($this->progressFile, json_encode($this->progress));
  2090. }
  2091. private static function throwException($message) {
  2092. self::saveToLog($message);
  2093. throw new Exception($message);
  2094. }
  2095. public function __construct($ID = 0, $tasksDirLocation = null) {
  2096. if (!$ID) self::throwException("Wrong ID parameter");
  2097. if (!$tasksDirLocation) self::throwException("Wrong directory of tasks location");
  2098. $this->ID = $ID;
  2099. $this->tasksDirLocation = $tasksDirLocation;
  2100. $this->progressFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.progress";
  2101. $this->saveProgress();
  2102. }
  2103. public function run() {
  2104. $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')";
  2105. $result = DB::getPDO()->fetchAll($query);
  2106. if (!$result) self::throwException("Błąd danych");
  2107. if ($this->loadResults()) {
  2108. $this->splitResults();
  2109. return;
  2110. }
  2111. self::saveToLog("Wczytuję parametry wyszukiwania powiązań");
  2112. $this->minDepth = (int) $result[0]['BI_analiza_minDepth'];
  2113. $this->maxDepth = (int) $result[0]['BI_analiza_maxDepth'];
  2114. $this->onlyTargets = ($result[0]['BI_analiza_onlyTargets'] != 'N');
  2115. if (!$this->minDepth) $this->minDepth = 1;
  2116. if (!$this->maxDepth) self::throwException("Błąd danych - nieokreślono maksymalnej głębokości analizy");
  2117. if ($this->minDepth > $this->maxDepth) self::throwException("Wartość minimalnej głębokości analizy jest większa od wartości maksymalnej głębokości analizy");
  2118. $subQueries = [];
  2119. foreach ($this->destTables as $destTable) {
  2120. $refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $destTable, true);
  2121. $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}'";
  2122. }
  2123. $query = implode(" union ", $subQueries) . " order by `ID` asc";
  2124. $resultDest = DB::getPDO()->fetchAll($query);
  2125. if ((!$resultDest) && $this->onlyTargets) self::throwException("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  2126. $subQueries = [];
  2127. foreach ($this->srcTables as $srcTable) {
  2128. $refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $srcTable, true);
  2129. $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}'";
  2130. }
  2131. $query = implode(" union ", $subQueries) . " order by `ID` asc";
  2132. $resultSrc = DB::getPDO()->fetchAll($query);
  2133. if (!$resultSrc) self::throwException("Błąd danych - nie zdefinowano żadnego początkowego obiektu");
  2134. if (count($resultSrc) <= count($resultDest) || (!$this->onlyTargets)) {
  2135. $result = $resultSrc;
  2136. $this->endNodes = array_map('reset', $resultDest);
  2137. $this->reverseSearch = false;
  2138. $this->query = "select ref.ID2 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID1";
  2139. } else {
  2140. $result = $resultDest;
  2141. $this->endNodes = array_map('reset', $resultSrc);
  2142. $this->reverseSearch = true;
  2143. $this->query = "select ref.ID1 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID2";
  2144. self::saveToLog("Docelowych obiektów jest mniej, niż początkowych - włączono mechanizm odwrotnego przeszukiwania");
  2145. }
  2146. self::saveToLog("Rozpoczynam wyszukiwanie powiązań");
  2147. $this->count = count($result);
  2148. $this->progress['summary']['count'] = $this->count;
  2149. $this->origMaxDepth = $this->maxDepth;
  2150. $this->saveProgress(['step' => 'relations']);
  2151. try {
  2152. foreach ($result as $i => $row) {
  2153. $this->i = $i + 1;
  2154. $this->itemID = DB::getPDO()->fetchValue("select `REMOTE_ID` from `BI_audit_ALL` where `ID` = :ID", [":ID" => $row['ID']]);
  2155. $this->startTimestamp = microtime(true);
  2156. $this->lastProgress = 0;
  2157. $this->saveProgress(['progress' => 0, 'message' => "Wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
  2158. if ($this->maxDepth != $this->origMaxDepth) {
  2159. $this->maxDepth = $this->origMaxDepth;
  2160. self::saveToLog("Przywrócono oryginalną maksymalną głębokość przeszukiwania ({$this->origMaxDepth})");
  2161. }
  2162. $this->findPowiazania($row['ID']);
  2163. $this->saveProgress(['progress' => 1, 'message' => "Zakończono wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
  2164. $this->lastResults = count($this->results);
  2165. }
  2166. } catch (Exception $e) {
  2167. if ($this->i < $this->count) {
  2168. $this->startTimestamp = microtime(true);
  2169. $this->lastProgress = 0;
  2170. $this->lastResults = count($this->results);
  2171. while (++$this->i <= $this->count) $this->saveProgress(['progress' => 0]);
  2172. }
  2173. if ($message = $e->getMessage()) self::saveToLog("Wystąpił błąd podczas wyszukiwania powiązań - {$message}");
  2174. }
  2175. $this->nodes = [];
  2176. self::saveToLog("Zakończono wyszukiwanie powiązań");
  2177. $this->sortResults();
  2178. $this->saveResults();
  2179. //$this->saveToDb(); 2017-12-14 - przerobiono na zapisywanie danych do bazy w locie
  2180. $this->splitResults();
  2181. }
  2182. private static function reversePath($path) {
  2183. $arr = array_reverse($path, true);
  2184. $keys = array_keys($arr);
  2185. array_unshift($arr, array_pop($arr));
  2186. return array_combine($keys, $arr);
  2187. }
  2188. private function addResult($progress) {
  2189. if (count($this->results) == $this->maxResults) {
  2190. $message = "Przerwano wyszukiwanie powiązań - osiągnięto maksymalną liczbę wyników {$this->maxResults}";
  2191. self::saveToLog($message);
  2192. $this->saveProgress(['progress' => $progress, 'message' => $message]);
  2193. throw new Exception('');
  2194. }
  2195. if ($this->reverseSearch) $path = self::reversePath($this->path);
  2196. else $path = $this->path;
  2197. $this->results[] = $path;
  2198. $this->saveToDb($path);
  2199. }
  2200. public function findPowiazania($ID, $progress = 0, $steps = 1, $relation = "") {
  2201. if (((++$this->step) % 1000000) == 0) {
  2202. $progressDiff = $progress - $this->lastProgress;
  2203. if ($progressDiff < 0.00005) {
  2204. $this->lowProgressCount++;
  2205. if ($this->lowProgressCount == 10) {
  2206. $this->maxDepth--;
  2207. self::saveToLog("Zbyt dużo rekurencji, zmniejszono maksymalną głębokość poszukiwań do {$this->maxDepth} dla bieżącego obiektu");
  2208. }
  2209. } else $this->lowProgressCount = 0;
  2210. }
  2211. if ((($this->step) % 100000) == 0) {
  2212. $this->saveProgress(['progress' => $progress]);
  2213. }
  2214. if ((($this->step) % 10000) == 0) {
  2215. if (memory_get_usage(true) > 3000000000) {
  2216. $this->nodes = [];
  2217. self::saveToLog("Oczyszczam podręczny cache - zajmuje zbyt dużo pamięci");
  2218. }
  2219. }
  2220. if (isset($this->path[$ID])) return false;
  2221. $this->path[$ID] = $relation;
  2222. if (!$relation) $relation = 0;
  2223. if (in_array($ID, $this->endNodes)) {
  2224. if (count($this->path) > $this->minDepth) $this->addResult($progress);
  2225. array_pop($this->path);
  2226. return;
  2227. }
  2228. if (count($this->path) > $this->maxDepth) {
  2229. if (!$this->onlyTargets) $this->addResult($progress);
  2230. array_pop($this->path);
  2231. return;
  2232. }
  2233. if (!isset($this->nodes[$ID][$relation])) {
  2234. $where = $relation ? "and ({$relation} & ref.RELATION_ID) != " . ($this->reverseSearch ? "ref.RELATION_ID" : $relation) : "";
  2235. $query = "{$this->query} = {$ID} {$where}";
  2236. $this->nodes[$ID][$relation] = DB::getPDO()->fetchAll($query);
  2237. }
  2238. $nodes = array_values(array_filter($this->nodes[$ID][$relation], function ($node) {
  2239. if (isset($this->path[$node['ID']])) return false;
  2240. return true;
  2241. }));
  2242. $count = count($nodes);
  2243. foreach ($nodes as $i => $node) $this->findPowiazania($node['ID'], ($progress + ($i / ($count * $steps))), ($count * $steps), $node['RELATION_ID']);
  2244. array_pop($this->path);
  2245. }
  2246. private function sortResults() {
  2247. if (!$this->results) return;
  2248. uasort($this->results, function ($a, $b) {
  2249. $ca = count($a);
  2250. $cb = count($b);
  2251. $c = min($ca, $cb);
  2252. $ka = array_keys($a);
  2253. $kb = array_keys($b);
  2254. for ($i = 0; $i < $c; $i++) {
  2255. if ($ka[$i] < $kb[$i]) return -1;
  2256. if ($ka[$i] > $kb[$i]) return 1;
  2257. }
  2258. if ($ca < $cb) return -1;
  2259. if ($ca > $cb) return 1;
  2260. return 0;
  2261. });
  2262. }
  2263. private function saveResults() {
  2264. self::saveToLog("Zapisuję wyliczone dane do pliku");
  2265. if (!$this->results) {
  2266. self::saveToLog("Brak wyliczonych danych - niczego nie zapisaono");
  2267. return false;
  2268. }
  2269. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  2270. $data = base64_encode(gzcompress(json_encode(['results' => $this->results, 'fidRow' => $this->fidRow])));
  2271. file_put_contents($dataFile, $data);
  2272. self::saveToLog("Zapisano wyliczone dane do pliku");
  2273. return true;
  2274. }
  2275. private function loadResults() {
  2276. self::saveToLog("Próbuję wczytać wcześniej wyliczone dane");
  2277. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  2278. if (!file_exists($dataFile)) {
  2279. self::saveToLog("Nie znaleziono pliku z wyliczonymi danymi");
  2280. return false;
  2281. }
  2282. $data = file_get_contents($dataFile);
  2283. $results = @json_decode(gzuncompress(base64_decode($data)), true);
  2284. if (!$results) {
  2285. self::saveToLog("Wystąpił błąd wczytywania wcześniej wyliczonych danych");
  2286. return false;
  2287. }
  2288. if (isset($results['results'])) {
  2289. $this->results = $results['results'];
  2290. if (isset($results['fidRow'])) $this->fidRow = $results['fidRow'];
  2291. } else $this->results = $results;
  2292. self::saveToLog("Wczytano wcześniej wyliczone dane");
  2293. return true;
  2294. }
  2295. private function relationName($ID) {
  2296. if (!$ID) return '';
  2297. if (!isset($this->relations[$ID])) {
  2298. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  2299. $result = DB::getPDO()->fetchAll($query);
  2300. $rels = array_map('reset', $result);
  2301. $this->relations[$ID] = implode(", ", $rels);
  2302. }
  2303. return $this->relations[$ID];
  2304. }
  2305. private function splitResults() {
  2306. $MAX = 1000;
  2307. $countBySource = [];
  2308. $resultsKeys = [];
  2309. foreach ($this->results as $resultKey => $result) {
  2310. $_keys = array_keys($result);
  2311. $countBySource[reset($_keys)][] = $resultKey;
  2312. }
  2313. foreach ($countBySource as $resultKeys) {
  2314. if (count($resultKeys) > $MAX) {
  2315. $countByDest = [];
  2316. foreach ($resultKeys as $resultKey) {
  2317. $_keys = array_keys($this->results[$resultKey]);
  2318. $countByDest[end($_keys)][] = $resultKey;
  2319. }
  2320. foreach ($countByDest as $resultKeys2) $resultsKeys = array_merge($resultsKeys, array_chunk($resultKeys2, $MAX));
  2321. } else $resultsKeys[] = $resultKeys;
  2322. }
  2323. $results = [];
  2324. while ($resultsKeys) {
  2325. $resultKeys = array_shift($resultsKeys);
  2326. while ($next = current($resultsKeys)) {
  2327. if (count($resultKeys) + count($next) <= $MAX) {
  2328. $resultKeys = array_merge($resultKeys, $next);
  2329. unset($resultsKeys[key($resultsKeys)]);
  2330. } else break; //next($resultsKeys);
  2331. }
  2332. $_results = [];
  2333. foreach ($resultKeys as $key) $_results[$key] = $this->results[$key];
  2334. $results[] = $_results;
  2335. // $results[] = array_map(function ($resultKey) {return $this->results[$resultKey];}, $resultKeys);
  2336. }
  2337. $this->splittedResults = $results;
  2338. $this->progress['summary']['reportsCount'] = count($results);
  2339. }
  2340. public function getPartsCount() {
  2341. return count($this->splittedResults);
  2342. }
  2343. private function generateItemsResults($resultsPart = null) {
  2344. if ($resultsPart === null) self::saveToLog("Generuję dane na potrzeby utworzenia pojedynczego pliku XML");
  2345. else {
  2346. self::saveToLog("Generuję dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  2347. if ($resultsPart >= $this->getPartsCount()) throw new Exception("generateItemsResults() error - bad part number");
  2348. }
  2349. $xmlTask = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  2350. $xmlRow = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  2351. $xmlObject = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object";
  2352. $items_kontrahenci = [];
  2353. $items_kw_person = [];
  2354. $kontrahenci = [];
  2355. $kw_person = [];
  2356. $_items_results = [];
  2357. $refUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  2358. $refKwRequestedToKwRequestedPerson = BiAuditRefTables::getRefTable('BI_audit_KW_requested', 'BI_audit_KW_requested_person', true);
  2359. $this->items_results[$resultsPart] = [];
  2360. $this->items_results[$resultsPart]['@attributes'] = ['xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd'];
  2361. $this->items_results[$resultsPart][$xmlTask]['@attributes'] = ['fid' => "{$xmlTask}.{$this->ID}"];
  2362. if ($resultsPart === null) {
  2363. $results = $this->results;
  2364. } else {
  2365. $results = (!empty($this->splittedResults[$resultsPart])) ? $this->splittedResults[$resultsPart] : [];
  2366. $this->items_results[$resultsPart][$xmlTask]['@attributes']['system_cache__dita:part'] = ($resultsPart + 1);
  2367. }
  2368. foreach ($results as $key => $result) {
  2369. if ($this->fidRow) $item_results = ['@attributes' => ['fid' => "{$xmlRow}.{$this->fidRow[$key]['fid']}"]];
  2370. foreach ($result as $ID => $rel) {
  2371. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  2372. $row = DB::getPDO()->fetchFirst($query);
  2373. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  2374. $obj = DB::fetch(DB::query($query));
  2375. $item_result = [];
  2376. if ($this->fidRow) {
  2377. $item_result['@attributes'] = ['fid' => "{$xmlObject}.{$this->fidRow[$key]['obj'][$ID]}"];
  2378. }
  2379. $item_result[$row['REMOTE_TABLE']] = array_merge(['@attributes' => ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"]], (array) $obj);
  2380. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_operational_raport_note', $row['REMOTE_TABLE'], false)) {
  2381. $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']}'";
  2382. if ($notes = DB::getPDO()->fetchAll($query)) $item_result[$row['REMOTE_TABLE']]['BI_audit_operational_raport_note'] = $notes;
  2383. }
  2384. if ($refTable = BiAuditRefTables::getRefTable($row['REMOTE_TABLE'], 'BI_audit_taxpayer', false)) {
  2385. $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']}'";
  2386. if ($taxpayer = DB::getPDO()->fetchFirst($query)) {
  2387. $item_result[$row['REMOTE_TABLE']]['BI_audit_taxpayer'] = array_merge(['@attributes' => ['fid' => "BI_audit_taxpayer.{$taxpayer['ID']}"]], $taxpayer);
  2388. }
  2389. }
  2390. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  2391. $item_results[$xmlObject][] = $item_result;
  2392. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  2393. $kontrahenci[] = $row['REMOTE_ID'];
  2394. $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']}'";
  2395. $res = DB::query($query);
  2396. if (mysql_num_rows($res)) {
  2397. $umowy = [];
  2398. while ($obj = DB::fetch($res)) {
  2399. $umowa = (array) $obj;
  2400. $umowa = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_RUM_UMOWY.{$umowa['ID']}"]], $umowa);
  2401. $umowy[] = $umowa;
  2402. }
  2403. $item_kontrahenci['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
  2404. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  2405. $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  2406. $items_kontrahenci[] = $item_kontrahenci;
  2407. }
  2408. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  2409. $kw_person[] = $row['REMOTE_ID'];
  2410. $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']}'";
  2411. $res = DB::query($query);
  2412. if (mysql_num_rows($res)) {
  2413. $kws = [];
  2414. while ($obj = DB::fetch($res)) {
  2415. $kw = (array) $obj;
  2416. $kw = array_merge(['@attributes' => ['fid' => "BI_audit_KW_requested.{$kw['ID']}"]], $kw);
  2417. $kws[] = $kw;
  2418. }
  2419. $item_kw_person['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
  2420. $item_kw_person['ID'] = $row['REMOTE_ID'];
  2421. $item_kw_person['BI_audit_KW_requested'] = $kws;
  2422. $items_kw_person[] = $item_kw_person;
  2423. }
  2424. }
  2425. }
  2426. $this->items_results[$resultsPart][$xmlTask][$xmlRow][] = $item_results;
  2427. }
  2428. $this->items_results[$resultsPart][$xmlTask]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  2429. $this->items_results[$resultsPart][$xmlTask]['BI_audit_KW_requested_person'] = $items_kw_person;
  2430. self::saveToLog("Wygenerowano dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  2431. }
  2432. private function saveToDb($result = null, $key = null) {
  2433. if ($result === null) {
  2434. self::saveToLog("Zapisuję wyliczone dane do bazy");
  2435. if (!$this->results) {
  2436. self::saveToLog("Brak wyliczonych danych - nie zapisaono niczego do bazy");
  2437. return null;
  2438. }
  2439. foreach ($this->results as $key => $result) $this->saveToDb($result, $key);
  2440. self::saveToLog("Zapisano wyliczone dane do bazy");
  2441. } else {
  2442. if ($key === null) {
  2443. end($this->results);
  2444. $key = key($this->results);
  2445. }
  2446. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  2447. $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
  2448. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  2449. $fidObj = [];
  2450. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  2451. foreach ($result as $ID => $rel) {
  2452. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  2453. $object = DB::getPDO()->fetchFirst($query);
  2454. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relationName($rel)]);
  2455. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  2456. $ref = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', $object['REMOTE_TABLE'], true);
  2457. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  2458. $fidObj[$ID] = $idPowiazaniaRowObject;
  2459. }
  2460. $this->fidRow[$key] = [
  2461. 'fid' => $IdPowiazaniaRow,
  2462. 'obj' => $fidObj,
  2463. ];
  2464. }
  2465. }
  2466. public function saveXml($resultsPart = null) {
  2467. if ($this->getPartsCount()) {
  2468. if ($resultsPart === null) {
  2469. self::saveToLog("Generuję pliki XML (liczba plików do wygenerowania: {$this->getPartsCount()})");
  2470. for ($i =0; $i < $this->getPartsCount(); $i++) {
  2471. $partNo = str_pad($i + 1, 6, '0', STR_PAD_LEFT);
  2472. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  2473. file_put_contents($xmlFile, $this->asXml($i));
  2474. }
  2475. self::saveToLog("Zakończono generowanie plików XML");
  2476. } else {
  2477. if ($resultsPart >= $this->getPartsCount()) {
  2478. self::saveToLog("saveXml() error - bad result number");
  2479. return;
  2480. }
  2481. $partNo = str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  2482. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  2483. file_put_contents($xmlFile, $this->asXml($resultsPart));
  2484. }
  2485. } else {
  2486. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
  2487. file_put_contents($xmlFile, $this->asXml());
  2488. }
  2489. }
  2490. public function asXml($resultsPart = null) {
  2491. self::saveToLog("Generuję plik XML ({$resultsPart})");
  2492. if (!$this->results) {
  2493. self::saveToLog("Brak wyników (#1), nie wygenerowano pliku XML ({$resultsPart})");
  2494. return null;
  2495. }
  2496. if (!isset($this->items_results[$resultsPart])) $this->generateItemsResults($resultsPart);
  2497. if (!isset($this->items_results[$resultsPart])) {
  2498. self::saveToLog("Brak wyników (#2), nie wygenerowano pliku XML ({$resultsPart})");
  2499. return null;
  2500. }
  2501. $xmlRoot = "RelatedFeatureRoot";
  2502. $return = V::arrayToXML($this->items_results[$resultsPart], true, $xmlRoot);
  2503. self::saveToLog("Wygenerowano plik XML ({$resultsPart})");
  2504. return $return;
  2505. }
  2506. public function asArray($resultsPart = null, $subArray = null) {
  2507. if (!$this->results) return null;
  2508. if (!$this->items_results[$resultsPart]) $this->generateItemsResults($resultsPart);
  2509. if (!$this->items_results[$resultsPart]) return null;
  2510. if ($subArray) {
  2511. if (isset($this->items_results[$resultsPart][$subArray])) return $this->items_results[$subArray];
  2512. else return [];
  2513. } else return $this->items_results[$resultsPart];
  2514. }
  2515. public function powiazaniaFound() {
  2516. if ($this->results) return true;
  2517. else return false;
  2518. }
  2519. public function generatePdfAndHtml() {
  2520. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  2521. if (!file_exists($antDir)) mkdir($antDir, 0770, true);
  2522. if (!is_dir($antDir)) {
  2523. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików PDF i HTML";
  2524. self::saveToLog("Nie wygenerowano plików PDF oraz HTML - problem z utworzeniem katalogu dla ant ({$resultsPart})");
  2525. $this->saveProgress(['reportsCreated' => 1]);
  2526. return;
  2527. }
  2528. $this->saveProgress(['step' => 'reports']);
  2529. if ($this->getPartsCount()) {
  2530. self::saveToLog("Generuję raporty w plikach PDF oraz HTML (liczba raportów do wygenerowania: {$this->getPartsCount()})");
  2531. for ($i =0; $i < $this->getPartsCount(); $i++) $this->_generatePdfAndHtml($i);
  2532. self::saveToLog("Zakończono generowanie raportów w plikach PDF oraz HTML");
  2533. } else $this->_generatePdfAndHtml();
  2534. }
  2535. private function _generatePdfAndHtml($resultsPart = null) {
  2536. $id_part = $resultsPart === null ? $this->ID : $this->ID . "_" . str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  2537. self::saveToLog("Generuję raport w pliku PDF oraz HTML ({$resultsPart})");
  2538. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.xml";
  2539. $pdfDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.pdf";
  2540. $htmlDestDir = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.html";
  2541. $htmlZipDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.zip";
  2542. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  2543. $antXmlFilename = "relations-{$id_part}.out_task.dita.final_with_RelatedFeatureLoop.xml";
  2544. $antXmlFile = $antDir . "/" . $antXmlFilename;
  2545. $ditamapFile = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}/relations-{$id_part}.ditamap";
  2546. $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";
  2547. $htmlDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}/html";
  2548. if (!file_exists($xmlFile)) $this->saveXml($resultsPart);
  2549. if (!file_exists($xmlFile)) {
  2550. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików XML, PDF i HTML";
  2551. self::saveToLog("Nie wygenerowano plików XML, PDF oraz HTML - problem z wygenerowaniem pliku XML ({$resultsPart})");
  2552. $this->saveProgress(['reportsCreated' => 1]);
  2553. return;
  2554. }
  2555. $this->saveProgress(['reportsCreated' => 0.05]);
  2556. copy($xmlFile, $antXmlFile);
  2557. self::saveToLog("Generuję plik przejściowy do wygenerowania plików PDF i HTML ({$resultsPart})");
  2558. 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}");
  2559. if (file_exists($ditamapFile))
  2560. {
  2561. self::saveToLog("Wygenerowano plik przejściowy");
  2562. $this->saveProgress(['reportsCreated' => 0.15]);
  2563. } else {
  2564. self::saveToLog("Nie udało się wygenerować pliku przejściowego, przerywm");
  2565. $this->saveProgress(['reportsCreated' => 1]);
  2566. return;
  2567. }
  2568. self::saveToLog("Generuję plik PDF ({$resultsPart})");
  2569. 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");
  2570. if (file_exists($pdfFile)) {
  2571. rename($pdfFile, $pdfDestFile);
  2572. self::saveToLog("Wygenerowano plik PDF ({$resultsPart})");
  2573. } else self::saveToLog("Nie udało się wygenerować pliku PDF ({$resultsPart})");
  2574. $this->saveProgress(['reportsCreated' => 0.45]);
  2575. self::saveToLog("Generuję pliki HTML ({$resultsPart})");
  2576. 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");
  2577. if (file_exists($htmlDir) && is_dir($htmlDir)) {
  2578. 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");
  2579. if (file_exists($htmlDestDir)) self::exec("rm -rf \"{$htmlDestDir}\"");
  2580. self::exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
  2581. self::saveToLog("Wygenerowano pliki HTML ({$resultsPart})");
  2582. } else self::saveToLog("Nie udało się wygenerować plików HTML {$resultsPart})");
  2583. $this->saveProgress(['reportsCreated' => 0.35]);
  2584. }
  2585. }