ID = $id; $uploader = new FileUploader($table.'_COLUMN', $record); $errMsg = ""; if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych
\n{$$errMsg}", 404); $uploader->findFolder(); return $uploader->getDestLocalPath(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
\n{$errMsg}", 404); return $folderConf['mount_point']; } private function initializePowiazaniaForm() { ?>
Generowanie powiązań :: powiazanie['L_APPOITMENT_INFO']?> # powiazanie['ID']?>

Wybierz pracowników, dla których mają zostać wyszukane powiązania

fetchall("select * from BI_audit_ENERGA_PRACOWNICY"); foreach ($pracownicy as $pracownik) { ?>
ID Imiona Nazwisko Pesel NIP Regon
Odśwież cache (wymagane w przypadku, gdy dokonano dowolnych zmian w tabelach pracowników/kontrahentów)
Anuluj
$this->powiazanie['ID'], 'FILE_STATUS' => 'TO_GENERATE', 'BI_analiza_employees' => implode(',', $prID), ]; if ($reloadCache == 'on') $sqlArr['BI_analiza_reloadCache'] = 'Y'; $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Y'"; $result = DB::getPDO()->fetchValue($query); if ($result) $sqlArr['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache (wymagane dla innego rekordu)'; elseif ($reloadCache == 'on') $sqlArr['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache'; else $sqlArr['FILE_STATUS_info'] = "Oczekuje na wygenerowanie powiązań"; $affected = DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr); if ($affected) { SE_Layout::alert('success','Oznaczono rekord do wygenerowania'); ?>
Powrót
initializePowiazaniaSave(); break; default: $this->initializePowiazaniaForm(); } } private function showPowiazania() { // $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']); // $xmlFile = "{$powiazanieDirLocation}/relations.xml"; // echo "
" . htmlentities(file_get_contents($xmlFile)) . "
"; echo "Statystyki znalezionych powiązań [TODO]"; } private function powiazania($ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA) { try { $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA}'"); 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"); } } catch (Exception $e) { SE_Layout::alert('danger',$e->getMessage()); $_SESSION['REFERER'] = $this->REFERER; ?>
Powrót
REFERER = $_SESSION['REFERER']; unset($_SESSION['REFERER']); } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST); else $this->REFERER=$_SERVER['HTTP_REFERER']; if (V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int') > 0) $this->powiazania(V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')); else SE_Layout::alert('danger','Błąd parametru'); SE_Layout::dol(); } public function doGenerate() { function deleteResultsFromDB($ID) { $query = "delete from row, ref using BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row row join `CRM__#REF_TABLE__25` ref on row.ID=ref.REMOTE_PRIMARY_KEY where ref.PRIMARY_KEY='{$ID}'"; DB::getPDO()->query($query); } function generatePhpScript($function) { return '' . $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"; $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 $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Y' and FILE_STATUS = 'TO_GENERATE'"; $result = DB::getPDO()->fetchAll($query); if ($result) { $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' => 'N', ]; } 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($reloadCacheResultFile); } } else { $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'"; $result = DB::getPDO()->fetchValue($query); if ($result) { $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', ]; file_put_contents($reloadCachePhpFile, generatePhpScript('doReloadCache()')); 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ń $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; $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); 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, BI_analiza_depth 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"; if (file_exists($generatePowiazaniaResultFile)) { $error = false; $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.xml"; if (file_exists($xmlFile)) { if (filesize($xmlFile)) { $generatePowiazaniaResult = file_get_contents($generatePowiazaniaResultFile); if ($generatePowiazaniaResult == "ok") { $generatePowiazaniaSqlFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.sql"; if (!file_exists($generatePowiazaniaSqlFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu"; } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult})"; } else $error = "Wystąpił nieznany błąd - plk xml został wygenerowany niepoprawnie"; } else $error = "Wystąpił nienzany błąd - nie znaleziono pliku xml"; if ($error) { $sqlArr = [ 'FILE_STATUS' => 'ERROR', 'FILE_STATUS_info' => $error, ]; deleteResultsFromDB($row['ID']); if (file_exists($xmlFile)) unlink($xmlFile); } else { $sqlArr = [ 'FILE_STATUS' => 'GENERATED', 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania', ]; $powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']); $destXmlFile = "{$powiazanieDirLocation}/relations.xml"; rename($xmlFile, $destXmlFile); } $sqlArr['ID'] = $row['ID']; DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr); $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php"; unlink($generatePowiazaniaPhpFile); unlink($generatePowiazaniaPidFile); unlink($generatePowiazaniaResultFile); if (file_exists($generatePowiazaniaSqlFile)) unlink($generatePowiazaniaSqlFile); } elseif (file_exists($generatePowiazaniaPidFile)) { $pid = file_get_contents($generatePowiazaniaPidFile); } } } catch (Exception $e) { echo $e->getMessage()."\n"; } } private function reloadCache_reTeryt() { 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', ], ]; $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) { } } // reTeryt('BI_audit_ENERGA_RUM_KONTRAHENCI'); reTeryt('BI_audit_ENERGA_PRACOWNICY_adresy'); } private function reloadCache_updateAll() { $tables = [ 'BI_audit_ENERGA_PRACOWNICY' => [ 'fields' => [ 'nip' => 'nip', 'regon' => 'regon', 'pesel' => 'pesel', ], //'where' => '', ], 'BI_audit_ENERGA_PRACOWNICY_adresy' => [ 'fields' => [ 'TERYT_SYM' => 'TERYT_SYM', 'TERYT_SYM_UL' => 'TERYT_SYM_UL', 'nrDomu' => 'nrBudynku', 'nrLokalu' => 'nrLokalu', ], //'where' => '', ], 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [ 'fields' => [ 'nip' => 'NIP', 'regon' => 'REGON', 'pesel' => 'PESEL', 'TERYT_SYM' => 'TERYT_SYM', 'TERYT_SYM_UL' => 'TERYT_SYM_UL', 'nrDomu' => 'Numer_budynku', 'nrLokalu' => 'Numer_mieszkania_lokalu', ], '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', ], //'where' => '', ], ]; $queries[] = "delete from BI_audit_ALL where BASE = 0"; $queries[] = "delete from BI_audit_ALL_ref where BASE = 0"; $queries[] = "delete from BI_audit_ALL_ref_RELATIONS where BASE = 0"; 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, " . implode(", ", array_keys($table['fields'])) . ") select '{$name}', ID, " . implode(", ", $table['fields']) . " from {$name} {$where}"; } $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 BASE = 0"; $queries[] = "set @var = (select round(coalesce(max(ID), '0.5')) from BI_audit_ALL_ref_RELATIONS)"; $queries[] = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) select @var:=@var*2, a.RELATION from (select a.REMOTE_TABLE as RELATION 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) as a left join BI_audit_ALL_ref_RELATIONS r on a.RELATION = r.RELATION where r.RELATION is null"; $queries[] = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID) select all1.ID, all2.ID, rel.ID from BI_audit_ALL as all1 join `BI_audit_ENERGA_PRACOWNICY` as pracownicy on all1.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and all1.REMOTE_ID = pracownicy.ID join BI_audit_ENERGA_PRACOWNICY_adresy as adresy on pracownicy.ID = adresy.ID_BI_audit_ENERGA_PRACOWNICY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY_adresy' and adresy.ID = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION"; $queries[] = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID) select all2.ID, all1.ID, rel.ID from BI_audit_ALL as all1 join `BI_audit_ENERGA_PRACOWNICY` as pracownicy on all1.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and all1.REMOTE_ID = pracownicy.ID join BI_audit_ENERGA_PRACOWNICY_adresy as adresy on pracownicy.ID = adresy.ID_BI_audit_ENERGA_PRACOWNICY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY_adresy' and adresy.ID = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all2.REMOTE_TABLE = rel.RELATION"; foreach ($queries as $query) DB::getPDO()->query($query); $BiAuditRelations = new BiAuditRelations(); $query = "select ID from BI_audit_ALL where BASE = 0"; $result = DB::query($query); while ($row = DB::fetch($result)) $BiAuditRelations->findRelations($row->ID); } public function doReloadCache() { $powiazaniaDirLocation = $this->getMainDirectory(); $tasksDirLocation = $powiazaniaDirLocation . "/.tasks"; $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result"; try { $this->reloadCache_reTeryt(); $this->reloadCache_updateAll(); 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"; $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid"; $sqlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.sql"; 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 { $query = "select BI_analiza_depth, BI_analiza_employees, A_ADM_COMPANY, A_CLASSIFIED from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$ID}' and FILE_STATUS = 'IN_PROGRESS' and BI_analiza_reloadCache != 'Y'"; $result = DB::getPDO()->fetchAll($query); if (!$result) throw new Exception("Błąd danych"); $powiazanie = $result[0]; if (!preg_match('/^[[:digit:]]+(,[[:digit:]]+)*$/', $powiazanie['BI_analiza_employees'])) throw new Exception("Błąd danych"); $query = "select ID from BI_audit_ALL where REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and REMOTE_ID in ({$powiazanie['BI_analiza_employees']})"; $result = DB::getPDO()->fetchAll($query); $BiAuditPowiazania = new BiAuditPowiazania($powiazanie['BI_analiza_depth']); foreach ($result as $row) $BiAuditPowiazania->findPowiazania($row['ID']); if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań"); $xml = $BiAuditPowiazania->asXml(); file_put_contents($xmlFile, $xml); file_put_contents($sqlFile, mysql_real_escape_string(gzcompress($xml))); $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); $powiazaniaRowSqlArr['A_ADM_COMPANY'] = $powiazanie['A_ADM_COMPANY']; $powiazaniaRowSqlArr['A_CLASSIFIED'] = $powiazanie['A_CLASSIFIED']; $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'] = <<has_errors()) { throw new Exception("DB Errors: " . implode("\n
", $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
", $db->get_errors())); } } } } class BiAuditRelations { private $RELATIONS_ID = []; 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']; 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]; } 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; $query = "select t2.ID as ID, t1.REMOTE_TABLE as REMOTE_TABLE_1, t2.REMOTE_TABLE as REMOTE_TABLE_2 {$items} " . "from BI_audit_ALL t1 join BI_audit_ALL t2 on " . implode(" or ", $joins) . " where t1.ID = {$ID} and (t2.BASE = 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); } $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0); $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0); if (!$end1) { $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2})"; DB::getPDO()->query($query); } if (!$end2) { $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1})"; DB::getPDO()->query($query); } } } } class BiAuditPowiazania { private $DEPTH; private $path = []; private $results = []; private $items_results = []; private $relations = []; public function __construct($depth = 0) { $this->DEPTH = (int) $depth; } public function findPowiazania($ID, $relation = "", $end = 0) { if (isset($this->path[$ID])) return false; $this->path[$ID] = $relation; if (!$relation) $relation = 0; if ($end) { $this->results[] = $this->path; array_pop($this->path); return true; } if (count($this->path) > $this->DEPTH) { 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 = []; // $refTableUmowyToKontrahenci = 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'); // $refTableKwToKwPerson = 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'); // echo "{$refTableUmowyToKontrahenci} :: {$refTableKwToKwPerson} \n"; // $refTablePowiazaniaToPowiazaniaRow = 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'); // echo ":: " . $refTablePowiazaniaToPowiazaniaRow . "::\n"; 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 `CRM__#REF_TABLE__23` 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 `CRM__#REF_TABLE__24` 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 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; } }