| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808 |
- <?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%';
- //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 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 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 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 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 dokonano dowolnych zmian w tabelach pracowników/kontrahentów.<br/>
- Pełne odświeżenie wymagane w przypadku modyfikacji baz KRS lub CEiDG (UWAGA - trwa to wiele godzin)
- </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;
- $this->truncatePowiazaniaFromDB($powiazanieID);
- $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
- 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
- foreach ($prID as $v) DB::getPDO()->insert($refPowiazaniaToPracownicy, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $v]);
- $refPowiazaniaToKontrahenci = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
- 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI');
- foreach ($kontrahenci as $kontrahent) DB::getPDO()->insert($refPowiazaniaToKontrahenci, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $kontrahent['ID']]);
- $refPowiazaniaToKwRequestedPreson = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
- 'default_db__x3A__BI_audit_KW_requested_person:BI_audit_KW_requested_person');
- 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 = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
- $pdfFile = "{$dir}/relations.pdf";
- $htmlFile = "{$dir}/html/relations-{$this->powiazanie['ID']}.html";
- $htmlZipFile = "{$dir}/html.zip";
- $url = $this->getUrl('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
- $pdfUrl = "{$url}/relations.pdf";
- $htmlUrl = "{$url}/html/relations-{$this->powiazanie['ID']}.html";
- $htmlZipUrl = "{$url}/html.zip";
- ?>
- <div class="container" style="margin-top:20px">
- <legend>
- Wygenerowany raport nr <?=$this->powiazanie['ID']?>
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <?php
- if (file_exists($pdfFile)) {
- ?>
- <a href="<?=$pdfUrl?>" target="_blank" class="btn btn-primary">Pokaż raport PDF</a>
- <?php
- }
- if (file_exists($htmlFile)) {
- ?>
- <a href="<?=$htmlUrl?>" target="_blank" class="btn btn-primary">Pokaż raport HTML</a>
- <?php
- }
- if (file_exists($htmlZipFile)) {
- ?>
- <a href="<?=$htmlZipUrl?>" target="_blank" download="Raport <?=$this->powiazanie['ID']?>.zip" class="btn btn-primary">Pobierz raport HTML</a>
- <?php
- }
- ?>
- <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 = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
- 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
- $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 dokonano dowolnych zmian w tabelach pracowników/kontrahentów.<br/>
- Pełne odświeżenie wymagane w przypadku modyfikacji baz KRS lub CEiDG (UWAGA - trwa to wiele godzin)
- </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 = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
- $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 class="containter" 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>
- </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 = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
- $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 function getRefsTables($namespace) {
- try {
- $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
- if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
- $fields = $item['field'];
- $refsTables = [];
- foreach ($fields as $field) {
- list($type, $child) = explode(":", $field['xsdType'], 2);
- if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) $refsTables[] = ACL::getRefTable($namespace, $child);
- }
- return $refsTables;
- } catch (Exception $e) {
- echo "{$namespace} - {$e->getMessage}";
- return [];
- }
- }
- private function truncatePowiazaniaFromDB($ID) {
- $refsTables = $this->getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
- if (!$refsTables) return null;
- $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
- 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
- $refsTables = array_diff($refsTables, [$refPowiazaniaToPowiazaniaRow]);
- $query = "delete from `" . implode("`, `", $refsTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
- foreach ($refsTables 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 function deleteResultsFromDB($ID) {
- $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
- 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
- $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
- 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
- $refsTables = $this->getRefsTables('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 ($refsTables 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() {
- function generatePhpScript($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("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");
- 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 = $this->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, 0755, true);
- if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
- ### 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', 'Part') 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' => 'Odświeżono 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 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 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 odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
- ];
- } else {
- $sqlArr = [
- 'FILE_STATUS_info' => 'W trakcie 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);
- $this->deleteResultsFromDB($row['ID']);
- $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
- $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
- $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
- 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";
- $generatePowiazaniaPdfFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pdf";
- $generatePowiazaniaHtmlDir = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.html";
- $generatePowiazaniaHtmlZipFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.zip";
- $error = false;
- $success = false;
- $sqlArr = [];
- if (file_exists($generatePowiazaniaResultFile)) {
- $generatePowiazaniaResult = file_get_contents($generatePowiazaniaResultFile);
- if ($generatePowiazaniaResult == "ok") {
- $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.xml";
- if (file_exists($xmlFile)) {
- if (filesize($xmlFile)) {
- $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
- if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0777, 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ł nieznany błąd - plk xml został wygenerowany niepoprawnie";
- } else $error = "Wystąpił nienzany błąd - nie znaleziono pliku xml";
- } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult})";
- } 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,
- ];
- $this->deleteResultsFromDB($row['ID']);
- if (file_exists($xmlFile)) unlink($xmlFile);
- } elseif ($success) {
- $sqlArr = [
- 'FILE_STATUS' => 'GENERATED',
- 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
- ];
- $destXmlFile = "{$powiazanieDirLocation}/relations.xml";
- $destPdfFile = "{$powiazanieDirLocation}/relations.pdf";
- $destHtmlDir = "{$powiazanieDirLocation}/html";
- $destHtmlZipFile = "{$powiazanieDirLocation}/html.zip";
- rename($xmlFile, $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 function reloadCache_reTeryt($full = false) {
- Lib::loadClass('Teryt');
- function reTeryt($table) {
- $tableConf = [
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
- 'kodPocztowy' => 'Kod_pocztowy',
- 'miejscowosc' => 'Miejscowosc',
- 'ulica' => 'Ulica',
- ],
- 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
- 'kodPocztowy' => 'kodPocztowy',
- 'miejscowosc' => 'miejscowosc',
- 'ulica' => 'ulica',
- ],
- 'BI_audit_KRS' => [
- 'wojewodztwo' => 'S_wojewodztwo',
- 'powiat' => 'S_powiat',
- 'gmina' => 'S_gmina',
- 'miejscowosc' => 'A_miejscowosc',
- 'ulica' => 'A_ulica',
- 'kodPocztowy' => 'A_kod',
- ],
- 'BI_audit_CEIDG' => [
- 'wojewodztwo' => 'wojewodztwo',
- 'powiat' => 'powiat',
- 'gmina' => 'gmina',
- 'miejscowosc' => 'miejscowosc',
- 'ulica' => 'ulica',
- 'kodPocztowy' => 'kodPocztowy',
- ],
- ];
- $columns = ['kodPocztowy', 'miejscowosc', 'ulica'];
- $query = "select * from `{$table}` where TERYT_SYM is null";
- try {
- $adresy = DB::getPDO()->fetchall($query);
- foreach ($adresy as $adres) {
- $search = [];
- foreach ($columns as $column) $search[$column] = $adres[$tableConf[$table][$column]];
- try {
- $teryt = Teryt::search($search);
- if ($teryt) {
- $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);
- }
- } catch (Exception $e) {
- }
- }
- } catch (Exception $e) {
- }
- }
- if ($full) {
- reTeryt('BI_audit_KRS');
- reTeryt('BI_audit_CEIDG');
- }
- reTeryt('BI_audit_ENERGA_RUM_KONTRAHENCI');
- reTeryt('BI_audit_ENERGA_PRACOWNICY_adresy');
- }
- private function reloadCache_updateAll($full = false) {
- $tables = [
- 'BI_audit_ENERGA_PRACOWNICY' => [
- 'fields' => [
- 'nip' => 'nip',
- 'regon' => 'regon',
- 'pesel' => 'pesel',
- ],
- 'base' => '0',
- //'where' => '',
- ],
- 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
- 'fields' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'nrBudynku',
- 'nrLokalu' => 'nrLokalu',
- ],
- 'base' => '0',
- //'where' => '',
- ],
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
- 'fields' => [
- 'krs' => 'KRS',
- 'nip' => 'NIP',
- 'regon' => 'REGON',
- 'pesel' => 'PESEL',
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'Numer_budynku',
- 'nrLokalu' => 'Numer_mieszkania_lokalu',
- ],
- 'base' => '0',
- 'where' => "ownCompany != 'Y'",
- ],
- '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' => '',
- ],
- ];
- $tables_full = [
- 'BI_audit_CEIDG' => [
- 'fields' => [
- 'nip' => 'nip',
- 'regon' => 'regon',
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'budynek',
- 'nrLokalu' => 'lokal',
- ],
- 'base' => '1',
- ],
- 'BI_audit_CEIDG_pelnomocnicy' => [
- 'fields' => [
- 'nip' => 'nip',
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'budynek',
- 'nrLokalu' => 'lokal',
- ],
- 'base' => '1',
- ],
- 'BI_audit_CEIDG_powiazania' => [
- 'fields' => [
- 'nip' => 'nip',
- 'regon' => 'regon',
- ],
- 'base' => '1',
- ],
- 'BI_audit_KRS' => [
- 'fields' => [
- 'krs' => 'krs',
- 'nip' => 'nip',
- 'regon' => 'regon',
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'A_nrDomu',
- 'nrLokalu' => 'A_nrLokalu',
- ],
- 'base' => '1',
- ],
- 'BI_audit_KRS_company' => [
- 'fields' => [
- 'regon' => 'regon',
- 'krs' => 'krs',
- ],
- 'base' => '1',
- ],
- 'BI_audit_KRS_person' => [
- 'fields' => [
- 'pesel' => 'pesel',
- ],
- 'base' => '1',
- ],
- ];
- if ($full) {
- $tables = array_merge($tables_full, $tables);
- $fullWhere = '1 = 1';
- } else {
- $fullWhere = 'BASE = 0';
- }
- $queries[] = "delete from BI_audit_ALL where {$fullWhere}";
- $queries[] = "delete from BI_audit_ALL_ref where {$fullWhere}";
- //$queries[] = "delete from BI_audit_ALL_ref_RELATIONS where {$fullWhere}"; // niepotrzebne
- foreach ($tables as $name => $table) {
- if (isset($table['where']) && $table['where']) $where = "where {$table['where']}";
- else $where = '';
- $queries[] = "insert into BI_audit_ALL (REMOTE_TABLE, REMOTE_ID, BASE, " . implode(", ", array_keys($table['fields'])) . ") select '{$name}', ID, '{$table['base']}', " . implode(", ", $table['fields']) . " from {$name} {$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[] = "update BI_audit_ALL set TERYT_SYM = null where TERYT_SYM = 0";
- $queries[] = "update BI_audit_ALL set TERYT_SYM_UL = null where TERYT_SYM_UL = 0";
- $queries[] = "update BI_audit_ALL set nrDomu = null where trim(nrDomu) = ''";
- $queries[] = "update BI_audit_ALL set nrLokalu = null where trim(nrLokalu) = ''";
- $queries[] = "update BI_audit_ALL set nrDomu = substring(nrDomu, 1, position('/' in nrDomu) - 1), nrLokalu = substring(nrDomu, position('/' in nrDomu ) + 1) where nrDomu rlike '^[[:digit:]]+.*/[[:digit:]]+.*$' and nrLokalu is null and {$fullWhere}";
- $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";
- if ($full) {
- $refCeidgToCeidgPelnomocnicy = ACL::getRefTable('default_db/BI_audit_CEIDG/BI_audit_CEIDG', "default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy");
- $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all1.ID, all2.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refCeidgToCeidgPelnomocnicy}` as ref on all1.REMOTE_TABLE = 'BI_audit_CEIDG' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_CEIDG_pelnomocnicy' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION";
- $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all2.ID, all1.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refCeidgToCeidgPelnomocnicy}` as ref on all1.REMOTE_TABLE = 'BI_audit_CEIDG' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_CEIDG_pelnomocnicy' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all2.REMOTE_TABLE = rel.RELATION";
- $refCeidgToCeidgPowiazania = ACL::getRefTable('default_db/BI_audit_CEIDG/BI_audit_CEIDG', "default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania");
- $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all1.ID, all2.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refCeidgToCeidgPowiazania}` as ref on all1.REMOTE_TABLE = 'BI_audit_CEIDG' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_CEIDG_powiazania' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION";
- $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all2.ID, all1.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refCeidgToCeidgPowiazania}` as ref on all1.REMOTE_TABLE = 'BI_audit_CEIDG' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_CEIDG_powiazania' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all2.REMOTE_TABLE = rel.RELATION";
- $refKrsToKrsCompany = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company");
- $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all1.ID, all2.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refKrsToKrsCompany}` as ref on all1.REMOTE_TABLE = 'BI_audit_KRS' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_KRS_company' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION";
- $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all2.ID, all1.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refKrsToKrsCompany}` as ref on all1.REMOTE_TABLE = 'BI_audit_KRS' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_KRS_company' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all2.REMOTE_TABLE = rel.RELATION";
- $refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
- $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all1.ID, all2.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refKrsToKrsPerson}` as ref on all1.REMOTE_TABLE = 'BI_audit_KRS' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_KRS_person' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION";
- $queries[] = "insert ignore into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all2.ID, all1.ID, rel.ID, 1 from BI_audit_ALL as all1 join `{$refKrsToKrsPerson}` as ref on all1.REMOTE_TABLE = 'BI_audit_KRS' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_KRS_person' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all2.REMOTE_TABLE = rel.RELATION";
- }
- $refPracownicyToPracownicyAdresy = ACL::getRefTable('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY', "default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy");
- $queries[] = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, BASE) select all1.ID, all2.ID, rel.ID, 0 from BI_audit_ALL as all1 join `{$refPracownicyToPracownicyAdresy}` as ref on all1.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY_adresy' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION";
- foreach ($queries as $query) DB::getPDO()->query($query);
- $BiAuditRelations = new BiAuditRelations($full);
- $query = "select ID from BI_audit_ALL where {$fullWhere} order by ID";
- $result = DB::query($query);
- while ($row = DB::fetch($result)) $BiAuditRelations->findRelations($row->ID);
- }
- public function doReloadCache($full = false) {
- $powiazaniaDirLocation = $this->getMainDirectory();
- $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
- $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
- $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
- file_put_contents($reloadCachePidFile, getmypid());
- try {
- $this->reloadCache_reTeryt($full);
- $this->reloadCache_updateAll($full);
- file_put_contents($reloadCacheResultFile, "ok");
- } catch (Exception $e) {
- file_put_contents($reloadCacheResultFile, $e->getMessage());
- }
- }
- public function doGeneratePowiazania($ID) {
- $powiazaniaDirLocation = $this->getMainDirectory();
- $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
- $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
- $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
- $pdfFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pdf";
- $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);
- if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
- file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
- $BiAuditPowiazania->saveToDb();
- $BiAuditPowiazania->generatePdfAndHtml($tasksDirLocation);
- /* $powiazania = $BiAuditPowiazania->asArray('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
- if (!$powiazania) return false;
- DB::getPDO()->query($query);
- foreach ($powiazania['BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row'] as $row) {
- $powiazaniaRowSqlArr = [];
- $string_concat_path = [];
- foreach ($row['object'] as $i => $object) {
- $powiazaniaRowObjectSqlArr = [];
- $table = array_keys($object)[0];
- if (!isset($tablesConf[$table])) throw new Exception("Błąd danych konfiguracyjnych");
- $concat = "table='{$table}'";
- if (isset($object['relation_from'])) $concat .= ";relation_from='{$object['relation_from']}'";
- foreach ($tablesConf[$table] as $field) {
- if ($object[$table][$field]) $concat .= ";{$field}='{$object[$table][$field]}'";
- }
- if ($i == 0) $powiazaniaRowSqlArr['string_concat_from'] = $concat;
- elseif ($i == count($row['object']) - 1) $powiazaniaRowSqlArr['string_concat_to'] = $concat;
- else $string_concat_path[] = $concat;
- }
- $powiazaniaRowSqlArr['string_concat_path'] = implode(' / ', $string_concat_path);
- $id_row = DB::getPDO()->insert("BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row", $powiazaniaRowSqlArr);
- if (!$id_row) throw new Exception("Błąd bazy danych");
- DB::getPDO()->insert('CRM__#REF_TABLE__25', ["PRIMARY_KEY" => $ID, "REMOTE_PRIMARY_KEY" => $id_row]);
- }
- */
- file_put_contents($resultFile, "ok");
- } catch (Exception $e) {
- file_put_contents($resultFile, $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 $full;
- private $relations = [
- 'nip' => ['nip'],
- 'regon' => ['regon'],
- 'krs' => ['krs'],
- 'pesel' => ['pesel'],
- 'adres' => ['TERYT_SYM', 'TERYT_SYM_UL', 'nrDomu', 'nrLokalu'],
- ];
- 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($full = false) {
- $this->full = $full;
- $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];
- }
- 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]) $ok++;
- }
- if ($ok / count($columns) > 0.5) {
- $joins[] = "(" . implode(" and ", $join) . ")";
- $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
- }
- }
- if (!$joins) return false;
- if ($this->full) $where = "where t1.ID = {$ID} and t2.ID > {$ID}";
- else $where = "where t1.ID = {$ID} and (t2.BASE = 1 or t2.ID > {$ID})";
- $query = "select t2.ID as ID, t1.REMOTE_TABLE as REMOTE_TABLE_1, t2.REMOTE_TABLE as REMOTE_TABLE_2 {$items}, t1.BASE * t2.BASE as BASE " .
- "from BI_audit_ALL t1 join BI_audit_ALL t2 on " . implode(" or ", $joins) . " {$where}";
- $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']})";
- 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']})";
- DB::getPDO()->query($query);
- }
- }
- }
- }
- class BiAuditPowiazania {
- private $minDepth;
- private $maxDepth;
- private $onlyTargets;
- private $ID;
- private $endNodes;
- private $path = [];
- private $results = [];
- private $items_results = [];
- private $relations = [];
- private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
- public function __construct($ID = 0) {
- if (!$ID) throw new Exception("Wrong ID parameter");
- $query = "select BI_analiza_minDepth, BI_analiza_maxDepth, BI_analiza_onlyTargets from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$ID}' and FILE_STATUS = 'IN_PROGRESS' and BI_analiza_reloadCache not in ('Full', 'Part')";
- $result = DB::getPDO()->fetchAll($query);
- if (!$result) throw new Exception("Błąd danych");
- $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) throw new Exception("Błąd danych - nieokreślono maksymalnej głębokości analizy");
- if ($this->minDepth > $this->maxDepth) throw new Exception("Wartość minimalnej głębokości analizy jest większa od wartości maksymalnej głębokości analizy");
- $this->ID = $ID;
- $subQueries = [];
- foreach ($this->destTables as $destTable) {
- $refTable = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "default_db__x3A__{$destTable}:{$destTable}");
- $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 = '{$ID}'";
- }
- $query = implode(" union ", $subQueries);
- $result = DB::getPDO()->fetchAll($query);
- if (!$result) throw new Exception("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
- $this->endNodes = array_map('reset', $result);
- $refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
- 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
- $query = "select `all`.ID as ID from BI_audit_ALL `all` join `{$refPowiazaniaToPracownicy}` ref
- on `all`.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and `all`.REMOTE_ID = ref.REMOTE_PRIMARY_KEY and ref.PRIMARY_KEY = '{$ID}'";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) $this->findPowiazania($row['ID']);
- }
- public function findPowiazania($ID, $relation = "", $end = 0) {
- if (isset($this->path[$ID])) return false;
- $this->path[$ID] = $relation;
- if (!$relation) $relation = 0;
- if ($end) {
- if (in_array($ID, $this->endNodes) && count($this->path) > $this->minDepth) $this->results[] = $this->path;
- array_pop($this->path);
- return true;
- }
- if (count($this->path) > $this->maxDepth) {
- if (!$this->onlyTargets) $this->results[] = $this->path;
- array_pop($this->path);
- return false;
- }
- $nodes = [];
- if ($relation) $where = "and ({$relation} & ref.RELATION_ID) != {$relation}";
- else $where = "";
- $query = "select ref.ID2, RELATION_ID, END from BI_audit_ALL_ref ref where ref.ID1 = '{$ID}' {$where}";
- $result = DB::query($query);
- while ($row = DB::fetch($result)) $nodes[$row->ID2] = ['relation' => (int) $row->RELATION_ID, 'end' => $row->END];
- foreach ($nodes as $node => $data) $this->findPowiazania($node, $data['relation'], $data['end']);
- array_pop($this->path);
- }
- private function relationName($ID) {
- 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 generateItemsResults() {
- $xmlRoot2 = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
- $xmlElements = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
- $this->items_results = [];
- $items_kontrahenci = [];
- $items_kw_person = [];
- $kontrahenci = [];
- $kw_person = [];
- $refUmowyToKontrahenci = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_UMOWY/BI_audit_ENERGA_RUM_UMOWY', 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI');
- $refKwRequestedToKwRequestedPerson = ACL::getRefTable('default_db/BI_audit_KW_requested/BI_audit_KW_requested', 'default_db__x3A__BI_audit_KW_requested_person:BI_audit_KW_requested_person');
- foreach ($this->results as $result) {
- $item_results = [];
- 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 = [$row['REMOTE_TABLE'] => (array) $obj];
- if ($rel) $item_result['relation_from'] = $this->relationName($rel);
- $item_results['object'][] = $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)) $umowy[] = (array) $obj;
- $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)) {
- $kw = [];
- while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
- $item_kw_person['ID'] = $row['REMOTE_ID'];
- $item_kw_person['BI_audit_KW_requested'] = $kw;
- $items_kw_person[] = $item_kw_person;
- }
- }
- }
- $this->items_results[$xmlRoot2][$xmlElements][] = $item_results;
- }
- $this->items_results[$xmlRoot2]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
- $this->items_results[$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;
- }
- public function saveToDb() {
- if (!$this->results) return null;
- $refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
- 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
- $refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
- 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
- foreach ($this->results as $result) {
- $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
- 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->relations[$rel]]);
- DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
- $ref = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
- "default_db__x3A__{$object['REMOTE_TABLE']}:{$object['REMOTE_TABLE']}");
- DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
- }
- }
- }
- public function asXml() {
- if (!$this->results) return null;
- if (!$this->items_results) $this->generateItemsResults();
- $xmlRoot = "RelatedFeatureRoot";
- return V::arrayToXML($this->items_results, true, $xmlRoot);
- }
- public function asArray($subArray = null) {
- if (!$this->results) return null;
- if (!$this->items_results) $this->generateItemsResults();
- if ($subArray) {
- if (isset($this->items_results[$subArray])) return $this->items_results[$subArray];
- else return [];
- } else return $this->items_results;
- }
- public function powiazaniaFound() {
- if ($this->results) return true;
- else return false;
- }
- public function generatePdfAndHtml($tasksDirLocation) {
- $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
- $pdfDestFile = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.pdf";
- $htmlDestDir = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.html";
- $htmlZipDestFile = "{$tasksDirLocation}/generatePowiazania-{$this->ID}.zip";
- $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
- $antXmlFilename = "relations-{$this->ID}.out_task.dita.final_with_RelatedFeatureLoop.xml";
- $antXmlFile = $antDir . "/" . $antXmlFilename;
- $pdfFile = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$this->ID}/pdf/relations-{$this->ID}.pdf";
- $htmlDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$this->ID}/html";
- if (!file_exists($antDir)) mkdir($antDir, 0755, true);
- if (!is_dir($antDir)) $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć pliku PDF";
- else {
- copy($xmlFile, $antXmlFile);
- shell_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-{$this->ID}");
- shell_exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$this->ID}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o pdf -i relations-{$this->ID}.ditamap -f pdf");
- if (file_exists($pdfFile)) rename($pdfFile, $pdfDestFile);
- shell_exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$this->ID}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o html -i relations-{$this->ID}.ditamap -f tocjs");
- if (file_exists($htmlDir) && is_dir($htmlDir)) {
- shell_exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$this->ID}\" && zip -r \"{$htmlZipDestFile}\" html");
- if (file_exists($htmlDestDir)) shell_exec("rm -rf \"{$htmlDestDir}\"");
- shell_exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
- }
- }
- }
- }
|