| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798 |
- <?php
- //TODO optimal - akcja aby doruzcic do pracownikow do analizy jakas spolke z kontekstu przegladania KRS - zapytanie przyklad:
- // insert ignore into BI_audit_ENERGA_PRACOWNICY (imiona, nazwisko, pesel, source )
- // select p.imiona, p.nazwisko, p.pesel, 'ENSO_STORA/zadanie' from `BI_audit_KRS_person` as p
- // right join `CRM__#REF_TABLE__12` as r on r.`REMOTE_PRIMARY_KEY`=p.ID
- // right join BI_audit_KRS as k on k.ID=r.`PRIMARY_KEY`
- // where k.`nazwa` like '%Stora%enso%';
- //serwisowy skrypt jest tutaj pod nazwa xyz.
- //TODO mozliwosc przerwania przetwarzania
- Lib::loadClass('RouteBase');
- Lib::loadClass('FoldersConfig');
- Lib::loadClass('FileUploader');
- Lib::loadClass('ProcesHelper');
- Lib::loadClass('SchemaFactory');
- Lib::loadClass('Core_AclHelper');
- Lib::loadClass('Core_AclSimpleSchemaBase');
- class Route_UrlAction_BiAuditGenerate extends RouteBase {
- private $powiazanie = null;
- private $SOURCE = null;
- private $REFERER;
- public function handleAuth() {
- if (!User::logged()) {
- User::authByRequest();
- }
- }
- private static function getDirectory($table, $id) {
- $folderConf = FoldersConfig::getAll($table.'_COLUMN');
- $record = new stdClass;
- $record->ID = $id;
- $uploader = new FileUploader($table.'_COLUMN', $record);
- $errMsg = "";
- if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
- $uploader->findFolder();
- return $uploader->getDestLocalPath(true);
- }
- private static function getUrl($table, $id) {
- $folderConf = FoldersConfig::getAll($table.'_COLUMN');
- $record = new stdClass;
- $record->ID = $id;
- $uploader = new FileUploader($table.'_COLUMN', $record);
- $errMsg = "";
- if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
- return $uploader->getFolderWeb() . "/" . $uploader->getDestFolder(true);
- }
- private static function getMainDirectory() {
- $folderConf = FoldersConfig::getAll('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_COLUMN');
- if (!isset($folderConf['mount_point'])) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
- return $folderConf['mount_point'];
- }
- private static function parseNipRegon($string) {
- $nip = null; $regon = null;
- preg_match('/^(.*[^[:digit:]])?([[:digit:]]{10})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
- if (!empty($matches[2])) $nip = trim($matches[2]);
- if ($nip && !V::isNip($nip)) $nip = null;
- preg_match('/^(.*[^[:digit:]])?([[:digit:]]{9})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
- if (!empty($matches[2])) $regon = trim($matches[2]);
- if ($regon && !V::isRegon($regon)) $regon = null;
- return [$nip, $regon];
- }
- private function initializePowiazaniaForm() {
- ?>
- <div class="container" style="margin-top:20px">
- <form class="form-horizontal" method="post">
- <legend>
- Generowanie powiązań :: <?=$this->powiazanie['L_APPOITMENT_INFO']?>
- <span class="pull-right"># <?=$this->powiazanie['ID']?></span>
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <h4>Wybierz pracowników, dla których mają zostać wyszukane powiązania</h4>
- <table class="table table-bordered table-hover table-striped" height=5>
- <thead>
- <tr style="text-align:center; background-color:lightgray">
- <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
- <td width=1>ID</td>
- <td>Imiona</td>
- <td>Nazwisko</td>
- <td>Pesel</td>
- <td>NIP</td>
- <td>Regon</td>
- <td>source</td>
- </tr>
- </thead>
- <tbody>
- <?php
- $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
- $queryFeatures = $acl->buildQuery(['limit' => 0]);
- $pracownicy = $queryFeatures->getItems();
- foreach ($pracownicy as $pracownik) {
- ?>
- <tr>
- <td><input type="checkbox" name="prID[]" value="<?=$pracownik['ID']?>" onClick="toggle(this)"/></td>
- <td align="right"><?=$pracownik['ID']?></td>
- <td><?=$pracownik['imiona']?></td>
- <td><?=$pracownik['nazwisko']?></td>
- <td><?=$pracownik['pesel']?></td>
- <td><?=$pracownik['nip']?></td>
- <td><?=$pracownik['regon']?></td>
- <td><?=$pracownik['source']?></td>
- </tr>
- <?php
- }
- ?>
- </tbody>
- </table>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-2 control-label">
- Odśwież cache
- </label>
- <div class="col-sm-2">
- <select name="reloadCache" class="form-control">
- <option value="No" selected>Nie</option>
- <!-- <option value="Part">Częściowe</option>-->
- <option value="Full">Pełne</option>
- </select>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-offset-2 col-sm-10">
- <!-- Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>-->
- Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów.<br/>
- Uwaga! Jeżeli aktywne są inne zadania, te zadanie zostanie wstrzymane do momentu ich ukończenia.
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <div class="containter" style="text-align:center">
- <button type="submit" class="btn btn-primary" name="action" value="initialize">Generuj</button>
- <a href="<?=$this->REFERER?>" class="btn btn-default">Anuluj</a>
- </div>
- </div>
- </div>
- <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
- </form>
- </div>
- <script language="JavaScript">
- <!--
- function toggleAll(source) {
- checkboxes = document.getElementsByName('prID[]');
- for(var i=0, n=checkboxes.length;i<n;i++) checkboxes[i].checked = source.checked;
- }
- function toggle(source) {
- checkboxes = document.getElementsByName('prID[]');
- all = true;
- for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked == false) all = false;
- source.form['checkAll'].checked = all;
- }
- -->
- </script>
- <?php
- }
- private function initializePowiazaniaSave() {
- $prID = V::get('prID', array(), $_POST);
- if (!$prID) throw new Exception("Nie wybrano żadnego pracownika!");
- $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
- $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
- $kontrahenci = $queryFeatures->getItems();
- $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_KW_requested_person/BI_audit_KW_requested_person');
- $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
- $requestedPersons = $queryFeatures->getItems();
- if (!($kontrahenci || $requestedPersons)) throw new Exception("Nie znaleziono żadnego obiektu końcowego");
- $sqlUpdate = ['FILE_STATUS' => 'TO_GENERATE'];
- $reloadCache = V::get('reloadCache', 'No', $_POST);
- $reloadCacheAvailable = ['Full', 'Part', 'No'];
- if (!in_array($reloadCache, $reloadCacheAvailable)) throw new Exception("Błąd formularza!");
- $sqlUpdate['BI_analiza_reloadCache'] = $reloadCache;
- $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part')";
- $result = DB::getPDO()->fetchValue($query);
- if ($result) $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache (wymagane dla innego rekordu)';
- elseif ($reloadCache != 'No') $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache';
- else $sqlUpdate['FILE_STATUS_info'] = "Oczekuje na wygenerowanie powiązań";
- if ($this->powiazanie) { // wyzwolone z poziomu tabeli BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA - aktualizujemy istniejący rekord
- $powiazanieID = $this->powiazanie['ID'];
- } else { // wyzwolone z poziomu tabeli BI_audit_ENERGA_PRACOWNICY - dodajemy nowy rekord
- if (count($prID) != 1) throw new Exception("Błąd formularza!");
- if (!($lAppoitmentInfo = V::get('info', false, $_POST))) throw new Exception("Błąd formularza!");
- if (!($BiAnalizaMinDepth = V::get('minDepth', false, $_POST))) throw new Exception("Błąd formularza!");
- if (!($BiAnalizaMaxDepth = V::get('maxDepth', false, $_POST))) throw new Exception("Błąd formularza!");
- if (!($BiAnalizaOnlyTargets = V::get('onlyTargets', false, $_POST))) throw new Exception("Błąd formularza!");
- $query = "select * from BI_audit_ENERGA_PRACOWNICY where ID='{$prID[0]}'";
- $result = DB::getPDO()->fetchFirst($query);
- if (!$result) throw new Exception("Błąd formularza!");
- $sqlInsert = [
- 'L_APPOITMENT_INFO' => $lAppoitmentInfo,
- 'A_STATUS' => 'NORMAL',
- 'A_STATUS_INFO' => 'Dodane przez BiAuditGenerate z poziomu tabeli BI_audit_ENERGA_PRACOWNICY',
- 'A_ADM_COMPANY' => $result['A_ADM_COMPANY'],
- 'A_CLASSIFIED' => $result['A_CLASSIFIED'],
- 'FILE_STATUS' => 'NONE',
- 'FILE_STATUS_info' => 'Oczekuję na zdefiniowanie danych wejściowych',
- 'BI_analiza_reloadCache' => $sqlUpdate['BI_analiza_reloadCache'],
- 'BI_analiza_minDepth' => $BiAnalizaMinDepth,
- 'BI_analiza_maxDepth' => $BiAnalizaMaxDepth,
- 'BI_analiza_onlyTargets' => $BiAnalizaOnlyTargets,
- ];
- $powiazanieID = DB::getDB()->ADD_NEW_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', (object)$sqlInsert);
- if ($powiazanieID) SE_Layout::alert('success','Dodano rekord do wygenerowania powiązań');
- else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
- }
- $sqlUpdate['ID'] = $powiazanieID;
- self::truncatePowiazaniaFromDB($powiazanieID);
- $refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
- foreach ($prID as $v) DB::getPDO()->insert($refPowiazaniaToPracownicy, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $v]);
- $refPowiazaniaToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
- foreach ($kontrahenci as $kontrahent) DB::getPDO()->insert($refPowiazaniaToKontrahenci, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $kontrahent['ID']]);
- $refPowiazaniaToKwRequestedPreson = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_KW_requested_person', true);
- foreach ($requestedPersons as $requestedPerson) DB::getPDO()->insert($refPowiazaniaToKwRequestedPreson, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $requestedPerson['ID']]);
- $affected = DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlUpdate);
- if ($affected) {
- if ($this->powiazanie) {
- SE_Layout::alert('success','Oznaczono rekord do wygenerowania powiązań');
- ?>
- <div class="container" style="text-align:center">
- <a href="<?=$this->REFERER?>" class="btn btn-primary">Powrót</a>
- </div>
- <?php
- }
- } else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
- }
- private function initializePowiazania() {
- switch (V::get('action', '', $_POST)) {
- case "initialize":
- $this->initializePowiazaniaSave();
- break;
- default:
- $this->initializePowiazaniaForm();
- }
- }
- private function showPowiazania() {
- // echo "Statystyki znalezionych powiązań [TODO]";
- $dir = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
- $url = self::getUrl('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
- $reports = [
- 'pdf' => [
- 'files' => glob("{$dir}/relations*.pdf"),
- 'label' => 'Raporty PDF:<br/> ',
- 'button' => 'Pokaż raport PDF',
- 'regex' => "/^relations(-{$this->powiazanie['ID']})?_([[:digit:]]+)\.pdf$/",
- 'parentDir' => false,
- ],
- 'html' => [
- 'files' => glob("{$dir}/html*/relations-{$this->powiazanie['ID']}*.html"),
- 'label' => 'Raporty HTML<br/>do przeglądania:',
- 'button' => 'Pokaż raport HTML',
- 'regex' => "/^relations-({$this->powiazanie['ID']})_([[:digit:]]+)\.html$/",
- 'parentDir' => true,
- ],
- 'htmlZip' => [
- 'files' => glob("{$dir}/html*.zip"),
- 'label' => 'Raporty HTML<br/>do pobrania:',
- 'button' => 'Pobież raport HTML',
- 'regex' => "/^html(-{$this->powiazanie['ID']})?_([[:digit:]]+)\.zip$/",
- 'parentDir' => false,
- ],
- ];
- ?>
- <div class="container" style="margin-top:20px">
- <legend>
- Wygenerowany raport nr <?=$this->powiazanie['ID']?>
- </legend>
- <div class="form-group" style="text-align: center;">
- <?php
- array_walk($reports, function ($report) use ($url) {
- echo "<div class=\"col-sm-2\"><h4>{$report['label']}</h4>";
- $hrefs = array_filter(array_map(function ($path) use ($url, $report) {
- if (!is_file($path)) return false;
- $file = basename($path);
- if (preg_match($report['regex'], $file, $matches)) $i = " (" . ltrim($matches[2], '0') . ")";
- else $i = '';
- if ($report['parentDir']) $file = basename(dirname($path)) . "/" . $file;
- return "<a href=\"{$url}/{$file}\" target=\"_blank\" class=\"btn btn-primary\">{$report['button']}{$i}</a>";
- }, $report['files']));
- if ($hrefs) echo implode('<br/><br/>', $hrefs);
- else echo "<h5>Nie znaleziono</h5>";
- echo "</div>\n";
- });
- ?>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <br/><br/><a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
- </div>
- </div>
- </div>
- <?php
- }
- private function showPowiazaniaList() {
- switch (V::get('action', '', $_POST)) {
- case "initialize":
- $this->initializePowiazaniaSave();
- break;
- }
- $this->showPowiazaniaListForm();
- }
- private function showPowiazaniaListForm() {
- if (!$this->SOURCE['ID']) throw new Exception("Błąd danych");
- elseif ($this->SOURCE['TABLE'] != 'BI_audit_ENERGA_PRACOWNICY') throw new Exception("Błąd danych");
- $query = "select * from `{$this->SOURCE['TABLE']}` where ID = '{$this->SOURCE['ID']}'";
- $pracownik = DB::getPDO()->fetchFirst($query);
- if (!$pracownik) throw new Exception("Błąd danych");
- ?>
- <div class="container" style="margin-top:20px">
- <legend>
- Lista wygenerowanych powiązań :: <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>
- <span class="pull-right"># <?=$pracownik['ID']?></span>
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <h4>Lista wygenerowanych powiązań, w których znajduje się pracownik</h4>
- <table class="table table-bordered table-hover table-striped" height=5>
- <thead>
- <tr style="text-align:center; background-color:lightgray">
- <td width=1>ID</td>
- <td>Adnotacje</td>
- <td>Minimalna głębokość analizy</td>
- <td>Maksymalna głębokość analizy</td>
- <td>Powiązania tylko do celów</td>
- <td>Status raportu</td>
- <td>Status raportu - informacje</td>
- <td>Indywidualny raport</td>
- <td width=1></td>
- </tr>
- </thead>
- <tbody>
- <?php
- $refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
- $query = "select `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.*
- from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
- join `{$refPowiazaniaToPracownicy}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPracownicy}`.`PRIMARY_KEY`
- where `REMOTE_PRIMARY_KEY` = '{$this->SOURCE['ID']}'";
- $result = DB::getPDO()->fetchAll($query);
- if (!$result) echo '<tr><td align="center" colspan="9">Brak znalezionych powiązań</td></tr>';
- else {
- foreach ($result as $row) {
- $query = "select count(*) from `{$refPowiazaniaToPracownicy}` where `PRIMARY_KEY` = '{$row['ID']}'";
- $count = DB::getPDO()->fetchValue($query);
- ?>
- <tr>
- <td align="right"><?=$row['ID']?></td>
- <td><?=$row['L_APPOITMENT_INFO']?></td>
- <td><?=$row['BI_analiza_minDepth']?></td>
- <td><?=$row['BI_analiza_maxDepth']?></td>
- <td><?=($row['BI_analiza_onlyTargets'] == 'N' ? "Nie" : "Tak")?></td>
- <td><?=$row['FILE_STATUS']?></td>
- <td><?=$row['FILE_STATUS_info']?></td>
- <td><?=($count > 1 ? 'Nie' : 'Tak')?></td>
- <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>
- </tr>
- <?php
- }
- }
- ?>
- </tbody>
- </table>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <h4>Dodaj nowe zadanie generowania powiazań dla tego pracownika</h4>
- </div>
- </div>
- <form class="form-horizontal" method="post">
- <div class="form-group">
- <label class="col-sm-4 control-label">Minimalna głębokość poszukiwań (liczba rekurencji)</label>
- <div class="col-sm-1">
- <input type="number" class="form-control" name="minDepth" id="minDepth" data-bind="value:replyNumber" min="1" max="9" value="1" required/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-4 control-label">Maksymalna głębokość poszukiwań (liczba rekurencji)</label>
- <div class="col-sm-1">
- <input type="number" class="form-control" name="maxDepth" id="maxDepth" data-bind="value:replyNumber" min="1" max="9" value="6" required/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-4 control-label">Czy zwracać tylko wyniki ze znalezionymi obiektami docelowymi (z tabeli kontrahentów)?</label>
- <div class="col-sm-1">
- <select name="onlyTargets" class="form-control">
- <option value="Y" selected>Tak</option>
- <option value="N">Nie</option>
- </select>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-4 control-label">Adnotacje</label>
- <div class="col-sm-4">
- <input type="text" class="form-control" name="info" value="Indywidualnie dla <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>" required/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-4 control-label">
- Odśwież cache
- </label>
- <div class="col-sm-2">
- <select name="reloadCache" class="form-control">
- <option value="No" selected>Nie</option>
- <!-- <option value="Part">Częściowe</option>-->
- <option value="Full">Pełne</option>
- </select>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-offset-4 col-sm-8">
- <!-- Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>-->
- Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów.<br/>
- Uwaga! Jeżeli aktywne są inne zadania, te zadanie zostanie wstrzymane do momentu ich ukończenia.
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <div class="containter" style="text-align:center">
- <button type="submit" class="btn btn-primary" name="action" value="initialize" onClick="return validate()">Generuj</button>
- <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
- </div>
- </div>
- </div>
- <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
- <input type="hidden" name="prID[]" value="<?=$pracownik['ID']?>">
- </form>
- </div>
- <script language="JavaScript">
- <!--
- function validate() {
- result = (document.getElementById('minDepth').value <= document.getElementById('maxDepth').value);
- if (!result) alert('Wartość minimalnej głębokości analizy nie może być większa od wartości maksymalnej głębokości analizy!');
- return result;
- }
- -->
- </script>
- <?php
- }
- private function powiazania() {
- try {
- if (!$this->SOURCE) throw new Exception("Błąd danych");
- elseif (!(isset($this->SOURCE['TABLE']) && isset($this->SOURCE['ID']))) throw new Exception("Błąd danych");
- switch ($this->SOURCE['TABLE']) {
- case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
- $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->SOURCE['ID']}'");
- if (!$powiazania) throw new Exception("Błąd danych");
- $this->powiazanie = $powiazania[0];
- switch ($this->powiazanie['FILE_STATUS']) {
- case "NONE":
- $this->initializePowiazania();
- break;
- case "GENERATED":
- $this->showPowiazania();
- break;
- default: throw new Exception("Błędny status rekordu");
- }
- break;
- case "BI_audit_ENERGA_PRACOWNICY":
- $this->showPowiazaniaList();
- break;
- case "BI_audit_KRS":
- $this->importKrsToPracownicySearch($this->SOURCE['ID']);
- break;
- case "BI_audit_KRS_person":
- $this->showKrsForKrsPerson();
- break;
- default: throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate");
- }
- } catch (Exception $e) {
- SE_Layout::alert('danger',$e->getMessage());
- $_SESSION['REFERER'] = $this->REFERER;
- ?>
- <div class="container" style="text-align:center">
- <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
- </div>
- <?php
- }
- }
- private function importKrsToPracownicy() {
- $action = V::get('action', '', $_POST);
- switch ($action) {
- case "search":
- $this->importKrsToPracownicySearch();
- break;
- default: $this->importKrsToPracownicyForm();
- }
- }
- private function importKrsToPracownicyForm() {
- ?>
- <div class="container" style="margin-top:20px">
- <legend>
- Importowanie podmiotów z KRS do tabel kontrahentów i pracowników
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <h4>Znajdź podmiot</h4>
- </div>
- </div>
- <form class="form-horizontal" method="post">
- <div class="form-group">
- <label class="col-sm-1 control-label">Nazwa</label>
- <div class="col-sm-4">
- <input type="text" class="form-control" name="nazwa" title="Podaj nazwę podmiotu">
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-1 control-label">KRS</label>
- <div class="col-sm-2">
- <input type="text" class="form-control" name="krs" pattern="^[0-9]{0,10}$" title="Podaj KRS"/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-1 control-label">NIP</label>
- <div class="col-sm-2">
- <input type="text" class="form-control" name="nip" pattern="^[0-9]{0,10}$" title="Podaj NIP (bez kresek i bez oznaczenia kraju)"/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-1 control-label">Regon</label>
- <div class="col-sm-2">
- <input type="text" class="form-control" name="regon" pattern="^[0-9]{0,9}$" title="Podaj regon"/>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-offset-1 col-sm-11">
- <button type="submit" class="btn btn-primary" name="action" value="search">Szukaj</button>
- <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
- </div>
- </div>
- </form>
- </div>
- <?php
- }
- private function importKrsToPracownicySearch($krsId = null) {
- $formItems = [
- "nazwa" => 'like',
- "krs" => '=',
- "nip" => '=',
- "regon" => '=',
- ];
- try {
- $subaction = V::get('subaction', '', $_POST);
- switch ($subaction) {
- case "listKrsPerson":
- $krsId = V::get('krsId', 0, $_POST, int);
- break;
- case "addKrsPersonToPracownicy":
- $krsId = V::get('krsId', 0, $_POST, int);
- $personId = V::get('personId', [], $_POST);
- if (!$personId) throw new Exception("Błąd formularza");
- $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) . ")";
- DB::getPDO()->query($query);
- SE_Layout::alert('success', "Pomyślnie zaimportowano " . count($personId) . " pracownik" . ((count($personId) == 1) ? "a" : "ów"));
- break;
- case "addKrsToKontrahenci":
- $krsId = V::get('krsId', 0, $_POST, int);
- if (!$krsId) throw new Exception("Błąd formularza");
- $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}'";
- $kontrahentExists = DB::getPDO()->fetchValue($query);
- if ($kontrahentExists) throw new Exception("Podmiot znajduje się już w tabeli kontrahentów");
- $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." ";
- DB::getPDO()->query($query);
- SE_Layout::alert('success', "Pomyślnie zaimportowano kontrahenta");
- break;
- }
- if ($krsId) {
- $where = ["ID = '{$krsId}'"];
- } else {
- $form = [];
- foreach ($formItems as $item => $type) {
- if ($param = V::get($item, '', $_POST)) {
- if ($type == 'like') $param = "%{$param}%";
- $form[$item] = DB::getPDO()->quote($param);
- }
- }
- if (!$form) throw new Exception("Nie wypełniono żadnego pola wyszukiwania!");
- $where = [];
- foreach ($form as $name => $value) $where[] = "`{$name}` {$formItems[$name]} {$value}";
- }
- } catch (Exception $e) {
- SE_Layout::alert('danger', $e->getMessage());
- $this->importKrsToPracownicyForm();
- return;
- }
- $query = "select * from `BI_audit_KRS` where " . implode(" and ", $where) . "order by ID limit 1001";
- $result = DB::getPDO()->fetchAll($query);
- if (count($result) == 1001) {
- SE_Layout::alert('danger', 'Znaleziono zbyt wiele wyników. Doprecyzuj parametry wyszukiwania.');
- $this->importKrsToPracownicyForm();
- return;
- } elseif (count($result) == 1) {
- $krsId = $result[0]['ID'];
- }
- ?>
- <div class="container" style="margin-top:20px">
- <form method="post">
- <legend>
- Importowanie podmiotów z KRS do tabel kontrahentów i pracowników
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <h4>Znalezione podmioty:</h4>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <table class="table table-bordered table-hover table-striped" height=5>
- <thead>
- <tr style="text-align:center; background-color:lightgray">
- <td width=1>Lp.</td>
- <td>Nazwa</td>
- <td>Adres</td>
- <td>KRS</td>
- <td>NIP</td>
- <td>Regon</td>
- <?php
- if (count($result) > 1) {
- ?>
- <td width=1>Wybierz</td>
- <?php
- }
- ?>
- </tr>
- </thead>
- <tbody>
- <?php
- if (!$result) echo '<tr><td align="center" colspan="6">Nie znaleziono podmiotu</td></tr>';
- else {
- $lp = 1;
- foreach ($result as $row) {
- $adres = $row['A_miejscowosc'];
- if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
- if ($row['A_nrDomu']) {
- $adres .= " {$row['A_nrDomu']}";
- if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
- }
- ?>
- <tr>
- <td align="right"><?=$lp++?></td>
- <td><?=htmlspecialchars($row['nazwa'])?></td>
- <td><?=htmlspecialchars($adres)?></td>
- <td><?=$row['krs']?></td>
- <td><?=$row['nip']?></td>
- <td><?=$row['regon']?></td>
- <?php
- if (count($result) > 1) {
- ?>
- <td align="center">
- <input type="radio" name="krsId" value="<?=$row['ID']?>"/>
- </td>
- <?php
- }
- ?>
- </tr>
- <?php
- }
- }
- ?>
- </tbody>
- </table>
- </div>
- </div>
- <?php
- if (count($result) > 1) {
- ?>
- <div class="form-group">
- <div class="col-sm-12">
- <?php
- foreach (array_keys($formItems) as $item) {
- ?>
- <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
- <?php
- }
- ?>
- <input type="hidden" name="back" value="search"/>
- <div class="containter" style="text-align:center">
- <button type="submit" class="btn btn-primary" name="subaction" value="listKrsPerson" onClick="return validateCompany(this)">Wybierz zaznaczony podmiot</button>
- <a href="" class="btn btn-default">Powrót</a>
- </div>
- </div>
- </div>
- <?php
- } elseif ($krsId) {
- ?>
- <div class="form-group">
- <div class="col-sm-12">
- <h4>Znalezione osoby:</h4>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <table class="table table-bordered table-hover table-striped" height=5>
- <thead>
- <tr style="text-align:center; background-color:lightgray">
- <td width=1>Lp.</td>
- <td>Nazwisko</td>
- <td>Imiona</td>
- <td>Pesel</td>
- <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
- </tr>
- </thead>
- <tbody>
- <?php
- $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}'";
- $kontrahentExists = DB::getPDO()->fetchValue($query);
- $refKrsToKrsPerson = BiAuditRefTables::getRefTable('BI_audit_KRS', 'BI_audit_KRS_person', true);
- $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}'";
- $result = DB::getPDO()->fetchAll($query);
- if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono osób powiązanych z podmiotem</td></tr>';
- else {
- $lp = 1;
- foreach ($result as $row) {
- ?>
- <tr<?=($row['pracownicyId'] ? ' style="color:darkgrey"' : '')?>>
- <td align="right"><?=$lp++?></td>
- <td><?=$row['nazwisko']?></td>
- <td><?=$row['imiona']?></td>
- <td><?=$row['pesel']?></td>
- <td><input type="checkbox" name="personId[]" value="<?=$row['ID']?>" onClick="toggle(this)" <?=($row['pracownicyId'] ? "disabled" : "")?>/></td>
- </tr>
- <?php
- }
- }
- ?>
- </tbody>
- </table>
- </div>
- </div>
- <!-- <div class="form-group">
- <div class="col-sm-12">
- <label class="col-sm-4 control-label">Opis/źródło</label>
- <div class="col-sm-4">
- <input type="text" class="form-control" name="source" placeholder="KRS"/>
- </div>
- </div>
- </div>-->
- <div class="form-group">
- <div class="col-sm-12" style="text-align: center;">
- <button type="submit" class="btn btn-primary" name="subaction" value="addKrsToKontrahenci"<?=($kontrahentExists ? " disabled" : "")?>>Dodaj firmę do tabeli kontrahentów</button>
- <button type="submit" class="btn btn-primary" name="subaction" value="addKrsPersonToPracownicy" onClick="return validatePerson(this)">Dodaj zaznaczone osoby do tabeli pracowników</button>
- <input type="hidden" name="krsId" value="<?=$krsId?>"/>
- <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
- <?php
- if (V::get('back', '', $_POST) == 'search') {
- foreach (array_keys($formItems) as $item) {
- ?>
- <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
- <?php
- }
- ?>
- <button type="submit" class="btn btn-default" name="action" value="search">Powrót</button>
- <?php
- } else {
- ?>
- <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
- <?php
- }
- ?>
- </div>
- </div>
- <?php
- }
- ?>
- <input type="hidden" name="action" value="search">
- </form>
- </div>
- <script language="JavaScript">
- <!--
- function toggleAll(source) {
- checkboxes = document.getElementsByName('personId[]');
- checked = false;
- for(var i=0, n=checkboxes.length;i<n;i++) {
- if (!checkboxes[i].disabled) {
- checkboxes[i].checked = source.checked;
- checked = true;
- }
- }
- if (source.checked && (!checked)) source.checked = false;
- }
- function toggle(source) {
- checkboxes = document.getElementsByName('personId[]');
- all = true;
- for(var i=0, n=checkboxes.length;i<n;i++) if(!checkboxes[i].disabled && checkboxes[i].checked == false) all = false;
- source.form['checkAll'].checked = all;
- }
- function validatePerson(source) {
- checkboxes = document.getElementsByName('personId[]');
- checked = false;
- for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked) checked = true;
- if (!checked) alert('Nie wybrano żadnej osoby!');
- return checked;
- }
- function validateCompany(source) {
- radios = document.getElementsByName('krsId');
- checked = false;
- for(var i=0, n=radios.length;i<n;i++) if(radios[i].checked) checked = true;
- if (!checked) alert('Nie wybrano żadnej firmy!');
- return checked;
- }
- -->
- </script>
- <?php
- }
- private function showKrsForKrsPerson() {
- $query = "select * from BI_audit_KRS_person where ID = '{$this->SOURCE['ID']}'";
- $result = DB::getPDO()->fetchFirst($query);
- ?>
- <div class="container" style="margin-top:20px">
- <legend>
- Lista podmiotów, w których występuje <?="{$result['nazwisko']} {$result['imiona']}" . ($result['pesel'] ? " (PESEL: {$result['pesel']})" : "")?>
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <table class="table table-bordered table-hover table-striped" height=5>
- <thead>
- <tr style="text-align:center; background-color:lightgray">
- <td width=1>Lp.</td>
- <td>Nazwa</td>
- <td>Adres</td>
- <td>KRS</td>
- <td>NIP</td>
- <td>Regon</td>
- <td width=1></td>
- </tr>
- </thead>
- <tbody>
- <?php
- $refKrsToKrsPerson = BiAuditRefTables::getRefTable('BI_audit_KRS', 'BI_audit_KRS_person', true);
- $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']}'";
- $result = DB::getPDO()->fetchAll($query);
- if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono powiązanych podmiotów</td></tr>';
- else {
- $lp = 1;
- foreach ($result as $row) {
- $adres = $row['A_miejscowosc'];
- if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
- if ($row['A_nrDomu']) {
- $adres .= " {$row['A_nrDomu']}";
- if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
- }
- ?>
- <tr>
- <td align="right"><?=$lp++?></td>
- <td><?=htmlspecialchars($row['nazwa'])?></td>
- <td><?=htmlspecialchars($adres)?></td>
- <td><?=$row['krs']?></td>
- <td><?=$row['nip']?></td>
- <td><?=$row['regon']?></td>
- <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>
- </tr>
- <?php
- }
- }
- ?>
- </tbody>
- </table>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <div class="containter" style="text-align:center">
- <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-default">Powrót</a>
- </div>
- </div>
- </div>
- </div>
- <?php
- }
- public function defaultAction() {
- SE_Layout::gora();
- SE_Layout::menu();
- if (isset($_SESSION['REFERER'])) {
- $this->REFERER = $_SESSION['REFERER'];
- unset($_SESSION['REFERER']);
- } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
- else $this->REFERER=$_SERVER['HTTP_REFERER'];
- if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
- elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
- elseif (($ID = V::get('ID_BI_audit_KRS', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS';
- elseif (($ID = V::get('ID_BI_audit_KRS_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS_person';
- if ($this->SOURCE) {
- $this->SOURCE['ID'] = $ID;
- $this->powiazania();
- }
- elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
- switch ($TABLE) {
- case "default_db/BI_audit_ENERGA_PRACOWNICY":
- $this->importKrsToPracownicy();
- break;
- default: SE_Layout::alert('danger', 'Błąd parametru');
- }
- }
- else SE_Layout::alert('danger', 'Błąd parametru');
- SE_Layout::dol();
- }
- private static function truncatePowiazaniaFromDB($ID) {
- $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
- if (!$refTables) return null;
- $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
- $refTables = array_diff($refTables, [$refPowiazaniaToPowiazaniaRow]);
- $query = "delete from `" . implode("`, `", $refTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
- foreach ($refTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
- $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
- DB::getPDO()->query($query);
- }
- private static function deleteResultsFromDB($ID) {
- $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
- $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
- $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
- $sqlDeleteFrom = "delete from
- `{$refPowiazaniaToPowiazaniaRow}`,
- `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
- `{$refPowiazaniaRowToPowiazaniaRowObject}`,
- `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
- $sqlUsing = "
- using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
- join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
- join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
- join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
- join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
- $sqlWhere = "
- where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
- foreach ($refTables as $refTable) {
- $sqlDeleteFrom .= ",\n`{$refTable}`";
- $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
- }
- $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
- DB::getPDO()->query($query);
- }
- public function doGenerate() {
- $generatePhpScript = function($function) {
- return '<?php
- ini_set("memory_limit", "4G");
- define("DS", DIRECTORY_SEPARATOR);
- define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
- define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
- define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
- ini_set("display_startup_errors", "0");
- ini_set("display_errors", "1");
- ini_set("log_errors", "1");
- ini_set("error_log", "/var/log/apache2/error_log");
- $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
- require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
- date_default_timezone_set("Europe/Warsaw");
- Lib::loadClass("Router");
- Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
- ';
- };
- try {
- ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
- $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
- ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
- $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
- if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
- ### Ustawienie zmiennych
- $powiazaniaDirLocation = self::getMainDirectory();
- $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
- $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
- $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
- $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
- $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
- ### Utworzenie niezbędnych katalogów i plików
- if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0770, true);
- if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
- ### Wyłączenie wcześniej używanego mechanizmu wymuszania częściowego odświeżania cache - teraz działa to z automatu
- $sqlArr = [
- 'BI_analiza_reloadCache' => 'No',
- ];
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Part') and FILE_STATUS = 'TO_GENERATE'";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
- }
- ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
- $doGenerate = true;
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full') and FILE_STATUS = 'TO_GENERATE'";
- $result = DB::getPDO()->fetchAll($query);
- if ($result) {
- $doGenerate = false;
- $sqlArr = [];
- if (file_exists($reloadCachePhpFile)) {
- if (file_exists($reloadCacheResultFile)) {
- $reloadCacheResult = file_get_contents($reloadCacheResultFile);
- if ($reloadCacheResult == "ok") {
- $sqlArr = [
- 'FILE_STATUS_info' => 'Ukończono pełne Odświeżenie cache, oczekiwanie na wygenerowanie powiązań',
- 'BI_analiza_reloadCache' => 'No',
- ];
- $doGenerate = true;
- } else {
- $sqlArr = [
- 'FILE_STATUS' => 'ERROR',
- 'FILE_STATUS_info' => "Wystąpił błąd podczas pełnego odświeżania cache ({$reloadCacheResult})",
- ];
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
- $result = DB::getPDO()->fetchAll($query);
- }
- unlink($reloadCachePhpFile);
- unlink($reloadCachePidFile);
- unlink($reloadCacheResultFile);
- } elseif (file_exists($reloadCachePidFile)) {
- $pid = file_get_contents($reloadCachePidFile);
- $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
- $processShouldBeRunning = "php {$reloadCachePhpFile}";
- if ($processRunning != $processShouldBeRunning) {
- if (!file_exists($reloadCacheResultFile)) {
- $sqlArr = [
- 'FILE_STATUS' => 'ERROR',
- 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas pełnego odświeżania cache - nie znaleziono procesu potomnego",
- ];
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
- $result = DB::getPDO()->fetchAll($query);
- unlink($reloadCachePhpFile);
- unlink($reloadCachePidFile);
- unlink($reloadCacheResultFile);
- }
- }
- }
- } else {
- $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
- $result2 = DB::getPDO()->fetchValue($query);
- if ($result2) {
- $sqlArr = [
- 'FILE_STATUS_info' => 'Wstrzymano pełne odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
- ];
- } else {
- $sqlArr = [
- 'FILE_STATUS_info' => 'W trakcie pełnego odświeżania cache',
- ];
- $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
- $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
- file_put_contents($reloadCachePhpFile, $generatePhpScript("doReloadCache({$fullReloadCache})"));
- shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
- }
- }
- if ($sqlArr) {
- foreach ($result as $row) {
- DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
- }
- }
- }
- ### Generowanie powiązań
- if ($doGenerate) {
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $sqlArr = [
- 'ID' => $row['ID'],
- 'FILE_STATUS' => 'IN_PROGRESS',
- 'FILE_STATUS_info' => 'W trakcie generowania powiązań',
- ];
- DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
- self::deleteResultsFromDB($row['ID']);
- $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
- $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
- $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
- $generatePowiazaniaProgressFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.progress";
- if (file_exists($generatePowiazaniaResultFile)) unlink ($generatePowiazaniaResultFile);
- if (file_exists($generatePowiazaniaProgressFile)) unlink ($generatePowiazaniaProgressFile);
- file_put_contents($generatePowiazaniaPhpFile, $generatePhpScript("doGeneratePowiazania({$row['ID']})"));
- shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
- }
- }
- ### Weryfikacja świeżo wygenerowanych powiązań
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
- $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
- $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
- $error = false;
- $success = false;
- $sqlArr = [];
- if (file_exists($generatePowiazaniaResultFile)) {
- $generatePowiazaniaResult = json_decode(file_get_contents($generatePowiazaniaResultFile), true);
- if ($generatePowiazaniaResult['result'] == "ok") {
- $powiazanieDirLocation = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
- if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0770, false);
- if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
- else $success = true;
- } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult['message']})";
- } elseif (file_exists($generatePowiazaniaPidFile)) {
- $pid = file_get_contents($generatePowiazaniaPidFile);
- $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
- $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
- if ($processRunning != $processShouldBeRunning) {
- if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
- }
- }
- if ($error) {
- $sqlArr = [
- 'FILE_STATUS' => 'ERROR',
- 'FILE_STATUS_info' => $error,
- ];
- self::deleteResultsFromDB($row['ID']);
- //if (file_exists($xmlFile)) unlink($xmlFile);
- } elseif ($success) {
- $sqlArr = [
- 'FILE_STATUS' => 'GENERATED',
- 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
- ];
- if ($generatePowiazaniaResult['parts']) {
- for ($i = 1; $i <= $generatePowiazaniaResult['parts']; $i++) {
- $partNo = str_pad($i, 6, '0', STR_PAD_LEFT);
- $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}_{$partNo}";
- $generatePowiazaniaXmlFile = "{$generateFilesName}.xml";
- $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
- $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
- $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
- $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.xml";
- $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.pdf";
- $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}";
- $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}.zip";
- if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
- if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
- if (file_exists($generatePowiazaniaHtmlDir)) {
- if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
- rename($generatePowiazaniaHtmlDir, $destHtmlDir);
- }
- if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
- }
- } else {
- $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}";
- $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
- $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
- $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
- $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.xml";
- $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.pdf";
- $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}";
- $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}.zip";
- if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
- if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
- if (file_exists($generatePowiazaniaHtmlDir)) {
- if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
- rename($generatePowiazaniaHtmlDir, $destHtmlDir);
- }
- if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
- }
- }
- if ($sqlArr) {
- $sqlArr['ID'] = $row['ID'];
- DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
- if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
- if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
- if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
- }
- }
- } catch (Exception $e) {
- echo $e->getMessage()."\n";
- }
- }
- private static function importPracownicy() { //TODO
- $fields = [
- 'BI_audit_ENERGA_PRACOWNICY' => [
- 'PERNR',
- 'imiona',
- 'nazwisko',
- 'pesel',
- 'nr_konta',
- 'jednostka_organizacyjna',
- 'nip',
- 'regon',
- 'source',
- ],
- 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
- 'kodPocztowy',
- 'miejscowosc',
- 'ulica',
- 'nrBudynku',
- 'nrLokalu',
- ],
- ];
- $query = "select * from `BI_audit_ENERGA_PRACOWNICY_import` where `importResult` = 'none'";
- $pracownicy = DB::getPDO()->query($query);
- while ($pracownik = $pracownicy->fetch()) {
- $ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `pesel` = '{$pracownik['pesel']}'");
- $sqlArr = [];
- foreach ($fields['BI_audit_ENERGA_PRACOWNICY'] as $field) $sqlArr[$field] = trim($pracownik[$field]);
- if ($ID_pracownik) DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY', 'ID', $ID, $sqlArr);
- else $ID_pracownik = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', $sqlArr);
- $sqlArr = [];
- foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $field) {
- $sqlArr[$field] = trim($pracownik[$field]);
- if (!$sqlArr[$field]) unset($sqlArr[$field]);
- }
- if (!$sqlArr) break;
- $sql = [];
- // foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $field) {
- // if (isset($sqlArr[$field])) $sql[] = "`{$field}` = " . DUPA;
- // }
- }
- }
- private static function reloadCache_parseUmowy($full = false) {
- $fields = [
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
- 'Tytul_dokumentu',
- 'Pelna_nazwa_kontrahenta',
- 'NIP',
- 'REGON',
- 'KRS',
- 'Kraj',
- 'Kod_pocztowy',
- 'Miejscowosc',
- 'Ulica',
- 'Numer_budynku',
- 'Numer_mieszkania_lokalu',
- 'TERYT_SYM',
- 'TERYT_SYM_UL',
- ],
- 'BI_audit_KRS' => [
- '"Zaimportowanoz KRS na podstawie umowy"',
- 'nazwa',
- 'nip',
- 'regon',
- 'krs',
- 'A_kraj',
- 'A_kod',
- 'A_miejscowosc',
- 'A_ulica',
- 'A_nrDomu',
- 'A_nrLokalu',
- 'TERYT_SYM',
- 'TERYT_SYM_UL',
- ],
- 'BI_audit_CEIDG' => [
- '"Zaimportowano z CEiDG na podstawie umowy"',
- 'firma',
- 'nip',
- 'regon',
- 'null',
- 'kraj',
- 'kodPocztowy',
- 'miejscowosc',
- 'ulica',
- 'budynek',
- 'lokal',
- 'TERYT_SYM',
- 'TERYT_SYM_UL',
- ],
- ];
- $refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
- if ($full) {
- DB::getPDO()->query("truncate table `{$refTable}`");
- DB::getPDO()->query("update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
- }
- $query = <<<SQL
- update `BI_audit_ENERGA_RUM_UMOWY` set `Wartosc` = replace(
- if(`Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_`,
- if(`Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_`,
- if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_`,
- if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_`,
- if(`Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_`, 0))))),
- ',', '.') where `A_STATUS` = 'WAITING';
- SQL;
- DB::getPDO()->query($query);
- $query = "select `ID`, `Strony_umowy` from `BI_audit_ENERGA_RUM_UMOWY` where `A_STATUS` = 'WAITING'";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $ID = $row['ID'];
- $strony = array_map('trim', explode("|", $row['Strony_umowy']));
- $K_IDs = [];
- foreach ($strony as $item) {
- $strona = array_map('trim', explode(";", $item));
- $nr = null;
- if (count($strona) == 3) $i = 1;//$nr = $strona[1];
- elseif (count($strona) == 4) $i = 2;//$nr = $strona[2];
- elseif (count($strona) >= 5 && count($strona) <= 6) $i = 3;//$nr = $strona[3];
- else $i = null;
- if ($i) $nr = $strona[$i];
- $notFound = false;
- if (is_numeric($nr)) {
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Numer_kontrahenta = '{$nr}'";
- if ($K_ID = DB::getPDO()->fetchValue($query)) {
- $K_IDs[] = $K_ID;
- } else {
- $nazwa = $strona[$i+1];
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Pelna_nazwa_kontrahenta = '" . addslashes($nazwa) . "'";
- if ($result2 = DB::getPDO()->fetchAll($query)) {
- foreach ($result2 as $item) $K_IDs[] = $item['ID'];
- } else $notFound = true;
- }
- } else $notFound = true;
- if ($notFound) {
- list($nip, $regon) = self::parseNipRegon($item);
- if ($nip || $regon) {
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where NIP = '{$nip}' or REGON = '{$regon}'";
- if ($result2 = DB::getPDO()->fetchall($query)) {
- foreach ($result2 as $item) $K_IDs[] = $item['ID'];
- } else {
- $query = "select ID from BI_audit_KRS where nip = '{$nip}' or regon = '{$regon}'";
- if ($result2 = DB::getPDO()->fetchall($query)) {
- foreach ($result2 as $item) {
- $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
- " select " . implode(', ', $fields['BI_audit_KRS']) . " from BI_audit_KRS where ID = '{$item['ID']}'";
- if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
- }
- } else {
- $query = "select ID from BI_audit_CEIDG where nip = '{$nip}' or regon = '{$regon}'";
- if ($result2 = DB::getPDO()->fetchall($query)) {
- foreach ($result2 as $item) {
- $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
- " select " . implode(', ', $fields['BI_audit_CEIDG']) .
- " from BI_audit_CEIDG where ID = '{$item['ID']}'";
- if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
- }
- }
- }
- }
- }
- }
- }
- foreach ($K_IDs as $K_ID) {
- if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
- DB::getPDO()->query("insert into `{$refTable}` (PRIMARY_KEY, REMOTE_PRIMARY_KEY) values ({$ID}, {$K_ID})");
- }
- }
- DB::getPDO()->update('BI_audit_ENERGA_RUM_UMOWY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
- }
- $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";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $query = "select nip, regon, krs from BI_audit_KRS where nip = '{$row['NIP']}' or regon = '{$row['REGON']}' or krs = '{$row['KRS']}'";
- if ($items = DB::getPDO()->fetchAll($query)) {
- list($nip, $regon, $krs) = [$items[0]["nip"], $items[0]["regon"], $items[0]["krs"]];
- if (count($items) > 1) {
- for ($i = 1; $i < count($items); $i++) {
- if ($nip != $items[$i]["nip"]) $nip = null;
- if ($regon != $items[$i]["regon"]) $regon = null;
- if ($krs != $items[$i]["krs"]) $krs = null;
- }
- }
- $set = [];
- if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
- if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
- if ($krs && $krs != $row['KRS']) $set[] = "KRS = '{$krs}'";
- if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row['ID']}'");
- }
- }
- $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";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $query = "select nip, regon from BI_audit_CEIDG where nip = '{$row['NIP']}' or regon = '{$row['REGON']}'";
- if ($items = DB::getPDO()->fetchAll($query)) {
- list($nip, $regon) = [$items[0]["nip"], $items[0]["regon"]];
- if (count($items) > 1) {
- for ($i = 1; $i < count($items); $i++) {
- if ($nip != $items[$i]["nip"]) $nip = null;
- if ($regon != $items[$i]["regon"]) $regon = null;
- }
- }
- $set = [];
- if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
- if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
- if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row->ID}'");
- }
- }
- }
- public static function reloadCache_reTeryt($full = false, $forceAll = false) {
- Lib::loadClass('Teryt');
- $tables = [
- 'BI_audit_CEIDG' => [
- 'fields' => [
- 'wojewodztwo' => 'wojewodztwo',
- 'powiat' => 'powiat',
- 'gmina' => 'gmina',
- 'miejscowosc' => 'miejscowosc',
- 'ulica' => 'ulica',
- 'kodPocztowy' => 'kodPocztowy',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'budynek',
- 'nrLokalu' => 'lokal',
- ],
- 'base' => '1',
- ],
- 'BI_audit_CEIDG_pelnomocnicy' => [
- 'fields' => [
- 'wojewodztwo' => 'wojewodztwo',
- 'powiat' => 'powiat',
- 'gmina' => 'gmina',
- 'miejscowosc' => 'miejscowosc',
- 'ulica' => 'ulica',
- 'kodPocztowy' => 'kodPocztowy',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'budynek',
- 'nrLokalu' => 'lokal',
- ],
- 'base' => '1',
- ],
- 'BI_audit_ENERGA_PRACOWNICY' => [
- 'fields' => [
- 'miejscowosc' => 'miejscowosc',
- 'kodPocztowy' => 'kodPocztowy',
- 'ulica' => 'ulica',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'nr',
- 'nrLokalu' => 'nrLokalu',
- ],
- 'base' => '0',
- ],
- 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
- 'fields' => [
- 'kodPocztowy' => 'kodPocztowy',
- 'miejscowosc' => 'miejscowosc',
- 'ulica' => 'ulica',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'nrBudynku',
- 'nrLokalu' => 'nrLokalu',
- ],
- 'base' => '0',
- ],
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
- 'fields' => [
- 'kodPocztowy' => 'Kod_pocztowy',
- 'miejscowosc' => 'Miejscowosc',
- 'ulica' => 'Ulica',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'Numer_budynku',
- 'nrLokalu' => 'Numer_mieszkania_lokalu',
- ],
- 'base' => '0',
- ],
- 'BI_audit_KRS' => [
- 'fields' => [
- 'wojewodztwo' => 'S_wojewodztwo',
- 'powiat' => 'S_powiat',
- 'gmina' => 'S_gmina',
- 'miejscowosc' => 'A_miejscowosc',
- 'ulica' => 'A_ulica',
- 'kodPocztowy' => 'A_kod',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'A_nrDomu',
- 'nrLokalu' => 'A_nrLokalu',
- ],
- 'base' => '1',
- ],
- 'BI_audit_KRS_address' => [
- 'fields' => [
- 'wojewodztwo' => 'S_wojewodztwo',
- 'powiat' => 'S_powiat',
- 'gmina' => 'S_gmina',
- 'miejscowosc' => 'A_miejscowosc',
- 'ulica' => 'A_ulica',
- 'kodPocztowy' => 'A_kod',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'A_nrDomu',
- 'nrLokalu' => 'A_nrLokalu',
- ],
- 'base' => '1',
- ],
- 'BI_audit_MSIG_address' => [
- 'fields' => [
- 'wojewodztwo' => 'S_wojewodztwo',
- 'powiat' => 'S_powiat',
- 'gmina' => 'S_gmina',
- 'miejscowosc' => 'A_miejscowosc',
- 'ulica' => 'A_ulica',
- 'kodPocztowy' => 'A_kod',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'A_nrDomu',
- 'nrLokalu' => 'A_nrLokalu',
- ],
- 'base' => '1',
- ],
- ];
- foreach ($tables as $table => $tableConf) {
- DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrDomu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrDomu']}`) = ''");
- DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrLokalu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrLokalu']}`) = ''");
- $where = ($full && ($forceAll || (!$tableConf['base']))) ? "" : "where `TERYT_SYM` is null and `cached` = 0";
- $query = "select * from `{$table}` {$where}";
- $refTable = BiAuditRefTables::getRefTable($table, 'TERYT_adresy', true);
- $terytJoinArr = [];
- foreach ($tableConf['fieldsTeryt'] as $terytField => $tableField) {
- $terytJoinArr[] = (
- $terytField == 'nrLokalu'
- ? "coalesce(`teryt`.`{$terytField}`, '') = coalesce(`table`.`{$tableField}`, '')"
- : "`teryt`.`{$terytField}` = `table`.`{$tableField}`"
- );
- }
- $terytJoin = implode(" and ", $terytJoinArr);
- $insertFields = "`" . implode("`, `", array_keys($tableConf['fieldsTeryt'])) . "`";
- $selectFields = "`" . implode("`, `", $tableConf['fieldsTeryt']) . "`";
- $adresy = DB::getPDO()->query($query);
- while ($adres = $adresy->fetch()) {
- DB::getPDO()->query("delete from `{$refTable}` where `PRIMARY_KEY` = '{$adres['ID']}'");
- if (!($forceAll and $adres['TERYT_SYM'])) {
- $search = [];
- foreach ($tableConf['fields'] as $field => $param) if (!empty($adres[$param])) $search[$field] = $adres[$param];
- try {
- $teryt = Teryt::search($search);
- } catch (Exception $e) {
- continue;
- }
- if (empty($teryt['SYM'])) continue;
- $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
- $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
- DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
- }
- if (!trim($adres[$tableConf['fieldsTeryt']['nrDomu']])) continue;
- $terytID = DB::getPDO()->fetchValue("select `teryt`.`ID` from `TERYT_adresy` as `teryt` join `{$table}` as `table` on {$terytJoin} where `table`.`ID` = '{$adres['ID']}'");
- if (!$terytID) {
- if (DB::getPDO()->query("insert into `TERYT_adresy` ({$insertFields}) select {$selectFields} from `{$table}` where `ID` = '{$adres['ID']}'")) {
- if (!($terytID = DB::getPDO()->lastInsertId())) {
- throw new Exception("Błąd dodania rekordu do TERYT_adresy #1");
- }
- } else {
- throw new Exception("Błąd dodania rekordu do TERYT_adresy #2");
- }
- }
- DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $adres['ID'], 'REMOTE_PRIMARY_KEY' => $terytID]);
- }
- }
- }
- private static function reloadCache_updateAll($full, $onlyBase) {
- $tablesConf = [
- 'BI_audit_CEIDG' => [
- 'fields' => [
- 'nip' => 'nip',
- 'regon' => 'regon',
- ],
- 'base' => '1',
- ],
- 'BI_audit_CEIDG_pelnomocnicy' => [
- 'fields' => [
- 'nip' => 'nip',
- ],
- 'base' => '1',
- ],
- 'BI_audit_CEIDG_powiazania' => [
- 'fields' => [
- 'nip' => 'nip',
- 'regon' => 'regon',
- ],
- 'base' => '1',
- ],
- 'BI_audit_ENERGA_PRACOWNICY' => [
- 'fields' => [
- 'nip' => 'nip',
- 'regon' => 'regon',
- 'pesel' => 'pesel',
- ],
- 'base' => '0',
- //'where' => '',
- ],
- 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
- 'fields' => [],
- 'base' => '0',
- //'where' => '',
- ],
-
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
- 'fields' => [
- 'krs' => 'KRS',
- 'nip' => 'NIP',
- 'regon' => 'REGON',
- 'pesel' => 'PESEL',
- ],
- 'base' => '0',
- 'where' => "and ownCompany != 'Y'",
- ],
- 'BI_audit_KRS' => [
- 'fields' => [
- 'krs' => 'krs',
- 'nip' => 'nip',
- 'regon' => 'regon',
- ],
- 'base' => '1',
- ],
- 'BI_audit_KRS_address' => [
- 'fields' => [],
- 'base' => '1',
- ],
- 'BI_audit_KRS_company' => [
- 'fields' => [
- 'regon' => 'regon',
- 'krs' => 'krs',
- ],
- 'base' => '1',
- ],
- 'BI_audit_KRS_person' => [
- 'fields' => [
- 'pesel' => 'pesel',
- ],
- 'base' => '1',
- ],
- 'BI_audit_MSIG' => [
- 'fields' => [
- 'krs' => 'krs',
- 'nip' => 'nip',
- 'regon' => 'regon',
- ],
- 'base' => '1',
- ],
- 'BI_audit_MSIG_address' => [
- 'fields' => [],
- 'base' => '1',
- ],
- 'BI_audit_MSIG_company' => [
- 'fields' => [
- 'regon' => 'regon',
- 'krs' => 'krs',
- ],
- 'base' => '1',
- ],
- 'BI_audit_MSIG_person' => [
- 'fields' => [
- 'pesel' => 'pesel',
- ],
- 'base' => '1',
- ],
- // 'BI_audit_KW_requested_person' => [
- // 'fields' => [
- // 'pesel' => 'Seller_person_pesel',
- // 'krs' => 'Seller_person_KRS',
- // 'nip' => 'Seller_person_NIP',
- // 'regon' => 'Seller_person_REGON',
- // ],
- // 'base' => '0',
- // //'where' => '',
- // ],
- 'TERYT_adresy' => [
- 'fields' => [],
- 'base' => '1',
- ],
- ];
- $refTablesConf = [
- 'BI_audit_CEIDG' => [
- 'refTablesTo' => [
- 'BI_audit_CEIDG_pelnomocnicy',
- 'BI_audit_CEIDG_powiazania',
- 'TERYT_adresy',
- ],
- 'base' => 1,
- ],
- 'BI_audit_CEIDG_pelnomocnicy' => [
- 'refTablesTo' => [
- 'TERYT_adresy',
- ],
- 'base' => 1,
- ],
- 'BI_audit_ENERGA_PRACOWNICY' => [
- 'refTablesTo' => [
- 'BI_audit_ENERGA_PRACOWNICY_adresy',
- 'TERYT_adresy',
- ],
- 'base' => 0,
- ],
- 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
- 'refTablesTo' => [
- 'TERYT_adresy',
- ],
- 'base' => 0,
- ],
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
- 'refTablesTo' => [
- 'TERYT_adresy',
- ],
- 'base' => 0,
- ],
- 'BI_audit_KRS' => [
- 'refTablesTo' => [
- 'BI_audit_KRS_address',
- 'BI_audit_KRS_company',
- 'BI_audit_KRS_person',
- 'TERYT_adresy',
- ],
- 'base' => 1,
- ],
- 'BI_audit_KRS_address' => [
- 'refTablesTo' => [
- 'TERYT_adresy',
- ],
- 'base' => 1,
- ],
- 'BI_audit_MSIG' => [
- 'refTablesTo' => [
- 'BI_audit_MSIG_address',
- 'BI_audit_MSIG_company',
- 'BI_audit_MSIG_person',
- ],
- 'base' => 1,
- ],
- 'BI_audit_MSIG_address' => [
- 'refTablesTo' => [
- 'TERYT_adresy',
- ],
- 'base' => 1,
- ],
- ];
-
- $sourceTables = ['BI_audit_ENERGA_PRACOWNICY'];
- if ($full) {
- foreach ($tablesConf as $table => $tableConf) if (!$tableConf['base']) $queries[] = "update `{$table}` set `cached` = 0";
- $queries[] = "delete from `BI_audit_ALL` where `BASE` = 0";
- // $queries[] = "optimize table `BI_audit_ALL`";
- $queries[] = "delete from `BI_audit_ALL_ref` where `BASE` = 0";
- // $queries[] = "optimize table `BI_audit_ALL_ref`";
- $allTables = [];
- foreach ($refTablesConf as $refTableFrom => $refTableConf) {
- $allTables[] = $refTableFrom;
- // if ($refTableConf['base']) continue;
- foreach ($refTableConf['refTablesTo'] as $refTableTo) {
- $allTables[] = $refTableTo;
- if ($refTableConf['base']) continue;
- $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
- $queries[] = "update `{$refTable}` set `A_STATUS` = 'WAITNG' where `A_STATUS` = 'NORMAL'";
- // $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}'";
- }
- }
- $allTables = array_unique($allTables);
- foreach ($allTables as $refTableFrom) {
- foreach ($allTables as $refTableTo) {
- if ($refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, false)) {
- $queries[] = "delete from `{$refTable}` where `TRANSACTION_ID` = '-1'";
- $queries[] = "optimize table `{$refTable}`";
- $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";
- }
- }
- }
- }
- foreach ($tablesConf as $table => $tableConf) {
- if ($onlyBase && (!$tableConf['base'])) continue;
- $where = "where `cached` = 0";
- if (!empty($tableConf['where'])) $where .= " {$tableConf['where']}";
- // $queries[] = "insert into `BI_audit_ALL` (`REMOTE_TABLE`, `REMOTE_ID`, `BASE`, " . implode(", ", array_keys($tableConf['fields'])) .
- // ") select '{$table}', ID, '{$tableConf['base']}', " . implode(", ", $tableConf['fields']) . " from `{$table}` {$where}";
- $fields = ["`REMOTE_TABLE`", "`REMOTE_ID`", "`BASE`"];
- foreach (array_keys($tableConf['fields']) as $field) $fields[] = "`{$field}`";
- $values = ["'{$table}'", "`ID`", "'{$tableConf['base']}'"];
- foreach ($tableConf['fields'] as $value) $values[] = "`{$value}`";
- $queries[] = "insert into `BI_audit_ALL` (" . implode(", ", $fields) . ") select " . implode(", ", $values) . " from `{$table}` {$where}";
- $queries[] = "update `{$table}` set `cached` = 1 {$where}";
- }
- $queries[] = "update `BI_audit_ALL` set `nip` = null where `nip` = 0";
- $queries[] = "update `BI_audit_ALL` set `regon` = null where `regon` = 0";
- $queries[] = "update `BI_audit_ALL` set `krs` = null where `krs` = 0";
- $queries[] = "update `BI_audit_ALL` set `pesel` = null where `pesel` = 0";
- $queries[] = "set @var = (select round(coalesce(max(`ID`), '0.5'), 1) from `BI_audit_ALL_ref_RELATIONS`)";
- $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";
- foreach ($refTablesConf as $refTableFrom => $refTableConf) {
- if ($onlyBase && (!$tableConf['base'])) continue;
- foreach ($refTableConf['refTablesTo'] as $refTableTo) {
- $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
- $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`";
- if (!in_array($refTableFrom, $sourceTables)) {
- $queries[] = "insert into `BI_audit_ALL_ref` (`ID1`, `ID2`, `RELATION_ID`, `BASE`) select `all2`.`ID`, `all1`.`ID`, `rel`.`ID`, {$refTableConf['base']} from `BI_audit_ALL` as `all1` join `{$refTable}` as `ref` on `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all1`.`REMOTE_ID` = `ref`.`PRIMARY_KEY` and `ref`.`A_STATUS` = 'WAITING' join `BI_audit_ALL` as `all2` on `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref`.`REMOTE_PRIMARY_KEY` = `all2`.`REMOTE_ID` join `BI_audit_ALL_ref_RELATIONS` `rel` on `all2`.`REMOTE_TABLE` = `rel`.`RELATION`";
- }
- if ($backRefTable = BiAuditRefTables::getRefTable($refTableTo, $refTableFrom, false)) {
- $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'";
- }
- $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'";
- }
- }
- foreach ($queries as $query) {
- echo "SQL: {$query}\n";
- DB::getPDO()->query($query);
- }
- $BiAuditRelations = new BiAuditRelations();
- $result = DB::getPDO()->query("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
- while ($row = $result->fetch()) $BiAuditRelations->findRelations($row['ID']);
- DB::getPDO()->query("update `BI_audit_ALL` set `reffed` = 1");
- }
- public function doReloadCache($full = false) {
- if ($full === 'base') {
- $onlyBase = true;
- $full = false;
- } else {
- $onlyBase = false;
- }
- $powiazaniaDirLocation = self::getMainDirectory();
- $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
- $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
- $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
- if ($full) file_put_contents($reloadCachePidFile, getmypid());
- try {
- //self::importPracownicy(); //TODO
- error_log('now: self::reloadCache_parseUmowy');
- self::reloadCache_parseUmowy($full);
- error_log('now: self::reloadCache_reTeryt');
- self::reloadCache_reTeryt($full);
- error_log('now: self::reloadCache_updateAll');
- self::reloadCache_updateAll($full, $onlyBase);
- if ($full) file_put_contents($reloadCacheResultFile, "ok");
- } catch (Exception $e) {
- var_dump($e);
- if ($full) file_put_contents($reloadCacheResultFile, $e->getMessage());
- else throw new Exception($e->getMessage());
- }
- }
- public function doGeneratePowiazania($ID) {
- $powiazaniaDirLocation = self::getMainDirectory();
- $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
- $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
- $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
- $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
- file_put_contents($pidFile, getmypid());
- $tablesConf = [
- 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
- 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
- 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
- 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
- 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
- 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
- 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
- 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
- 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
- ];
- try {
- $BiAuditPowiazania = new BiAuditPowiazania($ID, $tasksDirLocation);
- $query = "select count(*) from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` where `FILE_STATUS` = 'IN_PROGRESS' and `BI_analiza_reloadCache` = 'Part' and ID != ${ID}";
- $sqlArr = [
- 'BI_analiza_reloadCache' => 'Part',
- 'FILE_STATUS_info' => 'Odświeżam częściowo cache',
- ];
- do {
- DB::getPDO()->query("lock tables `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` write");
- $activeReloadingCache = DB::getPDO()->fetchValue($query);
- if (!$activeReloadingCache) DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
- DB::getPDO()->query("unlock tables");
- if ($activeReloadingCache) {
- BiAuditPowiazania::saveToLog("Czekam na zakończenie częściowego odświeżania cache przez inne zadanie");
- sleep(30);
- }
- } while ($activeReloadingCache);
-
- BiAuditPowiazania::saveToLog("Uruchamiam częściowe odświeżenie cache");
- $this->doReloadCache(); //DUPA testowe wylaczanie
- BiAuditPowiazania::saveToLog("Odświeżono częściowo cache");
- $sqlArr = [
- 'BI_analiza_reloadCache' => 'No',
- 'FILE_STATUS_info' => 'Szukam powiązań',
- ];
- DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
- $BiAuditPowiazania->run();
- if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
- //file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
- $sqlArr = ['FILE_STATUS_info' => 'Generuję raporty PDF i HTML'];
- DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
-
- //$BiAuditPowiazania->saveXml();
- $BiAuditPowiazania->generatePdfAndHtml();
- file_put_contents($resultFile, json_encode(['result' => 'ok', 'parts' => $BiAuditPowiazania->getPartsCount()]));
- } catch (Exception $e) {
- file_put_contents($resultFile, json_encode(['result' => 'error', 'message' => $e->getMessage()]));
- }
- }
- public function reinstallAction() {
- $this->reinstall();
- die('OK');
- }
- public function reinstall() {
- $sqlList = array();
- //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
- $sqlList['ActivateBiAuditGenerate'] = <<<SQL
- REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
- SQL;
- $sqlList['ChangeStructure1'] = <<<SQL
- 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';
- SQL;
- $sqlList['ChangeStructure2'] = <<<SQL
- UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
- SQL;
- $sqlList['ChangeStructure3'] = <<<SQL
- ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
- SQL;
- $sqlList['ChangeStructure4'] = <<<SQL
- ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_depth` `BI_analiza_maxDepth` INT(2) NULL DEFAULT '9';
- SQL;
- $sqlList['ChangeStructure5'] = <<<SQL
- ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_minDepth` INT(2) NOT NULL DEFAULT '0' AFTER `FILE_STATUS_info`;
- SQL;
- $sqlList['ChangeStructure6'] = <<<SQL
- ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_onlyTargets` ENUM('Y','N') NOT NULL DEFAULT 'Y' AFTER `BI_analiza_maxDepth`;
- SQL;
- $db = DB::getDB();
- if ($db->has_errors()) {
- throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
- }
- foreach ($sqlList as $sqlName => $sql) {
- $res = $db->query($sql);
- if ($db->has_errors()) {
- throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
- }
- }
- }
- }
- class BiAuditRelations {
- private $RELATIONS_ID = [];
- private $relations = [
- 'nip' => ['nip'],
- 'regon' => ['regon'],
- 'krs' => ['krs'],
- 'pesel' => ['pesel'],
- ];
- private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
- private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
- public function __construct() {
- $query = "select * from BI_audit_ALL_ref_RELATIONS";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
- }
- private function getRelationID($name) {
- if (!isset($this->RELATIONS_ID[$name])) {
- $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
- $newID = DB::getPDO()->fetchValue($query);
- $this->RELATIONS_ID[$name] = $newID;
- $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
- DB::getPDO()->query($query);
- }
- return $this->RELATIONS_ID[$name];
- }
- private function addToRefTable($fromTable, $toTable, $fromID, $toID) {
- if ($refTable = BiAuditRefTables::getRefTable($fromTable, $toTable, false)) {
- if (!DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = '{$fromID}' and `REMOTE_PRIMARY_KEY` = '{$toID}' and `A_STATUS` != 'DELETED'")) {
- DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $fromID, 'REMOTE_PRIMARY_KEY' => $toID, 'A_STATUS' => 'NORMAL', 'TRANSACTION_ID' => '-1']);
- }
- }
- }
- public function findRelations($ID) {
- $query = "select * from BI_audit_ALL where ID = '{$ID}'";
- if (!($result = DB::getPDO()->fetchAll($query))) return false;
- $row = $result[0];
- $joins = [];
- $items = '';
- foreach ($this->relations as $name => $columns) {
- $ok = 0;
- $join = [];
- foreach ($columns as $column) {
- $join[] = "t1.{$column} = t2.{$column}";
- if ($row[$column] !== null) $ok++;
- }
- if ($ok / count($columns) > 0.5) {
- $joins[] = "(" . implode(" and ", $join) . ")";
- $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
- }
- }
- if (!$joins) return false;
- $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 " .
- "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})";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $relationID = 0;
- foreach ($this->relations as $name => $v) {
- if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
- }
- $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
- $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
- $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
- $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
- if (!($start2 || $end1)) {
- $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
- $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
- $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
- DB::getPDO()->query($query);
- }
- if (!($start1 || $end2)) {
- $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
- $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
- $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
- DB::getPDO()->query($query);
- }
- }
- }
- }
- class BiAuditRefTables {
- public static function getRefTable($tableFrom, $tableTo, $returnException = false) {
- static $refTables = [];
- if (!isset($refTables[$tableFrom][$tableTo])) {
- try {
- $refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
- } catch (Exception $e) {
- if ($returnException) throw new Exception($e->getMessage());
- $refTables[$tableFrom][$tableTo] = false;
- }
- }
- return $refTables[$tableFrom][$tableTo];
- }
- public static function getRefTables($tableFrom) {
- static $refTables = [];
- if (!isset($refTables[$tableFrom])) {
- $namespace = "default_db/{$tableFrom}/{$tableFrom}";
- try {
- $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
- if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
- $fields = $item['field'];
- $_refTables = [];
- foreach ($fields as $field) {
- list($type, $child) = explode(":", $field['xsdType'], 2);
- if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) {
- try {
- $_refTable = ACL::getRefTable($namespace, $child);
- $_refTables[] = $_refTable;
- } catch (Exception $e) {
- }
- }
- }
- $refTables[$tableFrom] = $_refTables;
- } catch (Exception $e) {
- $refTables[$tableFrom] = [];
- }
- }
- return $refTables[$tableFrom];
- }
- }
- class BiAuditPowiazania {
- private $minDepth;
- private $maxDepth, $origMaxDepth;
- private $onlyTargets;
- private $ID;
- private $nodes = [];
- private $endNodes;
- private $path = [];
- private $results = [];
- private $items_results = [];
- private $relations = [];
- private $srcTables = ['BI_audit_ENERGA_PRACOWNICY'];
- private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
- private $step = 0;
- private $tasksDirLocation;
- private $progressFile;
- private $progress = [
- 'summary' => [
- 'count' => 0,
- 'message' => 'Inicjacja',
- 'ts' => null,
- 'step' => 'initialize',
- 'reportsCount' => 0,
- 'reportsCreated' => 0,
- ],
- 'details' => [],
- ];
- private $lastProgress = 0;
- private $lastResults = 0;
- private $startTimestamp = null;
- private $lastTimestamp = null;
- private $lowProgressCount = 0;
- private $count, $i;
- private $splittedResults = [];
- private $maxResults = 1000000;
- private $fidRow = [];
- private $itemID = 0;
- private $reverseSearch = false;
- private $query = "";
- private static function generateJson($type, $data) {
- return json_encode(['ts' => microtime(true), 'type' => $type, 'data' => $data]);
- }
- public static function saveToLog($message) {
- $messageJson = self::generateJson('message', ['message' => $message]);
- echo $messageJson . "\n";
- }
- private static function exec($cmd) {
- $path = 'export PATH=$PATH:/usr/sbin;';
- $cmd = "{$path} {$cmd}";
- echo "CMD :: {$cmd}\n";
- shell_exec($cmd);
- }
- private function saveProgress($args = []) {
- $timestamp = microtime(true);
- if (isset($args['progress']) && $this->i) {
- $elapsed = $timestamp - $this->startTimestamp;
- if ($args['progress']) {
- $estimated = ($elapsed * (1 - $args['progress'])) / $args['progress'];
- } else $estimated = "N/A";
- $this->lastProgress = $args['progress'];
- $this->lastTimestamp = $timestamp;
- $progressJson = self::generateJson('progress', ['progress' => $args['progress'], 'item' => $this->i . "/" . $this->count, 'results' => count($this->results), 'step' => $this->step, 'elapsed' => $elapsed, 'estimated' => $estimated]);
- echo $progressJson . "\n";
- $this->progress['details'][$this->itemID] = ['progress' => $args['progress'], 'results' => (count($this->results) - $this->lastResults), 'elapsed' => $elapsed, 'estimated' => $estimated];
- }
- if (isset($args['message'])) $this->progress['summary']['message'] = $args['message'];
- if (isset($args['step'])) $this->progress['summary']['step'] = $args['step'];
- if (isset($args['reportsCreated'])) $this->progress['summary']['reportsCreated'] = round($this->progress['summary']['reportsCreated'] + $args['reportsCreated'], 2);
- $this->progress['summary']['ts'] = $timestamp;
- file_put_contents($this->progressFile, json_encode($this->progress));
- }
- private static function throwException($message) {
- self::saveToLog($message);
- throw new Exception($message);
- }
- public function __construct($ID = 0, $tasksDirLocation = null) {
- if (!$ID) self::throwException("Wrong ID parameter");
- if (!$tasksDirLocation) self::throwException("Wrong directory of tasks location");
- $this->ID = $ID;
- $this->tasksDirLocation = $tasksDirLocation;
- $this->progressFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.progress";
- $this->saveProgress();
- }
- public function run() {
- $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')";
- $result = DB::getPDO()->fetchAll($query);
- if (!$result) self::throwException("Błąd danych");
- if ($this->loadResults()) {
- $this->splitResults();
- return;
- }
- self::saveToLog("Wczytuję parametry wyszukiwania powiązań");
- $this->minDepth = (int) $result[0]['BI_analiza_minDepth'];
- $this->maxDepth = (int) $result[0]['BI_analiza_maxDepth'];
- $this->onlyTargets = ($result[0]['BI_analiza_onlyTargets'] != 'N');
- if (!$this->minDepth) $this->minDepth = 1;
- if (!$this->maxDepth) self::throwException("Błąd danych - nieokreślono maksymalnej głębokości analizy");
- if ($this->minDepth > $this->maxDepth) self::throwException("Wartość minimalnej głębokości analizy jest większa od wartości maksymalnej głębokości analizy");
- $subQueries = [];
- foreach ($this->destTables as $destTable) {
- $refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $destTable, true);
- $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}'";
- }
- $query = implode(" union ", $subQueries) . " order by `ID` asc";
- $resultDest = DB::getPDO()->fetchAll($query);
- if ((!$resultDest) && $this->onlyTargets) self::throwException("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
- $subQueries = [];
- foreach ($this->srcTables as $srcTable) {
- $refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $srcTable, true);
- $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}'";
- }
- $query = implode(" union ", $subQueries) . " order by `ID` asc";
- $resultSrc = DB::getPDO()->fetchAll($query);
- if (!$resultSrc) self::throwException("Błąd danych - nie zdefinowano żadnego początkowego obiektu");
- if (count($resultSrc) <= count($resultDest) || (!$this->onlyTargets)) {
- $result = $resultSrc;
- $this->endNodes = array_map('reset', $resultDest);
- $this->reverseSearch = false;
- $this->query = "select ref.ID2 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID1";
- } else {
- $result = $resultDest;
- $this->endNodes = array_map('reset', $resultSrc);
- $this->reverseSearch = true;
- $this->query = "select ref.ID1 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID2";
- self::saveToLog("Docelowych obiektów jest mniej, niż początkowych - włączono mechanizm odwrotnego przeszukiwania");
- }
- self::saveToLog("Rozpoczynam wyszukiwanie powiązań");
- $this->count = count($result);
- $this->progress['summary']['count'] = $this->count;
- $this->origMaxDepth = $this->maxDepth;
- $this->saveProgress(['step' => 'relations']);
- try {
- foreach ($result as $i => $row) {
- $this->i = $i + 1;
- $this->itemID = DB::getPDO()->fetchValue("select `REMOTE_ID` from `BI_audit_ALL` where `ID` = :ID", [":ID" => $row['ID']]);
- $this->startTimestamp = microtime(true);
- $this->lastProgress = 0;
- $this->saveProgress(['progress' => 0, 'message' => "Wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
- if ($this->maxDepth != $this->origMaxDepth) {
- $this->maxDepth = $this->origMaxDepth;
- self::saveToLog("Przywrócono oryginalną maksymalną głębokość przeszukiwania ({$this->origMaxDepth})");
- }
- $this->findPowiazania($row['ID']);
- $this->saveProgress(['progress' => 1, 'message' => "Zakończono wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
- $this->lastResults = count($this->results);
- }
- } catch (Exception $e) {
- if ($this->i < $this->count) {
- $this->startTimestamp = microtime(true);
- $this->lastProgress = 0;
- $this->lastResults = count($this->results);
- while (++$this->i <= $this->count) $this->saveProgress(['progress' => 0]);
- }
- if ($message = $e->getMessage()) self::saveToLog("Wystąpił błąd podczas wyszukiwania powiązań - {$message}");
- }
- $this->nodes = [];
- self::saveToLog("Zakończono wyszukiwanie powiązań");
- $this->sortResults();
- $this->saveResults();
- //$this->saveToDb(); 2017-12-14 - przerobiono na zapisywanie danych do bazy w locie
- $this->splitResults();
- }
- private static function reversePath($path) {
- $arr = array_reverse($path, true);
- $keys = array_keys($arr);
- array_unshift($arr, array_pop($arr));
- return array_combine($keys, $arr);
- }
- private function addResult($progress) {
- if (count($this->results) == $this->maxResults) {
- $message = "Przerwano wyszukiwanie powiązań - osiągnięto maksymalną liczbę wyników {$this->maxResults}";
- self::saveToLog($message);
- $this->saveProgress(['progress' => $progress, 'message' => $message]);
- throw new Exception('');
- }
- if ($this->reverseSearch) $path = self::reversePath($this->path);
- else $path = $this->path;
- $this->results[] = $path;
- $this->saveToDb($path);
- }
- public function findPowiazania($ID, $progress = 0, $steps = 1, $relation = "") {
- if (((++$this->step) % 1000000) == 0) {
- $progressDiff = $progress - $this->lastProgress;
- if ($progressDiff < 0.00005) {
- $this->lowProgressCount++;
- if ($this->lowProgressCount == 10) {
- $this->maxDepth--;
- self::saveToLog("Zbyt dużo rekurencji, zmniejszono maksymalną głębokość poszukiwań do {$this->maxDepth} dla bieżącego obiektu");
- }
- } else $this->lowProgressCount = 0;
- }
- if ((($this->step) % 100000) == 0) {
- $this->saveProgress(['progress' => $progress]);
- }
- if ((($this->step) % 10000) == 0) {
- if (memory_get_usage(true) > 3000000000) {
- $this->nodes = [];
- self::saveToLog("Oczyszczam podręczny cache - zajmuje zbyt dużo pamięci");
- }
- }
- if (isset($this->path[$ID])) return false;
- $this->path[$ID] = $relation;
- if (!$relation) $relation = 0;
- if (in_array($ID, $this->endNodes)) {
- if (count($this->path) > $this->minDepth) $this->addResult($progress);
- array_pop($this->path);
- return;
- }
- if (count($this->path) > $this->maxDepth) {
- if (!$this->onlyTargets) $this->addResult($progress);
- array_pop($this->path);
- return;
- }
- if (!isset($this->nodes[$ID][$relation])) {
- $where = $relation ? "and ({$relation} & ref.RELATION_ID) != " . ($this->reverseSearch ? "ref.RELATION_ID" : $relation) : "";
- $query = "{$this->query} = {$ID} {$where}";
- $this->nodes[$ID][$relation] = DB::getPDO()->fetchAll($query);
- }
- $nodes = array_values(array_filter($this->nodes[$ID][$relation], function ($node) {
- if (isset($this->path[$node['ID']])) return false;
- return true;
- }));
- $count = count($nodes);
- foreach ($nodes as $i => $node) $this->findPowiazania($node['ID'], ($progress + ($i / ($count * $steps))), ($count * $steps), $node['RELATION_ID']);
- array_pop($this->path);
- }
- private function sortResults() {
- if (!$this->results) return;
- uasort($this->results, function ($a, $b) {
- $ca = count($a);
- $cb = count($b);
- $c = min($ca, $cb);
- $ka = array_keys($a);
- $kb = array_keys($b);
- for ($i = 0; $i < $c; $i++) {
- if ($ka[$i] < $kb[$i]) return -1;
- if ($ka[$i] > $kb[$i]) return 1;
- }
- if ($ca < $cb) return -1;
- if ($ca > $cb) return 1;
- return 0;
- });
- }
- private function saveResults() {
- self::saveToLog("Zapisuję wyliczone dane do pliku");
- if (!$this->results) {
- self::saveToLog("Brak wyliczonych danych - niczego nie zapisaono");
- return false;
- }
- $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
- $data = base64_encode(gzcompress(json_encode(['results' => $this->results, 'fidRow' => $this->fidRow])));
- file_put_contents($dataFile, $data);
- self::saveToLog("Zapisano wyliczone dane do pliku");
- return true;
- }
- private function loadResults() {
- self::saveToLog("Próbuję wczytać wcześniej wyliczone dane");
- $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
- if (!file_exists($dataFile)) {
- self::saveToLog("Nie znaleziono pliku z wyliczonymi danymi");
- return false;
- }
- $data = file_get_contents($dataFile);
- $results = @json_decode(gzuncompress(base64_decode($data)), true);
- if (!$results) {
- self::saveToLog("Wystąpił błąd wczytywania wcześniej wyliczonych danych");
- return false;
- }
- if (isset($results['results'])) {
- $this->results = $results['results'];
- if (isset($results['fidRow'])) $this->fidRow = $results['fidRow'];
- } else $this->results = $results;
- self::saveToLog("Wczytano wcześniej wyliczone dane");
- return true;
- }
- private function relationName($ID) {
- if (!$ID) return '';
- if (!isset($this->relations[$ID])) {
- $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
- $result = DB::getPDO()->fetchAll($query);
- $rels = array_map('reset', $result);
- $this->relations[$ID] = implode(", ", $rels);
- }
- return $this->relations[$ID];
- }
- private function splitResults() {
- $MAX = 1000;
- $countBySource = [];
- $resultsKeys = [];
- foreach ($this->results as $resultKey => $result) {
- $_keys = array_keys($result);
- $countBySource[reset($_keys)][] = $resultKey;
- }
- foreach ($countBySource as $resultKeys) {
- if (count($resultKeys) > $MAX) {
- $countByDest = [];
- foreach ($resultKeys as $resultKey) {
- $_keys = array_keys($this->results[$resultKey]);
- $countByDest[end($_keys)][] = $resultKey;
- }
- foreach ($countByDest as $resultKeys2) $resultsKeys = array_merge($resultsKeys, array_chunk($resultKeys2, $MAX));
- } else $resultsKeys[] = $resultKeys;
- }
- $results = [];
- while ($resultsKeys) {
- $resultKeys = array_shift($resultsKeys);
- while ($next = current($resultsKeys)) {
- if (count($resultKeys) + count($next) <= $MAX) {
- $resultKeys = array_merge($resultKeys, $next);
- unset($resultsKeys[key($resultsKeys)]);
- } else break; //next($resultsKeys);
- }
- $_results = [];
- foreach ($resultKeys as $key) $_results[$key] = $this->results[$key];
- $results[] = $_results;
- // $results[] = array_map(function ($resultKey) {return $this->results[$resultKey];}, $resultKeys);
- }
- $this->splittedResults = $results;
- $this->progress['summary']['reportsCount'] = count($results);
- }
- public function getPartsCount() {
- return count($this->splittedResults);
- }
- private function generateItemsResults($resultsPart = null) {
- if ($resultsPart === null) self::saveToLog("Generuję dane na potrzeby utworzenia pojedynczego pliku XML");
- else {
- self::saveToLog("Generuję dane na potrzeby utworzenia pliku XML ({$resultsPart})");
- if ($resultsPart >= $this->getPartsCount()) throw new Exception("generateItemsResults() error - bad part number");
- }
- $xmlTask = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
- $xmlRow = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
- $xmlObject = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object";
- $items_kontrahenci = [];
- $items_kw_person = [];
- $kontrahenci = [];
- $kw_person = [];
- $_items_results = [];
- $refUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
- $refKwRequestedToKwRequestedPerson = BiAuditRefTables::getRefTable('BI_audit_KW_requested', 'BI_audit_KW_requested_person', true);
- $this->items_results[$resultsPart] = [];
- $this->items_results[$resultsPart]['@attributes'] = ['xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd'];
- $this->items_results[$resultsPart][$xmlTask]['@attributes'] = ['fid' => "{$xmlTask}.{$this->ID}"];
- if ($resultsPart === null) {
- $results = $this->results;
- } else {
- $results = (!empty($this->splittedResults[$resultsPart])) ? $this->splittedResults[$resultsPart] : [];
- $this->items_results[$resultsPart][$xmlTask]['@attributes']['system_cache__dita:part'] = ($resultsPart + 1);
- }
- foreach ($results as $key => $result) {
- if ($this->fidRow) $item_results = ['@attributes' => ['fid' => "{$xmlRow}.{$this->fidRow[$key]['fid']}"]];
- foreach ($result as $ID => $rel) {
- $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
- $row = DB::getPDO()->fetchFirst($query);
- $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
- $obj = DB::fetch(DB::query($query));
- $item_result = [];
- if ($this->fidRow) {
- $item_result['@attributes'] = ['fid' => "{$xmlObject}.{$this->fidRow[$key]['obj'][$ID]}"];
- }
- $item_result[$row['REMOTE_TABLE']] = array_merge(['@attributes' => ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"]], (array) $obj);
- if ($refTable = BiAuditRefTables::getRefTable('BI_audit_operational_raport_note', $row['REMOTE_TABLE'], false)) {
- $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']}'";
- if ($notes = DB::getPDO()->fetchAll($query)) $item_result[$row['REMOTE_TABLE']]['BI_audit_operational_raport_note'] = $notes;
- }
- if ($refTable = BiAuditRefTables::getRefTable($row['REMOTE_TABLE'], 'BI_audit_taxpayer', false)) {
- $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']}'";
- if ($taxpayer = DB::getPDO()->fetchFirst($query)) {
- $item_result[$row['REMOTE_TABLE']]['BI_audit_taxpayer'] = array_merge(['@attributes' => ['fid' => "BI_audit_taxpayer.{$taxpayer['ID']}"]], $taxpayer);
- }
- }
- if ($rel) $item_result['relation_from'] = $this->relationName($rel);
- $item_results[$xmlObject][] = $item_result;
- if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
- $kontrahenci[] = $row['REMOTE_ID'];
- $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']}'";
- $res = DB::query($query);
- if (mysql_num_rows($res)) {
- $umowy = [];
- while ($obj = DB::fetch($res)) {
- $umowa = (array) $obj;
- $umowa = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_RUM_UMOWY.{$umowa['ID']}"]], $umowa);
- $umowy[] = $umowa;
- }
- $item_kontrahenci['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
- $item_kontrahenci['ID'] = $row['REMOTE_ID'];
- $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
- $items_kontrahenci[] = $item_kontrahenci;
- }
- } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
- $kw_person[] = $row['REMOTE_ID'];
- $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']}'";
- $res = DB::query($query);
- if (mysql_num_rows($res)) {
- $kws = [];
- while ($obj = DB::fetch($res)) {
- $kw = (array) $obj;
- $kw = array_merge(['@attributes' => ['fid' => "BI_audit_KW_requested.{$kw['ID']}"]], $kw);
- $kws[] = $kw;
- }
- $item_kw_person['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
- $item_kw_person['ID'] = $row['REMOTE_ID'];
- $item_kw_person['BI_audit_KW_requested'] = $kws;
- $items_kw_person[] = $item_kw_person;
- }
- }
- }
- $this->items_results[$resultsPart][$xmlTask][$xmlRow][] = $item_results;
- }
- $this->items_results[$resultsPart][$xmlTask]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
- $this->items_results[$resultsPart][$xmlTask]['BI_audit_KW_requested_person'] = $items_kw_person;
- self::saveToLog("Wygenerowano dane na potrzeby utworzenia pliku XML ({$resultsPart})");
- }
- private function saveToDb($result = null, $key = null) {
- if ($result === null) {
- self::saveToLog("Zapisuję wyliczone dane do bazy");
- if (!$this->results) {
- self::saveToLog("Brak wyliczonych danych - nie zapisaono niczego do bazy");
- return null;
- }
- foreach ($this->results as $key => $result) $this->saveToDb($result, $key);
- self::saveToLog("Zapisano wyliczone dane do bazy");
- } else {
- if ($key === null) {
- end($this->results);
- $key = key($this->results);
- }
- $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
- $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
- $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
- $fidObj = [];
- DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
- foreach ($result as $ID => $rel) {
- $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
- $object = DB::getPDO()->fetchFirst($query);
- $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relationName($rel)]);
- DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
- $ref = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', $object['REMOTE_TABLE'], true);
- DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
- $fidObj[$ID] = $idPowiazaniaRowObject;
- }
- $this->fidRow[$key] = [
- 'fid' => $IdPowiazaniaRow,
- 'obj' => $fidObj,
- ];
- }
- }
- public function saveXml($resultsPart = null) {
- if ($this->getPartsCount()) {
- if ($resultsPart === null) {
- self::saveToLog("Generuję pliki XML (liczba plików do wygenerowania: {$this->getPartsCount()})");
- for ($i =0; $i < $this->getPartsCount(); $i++) {
- $partNo = str_pad($i + 1, 6, '0', STR_PAD_LEFT);
- $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
- file_put_contents($xmlFile, $this->asXml($i));
- }
- self::saveToLog("Zakończono generowanie plików XML");
- } else {
- if ($resultsPart >= $this->getPartsCount()) {
- self::saveToLog("saveXml() error - bad result number");
- return;
- }
- $partNo = str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
- $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
- file_put_contents($xmlFile, $this->asXml($resultsPart));
- }
- } else {
- $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
- file_put_contents($xmlFile, $this->asXml());
- }
- }
- public function asXml($resultsPart = null) {
- self::saveToLog("Generuję plik XML ({$resultsPart})");
- if (!$this->results) {
- self::saveToLog("Brak wyników (#1), nie wygenerowano pliku XML ({$resultsPart})");
- return null;
- }
- if (!isset($this->items_results[$resultsPart])) $this->generateItemsResults($resultsPart);
- if (!isset($this->items_results[$resultsPart])) {
- self::saveToLog("Brak wyników (#2), nie wygenerowano pliku XML ({$resultsPart})");
- return null;
- }
- $xmlRoot = "RelatedFeatureRoot";
- $return = V::arrayToXML($this->items_results[$resultsPart], true, $xmlRoot);
- self::saveToLog("Wygenerowano plik XML ({$resultsPart})");
- return $return;
- }
- public function asArray($resultsPart = null, $subArray = null) {
- if (!$this->results) return null;
- if (!$this->items_results[$resultsPart]) $this->generateItemsResults($resultsPart);
- if (!$this->items_results[$resultsPart]) return null;
- if ($subArray) {
- if (isset($this->items_results[$resultsPart][$subArray])) return $this->items_results[$subArray];
- else return [];
- } else return $this->items_results[$resultsPart];
- }
- public function powiazaniaFound() {
- if ($this->results) return true;
- else return false;
- }
- public function generatePdfAndHtml() {
- $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
- if (!file_exists($antDir)) mkdir($antDir, 0770, true);
- if (!is_dir($antDir)) {
- $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików PDF i HTML";
- self::saveToLog("Nie wygenerowano plików PDF oraz HTML - problem z utworzeniem katalogu dla ant ({$resultsPart})");
- $this->saveProgress(['reportsCreated' => 1]);
- return;
- }
- $this->saveProgress(['step' => 'reports']);
- if ($this->getPartsCount()) {
- self::saveToLog("Generuję raporty w plikach PDF oraz HTML (liczba raportów do wygenerowania: {$this->getPartsCount()})");
- for ($i =0; $i < $this->getPartsCount(); $i++) $this->_generatePdfAndHtml($i);
- self::saveToLog("Zakończono generowanie raportów w plikach PDF oraz HTML");
- } else $this->_generatePdfAndHtml();
- }
- private function _generatePdfAndHtml($resultsPart = null) {
- $id_part = $resultsPart === null ? $this->ID : $this->ID . "_" . str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
- self::saveToLog("Generuję raport w pliku PDF oraz HTML ({$resultsPart})");
- $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.xml";
- $pdfDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.pdf";
- $htmlDestDir = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.html";
- $htmlZipDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.zip";
- $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
- $antXmlFilename = "relations-{$id_part}.out_task.dita.final_with_RelatedFeatureLoop.xml";
- $antXmlFile = $antDir . "/" . $antXmlFilename;
- $ditamapFile = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}/relations-{$id_part}.ditamap";
- $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";
- $htmlDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}/html";
- if (!file_exists($xmlFile)) $this->saveXml($resultsPart);
- if (!file_exists($xmlFile)) {
- $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików XML, PDF i HTML";
- self::saveToLog("Nie wygenerowano plików XML, PDF oraz HTML - problem z wygenerowaniem pliku XML ({$resultsPart})");
- $this->saveProgress(['reportsCreated' => 1]);
- return;
- }
- $this->saveProgress(['reportsCreated' => 0.05]);
- copy($xmlFile, $antXmlFile);
- self::saveToLog("Generuję plik przejściowy do wygenerowania plików PDF i HTML ({$resultsPart})");
- 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}");
- if (file_exists($ditamapFile))
- {
- self::saveToLog("Wygenerowano plik przejściowy");
- $this->saveProgress(['reportsCreated' => 0.15]);
- } else {
- self::saveToLog("Nie udało się wygenerować pliku przejściowego, przerywm");
- $this->saveProgress(['reportsCreated' => 1]);
- return;
- }
- self::saveToLog("Generuję plik PDF ({$resultsPart})");
- 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");
- if (file_exists($pdfFile)) {
- rename($pdfFile, $pdfDestFile);
- self::saveToLog("Wygenerowano plik PDF ({$resultsPart})");
- } else self::saveToLog("Nie udało się wygenerować pliku PDF ({$resultsPart})");
- $this->saveProgress(['reportsCreated' => 0.45]);
- self::saveToLog("Generuję pliki HTML ({$resultsPart})");
- 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");
- if (file_exists($htmlDir) && is_dir($htmlDir)) {
- 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");
- if (file_exists($htmlDestDir)) self::exec("rm -rf \"{$htmlDestDir}\"");
- self::exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
- self::saveToLog("Wygenerowano pliki HTML ({$resultsPart})");
- } else self::saveToLog("Nie udało się wygenerować plików HTML {$resultsPart})");
- $this->saveProgress(['reportsCreated' => 0.35]);
- }
- }
|