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 static function getUrl($table, $id) {
$folderConf = FoldersConfig::getAll($table.'_COLUMN');
$record = new stdClass;
$record->ID = $id;
$uploader = new FileUploader($table.'_COLUMN', $record);
$errMsg = "";
if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych
\n{$errMsg}", 404);
return $uploader->getFolderWeb() . "/" . $uploader->getDestFolder(true);
}
private static function getMainDirectory() {
$folderConf = FoldersConfig::getAll('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_COLUMN');
if (!isset($folderConf['mount_point'])) throw new HttpException("Błąd danych konfiguracyjnych
\n{$errMsg}", 404);
return $folderConf['mount_point'];
}
private static function parseNipRegon($string) {
$nip = null; $regon = null;
preg_match('/^(.*[^[:digit:]])?([[:digit:]]{10})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
if (!empty($matches[2])) $nip = trim($matches[2]);
if ($nip && !V::isNip($nip)) $nip = null;
preg_match('/^(.*[^[:digit:]])?([[:digit:]]{9})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
if (!empty($matches[2])) $regon = trim($matches[2]);
if ($regon && !V::isRegon($regon)) $regon = null;
return [$nip, $regon];
}
private function initializePowiazaniaForm() {
?>
buildQuery(['limit' => 0, 'cols' => ['ID']]);
$kontrahenci = $queryFeatures->getItems();
$acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_KW_requested_person/BI_audit_KW_requested_person');
$queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
$requestedPersons = $queryFeatures->getItems();
if (!($kontrahenci || $requestedPersons)) throw new Exception("Nie znaleziono żadnego obiektu końcowego");
$sqlUpdate = ['FILE_STATUS' => 'TO_GENERATE'];
$reloadCache = V::get('reloadCache', 'No', $_POST);
$reloadCacheAvailable = ['Full', 'Part', 'No'];
if (!in_array($reloadCache, $reloadCacheAvailable)) throw new Exception("Błąd formularza!");
$sqlUpdate['BI_analiza_reloadCache'] = $reloadCache;
$query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part')";
$result = DB::getPDO()->fetchValue($query);
if ($result) $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache (wymagane dla innego rekordu)';
elseif ($reloadCache != 'No') $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache';
else $sqlUpdate['FILE_STATUS_info'] = "Oczekuje na wygenerowanie powiązań";
if ($this->powiazanie) { // wyzwolone z poziomu tabeli BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA - aktualizujemy istniejący rekord
$powiazanieID = $this->powiazanie['ID'];
} else { // wyzwolone z poziomu tabeli BI_audit_ENERGA_PRACOWNICY - dodajemy nowy rekord
if (count($prID) != 1) throw new Exception("Błąd formularza!");
if (!($lAppoitmentInfo = V::get('info', false, $_POST))) throw new Exception("Błąd formularza!");
if (!($BiAnalizaMinDepth = V::get('minDepth', false, $_POST))) throw new Exception("Błąd formularza!");
if (!($BiAnalizaMaxDepth = V::get('maxDepth', false, $_POST))) throw new Exception("Błąd formularza!");
if (!($BiAnalizaOnlyTargets = V::get('onlyTargets', false, $_POST))) throw new Exception("Błąd formularza!");
$query = "select * from BI_audit_ENERGA_PRACOWNICY where ID='{$prID[0]}'";
$result = DB::getPDO()->fetchFirst($query);
if (!$result) throw new Exception("Błąd formularza!");
$sqlInsert = [
'L_APPOITMENT_INFO' => $lAppoitmentInfo,
'A_STATUS' => 'NORMAL',
'A_STATUS_INFO' => 'Dodane przez BiAuditGenerate z poziomu tabeli BI_audit_ENERGA_PRACOWNICY',
'A_ADM_COMPANY' => $result['A_ADM_COMPANY'],
'A_CLASSIFIED' => $result['A_CLASSIFIED'],
'FILE_STATUS' => 'NONE',
'FILE_STATUS_info' => 'Oczekuję na zdefiniowanie danych wejściowych',
'BI_analiza_reloadCache' => $sqlUpdate['BI_analiza_reloadCache'],
'BI_analiza_minDepth' => $BiAnalizaMinDepth,
'BI_analiza_maxDepth' => $BiAnalizaMaxDepth,
'BI_analiza_onlyTargets' => $BiAnalizaOnlyTargets,
];
$powiazanieID = DB::getDB()->ADD_NEW_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', (object)$sqlInsert);
if ($powiazanieID) SE_Layout::alert('success','Dodano rekord do wygenerowania powiązań');
else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
}
$sqlUpdate['ID'] = $powiazanieID;
self::truncatePowiazaniaFromDB($powiazanieID);
$refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
foreach ($prID as $v) DB::getPDO()->insert($refPowiazaniaToPracownicy, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $v]);
$refPowiazaniaToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
foreach ($kontrahenci as $kontrahent) DB::getPDO()->insert($refPowiazaniaToKontrahenci, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $kontrahent['ID']]);
$refPowiazaniaToKwRequestedPreson = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_KW_requested_person', true);
foreach ($requestedPersons as $requestedPerson) DB::getPDO()->insert($refPowiazaniaToKwRequestedPreson, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $requestedPerson['ID']]);
$affected = DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlUpdate);
if ($affected) {
if ($this->powiazanie) {
SE_Layout::alert('success','Oznaczono rekord do wygenerowania powiązań');
?>
initializePowiazaniaSave();
break;
default:
$this->initializePowiazaniaForm();
}
}
private function showPowiazania() {
// echo "Statystyki znalezionych powiązań [TODO]";
$dir = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
$url = self::getUrl('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
$reports = [
'pdf' => [
'files' => glob("{$dir}/relations*.pdf"),
'label' => 'Raporty PDF:
',
'button' => 'Pokaż raport PDF',
'regex' => "/^relations(-{$this->powiazanie['ID']})?_([[:digit:]]+)\.pdf$/",
'parentDir' => false,
],
'html' => [
'files' => glob("{$dir}/html*/relations-{$this->powiazanie['ID']}*.html"),
'label' => 'Raporty HTML
do przeglądania:',
'button' => 'Pokaż raport HTML',
'regex' => "/^relations-({$this->powiazanie['ID']})_([[:digit:]]+)\.html$/",
'parentDir' => true,
],
'htmlZip' => [
'files' => glob("{$dir}/html*.zip"),
'label' => 'Raporty HTML
do pobrania:',
'button' => 'Pobież raport HTML',
'regex' => "/^html(-{$this->powiazanie['ID']})?_([[:digit:]]+)\.zip$/",
'parentDir' => false,
],
];
?>
\n";
});
?>
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");
?>
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;
?>
importKrsToPracownicySearch();
break;
default: $this->importKrsToPracownicyForm();
}
}
private function importKrsToPracownicyForm() {
?>
'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'];
}
?>
SOURCE['ID']}'";
$result = DB::getPDO()->fetchFirst($query);
?>
REFERER = $_SESSION['REFERER'];
unset($_SESSION['REFERER']);
} elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
else $this->REFERER=$_SERVER['HTTP_REFERER'];
if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
elseif (($ID = V::get('ID_BI_audit_KRS', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS';
elseif (($ID = V::get('ID_BI_audit_KRS_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS_person';
if ($this->SOURCE) {
$this->SOURCE['ID'] = $ID;
$this->powiazania();
}
elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
switch ($TABLE) {
case "default_db/BI_audit_ENERGA_PRACOWNICY":
$this->importKrsToPracownicy();
break;
default: SE_Layout::alert('danger', 'Błąd parametru');
}
}
else SE_Layout::alert('danger', 'Błąd parametru');
SE_Layout::dol();
}
private static function truncatePowiazaniaFromDB($ID) {
$refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
if (!$refTables) return null;
$refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
$refTables = array_diff($refTables, [$refPowiazaniaToPowiazaniaRow]);
$query = "delete from `" . implode("`, `", $refTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
foreach ($refTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
$query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
DB::getPDO()->query($query);
}
private static function deleteResultsFromDB($ID) {
$refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
$refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
$refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
$sqlDeleteFrom = "delete from
`{$refPowiazaniaToPowiazaniaRow}`,
`BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
`{$refPowiazaniaRowToPowiazaniaRowObject}`,
`BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
$sqlUsing = "
using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
$sqlWhere = "
where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
foreach ($refTables as $refTable) {
$sqlDeleteFrom .= ",\n`{$refTable}`";
$sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
}
$query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
DB::getPDO()->query($query);
}
public function doGenerate() {
$generatePhpScript = function($function) {
return '' . $function . ';
';
};
try {
### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
$_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
$moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
### Ustawienie zmiennych
$powiazaniaDirLocation = self::getMainDirectory();
$tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
$reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
$reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
$reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
$reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
### Utworzenie niezbędnych katalogów i plików
if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0770, true);
if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
### Wyłączenie wcześniej używanego mechanizmu wymuszania częściowego odświeżania cache - teraz działa to z automatu
$sqlArr = [
'BI_analiza_reloadCache' => 'No',
];
$query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Part') and FILE_STATUS = 'TO_GENERATE'";
$result = DB::getPDO()->fetchAll($query);
foreach ($result as $row) {
DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
}
### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
$doGenerate = true;
$query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full') and FILE_STATUS = 'TO_GENERATE'";
$result = DB::getPDO()->fetchAll($query);
if ($result) {
$doGenerate = false;
$sqlArr = [];
if (file_exists($reloadCachePhpFile)) {
if (file_exists($reloadCacheResultFile)) {
$reloadCacheResult = file_get_contents($reloadCacheResultFile);
if ($reloadCacheResult == "ok") {
$sqlArr = [
'FILE_STATUS_info' => 'Ukończono pełne Odświeżenie cache, oczekiwanie na wygenerowanie powiązań',
'BI_analiza_reloadCache' => 'No',
];
$doGenerate = true;
} else {
$sqlArr = [
'FILE_STATUS' => 'ERROR',
'FILE_STATUS_info' => "Wystąpił błąd podczas pełnego odświeżania cache ({$reloadCacheResult})",
];
$query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
$result = DB::getPDO()->fetchAll($query);
}
unlink($reloadCachePhpFile);
unlink($reloadCachePidFile);
unlink($reloadCacheResultFile);
} elseif (file_exists($reloadCachePidFile)) {
$pid = file_get_contents($reloadCachePidFile);
$processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
$processShouldBeRunning = "php {$reloadCachePhpFile}";
if ($processRunning != $processShouldBeRunning) {
if (!file_exists($reloadCacheResultFile)) {
$sqlArr = [
'FILE_STATUS' => 'ERROR',
'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas pełnego odświeżania cache - nie znaleziono procesu potomnego",
];
$query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
$result = DB::getPDO()->fetchAll($query);
unlink($reloadCachePhpFile);
unlink($reloadCachePidFile);
unlink($reloadCacheResultFile);
}
}
}
} else {
$query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
$result2 = DB::getPDO()->fetchValue($query);
if ($result2) {
$sqlArr = [
'FILE_STATUS_info' => 'Wstrzymano pełne odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
];
} else {
$sqlArr = [
'FILE_STATUS_info' => 'W trakcie pełnego odświeżania cache',
];
$query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
$fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
file_put_contents($reloadCachePhpFile, $generatePhpScript("doReloadCache({$fullReloadCache})"));
shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
}
}
if ($sqlArr) {
foreach ($result as $row) {
DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
}
}
}
### Generowanie powiązań
if ($doGenerate) {
$query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
$result = DB::getPDO()->fetchAll($query);
foreach ($result as $row) {
$sqlArr = [
'ID' => $row['ID'],
'FILE_STATUS' => 'IN_PROGRESS',
'FILE_STATUS_info' => 'W trakcie generowania powiązań',
];
DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
self::deleteResultsFromDB($row['ID']);
$generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
$generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
$generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
$generatePowiazaniaProgressFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.progress";
if (file_exists($generatePowiazaniaResultFile)) unlink ($generatePowiazaniaResultFile);
if (file_exists($generatePowiazaniaProgressFile)) unlink ($generatePowiazaniaProgressFile);
file_put_contents($generatePowiazaniaPhpFile, $generatePhpScript("doGeneratePowiazania({$row['ID']})"));
shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
}
}
### Weryfikacja świeżo wygenerowanych powiązań
$query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
$result = DB::getPDO()->fetchAll($query);
foreach ($result as $row) {
$generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
$generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
$generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
$error = false;
$success = false;
$sqlArr = [];
if (file_exists($generatePowiazaniaResultFile)) {
$generatePowiazaniaResult = json_decode(file_get_contents($generatePowiazaniaResultFile), true);
if ($generatePowiazaniaResult['result'] == "ok") {
$powiazanieDirLocation = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0770, false);
if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
else $success = true;
} else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult['message']})";
} elseif (file_exists($generatePowiazaniaPidFile)) {
$pid = file_get_contents($generatePowiazaniaPidFile);
$processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
$processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
if ($processRunning != $processShouldBeRunning) {
if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
}
}
if ($error) {
$sqlArr = [
'FILE_STATUS' => 'ERROR',
'FILE_STATUS_info' => $error,
];
self::deleteResultsFromDB($row['ID']);
//if (file_exists($xmlFile)) unlink($xmlFile);
} elseif ($success) {
$sqlArr = [
'FILE_STATUS' => 'GENERATED',
'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
];
if ($generatePowiazaniaResult['parts']) {
for ($i = 1; $i <= $generatePowiazaniaResult['parts']; $i++) {
$partNo = str_pad($i, 6, '0', STR_PAD_LEFT);
$generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}_{$partNo}";
$generatePowiazaniaXmlFile = "{$generateFilesName}.xml";
$generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
$generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
$generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
$destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.xml";
$destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.pdf";
$destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}";
$destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}.zip";
if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
if (file_exists($generatePowiazaniaHtmlDir)) {
if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
rename($generatePowiazaniaHtmlDir, $destHtmlDir);
}
if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
}
} else {
$generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}";
$generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
$generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
$generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
$destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.xml";
$destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.pdf";
$destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}";
$destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}.zip";
if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
if (file_exists($generatePowiazaniaHtmlDir)) {
if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
rename($generatePowiazaniaHtmlDir, $destHtmlDir);
}
if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
}
}
if ($sqlArr) {
$sqlArr['ID'] = $row['ID'];
DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
}
}
} catch (Exception $e) {
echo $e->getMessage()."\n";
}
}
private static function importPracownicy() { //TODO
$fields = [
'BI_audit_ENERGA_PRACOWNICY' => [
'PERNR',
'imiona',
'nazwisko',
'pesel',
'nr_konta',
'jednostka_organizacyjna',
'nip',
'regon',
'source',
],
'BI_audit_ENERGA_PRACOWNICY_adresy' => [
'kodPocztowy',
'miejscowosc',
'ulica',
'nrBudynku',
'nrLokalu',
],
];
$query = "select * from `BI_audit_ENERGA_PRACOWNICY_import` where `importResult` = 'none'";
$pracownicy = DB::getPDO()->query($query);
while ($pracownik = $pracownicy->fetch()) {
$ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `pesel` = '{$pracownik['pesel']}'");
$sqlArr = [];
foreach ($fields['BI_audit_ENERGA_PRACOWNICY'] as $field) $sqlArr[$field] = trim($pracownik[$field]);
if ($ID_pracownik) DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY', 'ID', $ID, $sqlArr);
else $ID_pracownik = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', $sqlArr);
$sqlArr = [];
foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $field) {
$sqlArr[$field] = trim($pracownik[$field]);
if (!$sqlArr[$field]) unset($sqlArr[$field]);
}
if (!$sqlArr) break;
$sql = [];
// foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $field) {
// if (isset($sqlArr[$field])) $sql[] = "`{$field}` = " . DUPA;
// }
}
}
private static function reloadCache_parseUmowy($full = false) {
$fields = [
'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
'Tytul_dokumentu',
'Pelna_nazwa_kontrahenta',
'NIP',
'REGON',
'KRS',
'Kraj',
'Kod_pocztowy',
'Miejscowosc',
'Ulica',
'Numer_budynku',
'Numer_mieszkania_lokalu',
'TERYT_SYM',
'TERYT_SYM_UL',
],
'BI_audit_KRS' => [
'"Zaimportowanoz KRS na podstawie umowy"',
'nazwa',
'nip',
'regon',
'krs',
'A_kraj',
'A_kod',
'A_miejscowosc',
'A_ulica',
'A_nrDomu',
'A_nrLokalu',
'TERYT_SYM',
'TERYT_SYM_UL',
],
'BI_audit_CEIDG' => [
'"Zaimportowano z CEiDG na podstawie umowy"',
'firma',
'nip',
'regon',
'null',
'kraj',
'kodPocztowy',
'miejscowosc',
'ulica',
'budynek',
'lokal',
'TERYT_SYM',
'TERYT_SYM_UL',
],
];
$refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
if ($full) {
DB::getPDO()->query("truncate table `{$refTable}`");
DB::getPDO()->query("update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
}
$query = <<query($query);
$query = "select `ID`, `Strony_umowy` from `BI_audit_ENERGA_RUM_UMOWY` where `A_STATUS` = 'WAITING'";
$result = DB::getPDO()->fetchAll($query);
foreach ($result as $row) {
$ID = $row['ID'];
$strony = array_map('trim', explode("|", $row['Strony_umowy']));
$K_IDs = [];
foreach ($strony as $item) {
$strona = array_map('trim', explode(";", $item));
$nr = null;
if (count($strona) == 3) $i = 1;//$nr = $strona[1];
elseif (count($strona) == 4) $i = 2;//$nr = $strona[2];
elseif (count($strona) >= 5 && count($strona) <= 6) $i = 3;//$nr = $strona[3];
else $i = null;
if ($i) $nr = $strona[$i];
$notFound = false;
if (is_numeric($nr)) {
$query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Numer_kontrahenta = '{$nr}'";
if ($K_ID = DB::getPDO()->fetchValue($query)) {
$K_IDs[] = $K_ID;
} else {
$nazwa = $strona[$i+1];
$query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Pelna_nazwa_kontrahenta = '" . addslashes($nazwa) . "'";
if ($result2 = DB::getPDO()->fetchAll($query)) {
foreach ($result2 as $item) $K_IDs[] = $item['ID'];
} else $notFound = true;
}
} else $notFound = true;
if ($notFound) {
list($nip, $regon) = self::parseNipRegon($item);
if ($nip || $regon) {
$query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where NIP = '{$nip}' or REGON = '{$regon}'";
if ($result2 = DB::getPDO()->fetchall($query)) {
foreach ($result2 as $item) $K_IDs[] = $item['ID'];
} else {
$query = "select ID from BI_audit_KRS where nip = '{$nip}' or regon = '{$regon}'";
if ($result2 = DB::getPDO()->fetchall($query)) {
foreach ($result2 as $item) {
$query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
" select " . implode(', ', $fields['BI_audit_KRS']) . " from BI_audit_KRS where ID = '{$item['ID']}'";
if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
}
} else {
$query = "select ID from BI_audit_CEIDG where nip = '{$nip}' or regon = '{$regon}'";
if ($result2 = DB::getPDO()->fetchall($query)) {
foreach ($result2 as $item) {
$query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
" select " . implode(', ', $fields['BI_audit_CEIDG']) .
" from BI_audit_CEIDG where ID = '{$item['ID']}'";
if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
}
}
}
}
}
}
}
foreach ($K_IDs as $K_ID) {
if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
DB::getPDO()->query("insert into `{$refTable}` (PRIMARY_KEY, REMOTE_PRIMARY_KEY) values ({$ID}, {$K_ID})");
}
}
DB::getPDO()->update('BI_audit_ENERGA_RUM_UMOWY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
}
$query = "select ID, NIP, REGON, KRS from BI_audit_ENERGA_RUM_KONTRAHENCI where (NIP is null or REGON is null or KRS is null) and not (NIP is null and REGON is null and KRS is null) and `cached` = 0";
$result = DB::getPDO()->fetchAll($query);
foreach ($result as $row) {
$query = "select nip, regon, krs from BI_audit_KRS where nip = '{$row['NIP']}' or regon = '{$row['REGON']}' or krs = '{$row['KRS']}'";
if ($items = DB::getPDO()->fetchAll($query)) {
list($nip, $regon, $krs) = [$items[0]["nip"], $items[0]["regon"], $items[0]["krs"]];
if (count($items) > 1) {
for ($i = 1; $i < count($items); $i++) {
if ($nip != $items[$i]["nip"]) $nip = null;
if ($regon != $items[$i]["regon"]) $regon = null;
if ($krs != $items[$i]["krs"]) $krs = null;
}
}
$set = [];
if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
if ($krs && $krs != $row['KRS']) $set[] = "KRS = '{$krs}'";
if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row['ID']}'");
}
}
$query = "select ID, NIP, REGON from BI_audit_ENERGA_RUM_KONTRAHENCI where (NIP is null or REGON is null) and not (NIP is null and REGON is null) and `cached` = 0";
$result = DB::getPDO()->fetchAll($query);
foreach ($result as $row) {
$query = "select nip, regon from BI_audit_CEIDG where nip = '{$row['NIP']}' or regon = '{$row['REGON']}'";
if ($items = DB::getPDO()->fetchAll($query)) {
list($nip, $regon) = [$items[0]["nip"], $items[0]["regon"]];
if (count($items) > 1) {
for ($i = 1; $i < count($items); $i++) {
if ($nip != $items[$i]["nip"]) $nip = null;
if ($regon != $items[$i]["regon"]) $regon = null;
}
}
$set = [];
if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row->ID}'");
}
}
}
public static function reloadCache_reTeryt($full = false, $forceAll = false) {
Lib::loadClass('Teryt');
$tables = [
'BI_audit_CEIDG' => [
'fields' => [
'wojewodztwo' => 'wojewodztwo',
'powiat' => 'powiat',
'gmina' => 'gmina',
'miejscowosc' => 'miejscowosc',
'ulica' => 'ulica',
'kodPocztowy' => 'kodPocztowy',
],
'fieldsTeryt' => [
'TERYT_SYM' => 'TERYT_SYM',
'TERYT_SYM_UL' => 'TERYT_SYM_UL',
'nrDomu' => 'budynek',
'nrLokalu' => 'lokal',
],
'base' => '1',
],
'BI_audit_CEIDG_pelnomocnicy' => [
'fields' => [
'wojewodztwo' => 'wojewodztwo',
'powiat' => 'powiat',
'gmina' => 'gmina',
'miejscowosc' => 'miejscowosc',
'ulica' => 'ulica',
'kodPocztowy' => 'kodPocztowy',
],
'fieldsTeryt' => [
'TERYT_SYM' => 'TERYT_SYM',
'TERYT_SYM_UL' => 'TERYT_SYM_UL',
'nrDomu' => 'budynek',
'nrLokalu' => 'lokal',
],
'base' => '1',
],
'BI_audit_ENERGA_PRACOWNICY' => [
'fields' => [
'miejscowosc' => 'miejscowosc',
'kodPocztowy' => 'kodPocztowy',
'ulica' => 'ulica',
],
'fieldsTeryt' => [
'TERYT_SYM' => 'TERYT_SYM',
'TERYT_SYM_UL' => 'TERYT_SYM_UL',
'nrDomu' => 'nr',
'nrLokalu' => 'nrLokalu',
],
'base' => '0',
],
'BI_audit_ENERGA_PRACOWNICY_adresy' => [
'fields' => [
'kodPocztowy' => 'kodPocztowy',
'miejscowosc' => 'miejscowosc',
'ulica' => 'ulica',
],
'fieldsTeryt' => [
'TERYT_SYM' => 'TERYT_SYM',
'TERYT_SYM_UL' => 'TERYT_SYM_UL',
'nrDomu' => 'nrBudynku',
'nrLokalu' => 'nrLokalu',
],
'base' => '0',
],
'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
'fields' => [
'kodPocztowy' => 'Kod_pocztowy',
'miejscowosc' => 'Miejscowosc',
'ulica' => 'Ulica',
],
'fieldsTeryt' => [
'TERYT_SYM' => 'TERYT_SYM',
'TERYT_SYM_UL' => 'TERYT_SYM_UL',
'nrDomu' => 'Numer_budynku',
'nrLokalu' => 'Numer_mieszkania_lokalu',
],
'base' => '0',
],
'BI_audit_KRS' => [
'fields' => [
'wojewodztwo' => 'S_wojewodztwo',
'powiat' => 'S_powiat',
'gmina' => 'S_gmina',
'miejscowosc' => 'A_miejscowosc',
'ulica' => 'A_ulica',
'kodPocztowy' => 'A_kod',
],
'fieldsTeryt' => [
'TERYT_SYM' => 'TERYT_SYM',
'TERYT_SYM_UL' => 'TERYT_SYM_UL',
'nrDomu' => 'A_nrDomu',
'nrLokalu' => 'A_nrLokalu',
],
'base' => '1',
],
'BI_audit_KRS_address' => [
'fields' => [
'wojewodztwo' => 'S_wojewodztwo',
'powiat' => 'S_powiat',
'gmina' => 'S_gmina',
'miejscowosc' => 'A_miejscowosc',
'ulica' => 'A_ulica',
'kodPocztowy' => 'A_kod',
],
'fieldsTeryt' => [
'TERYT_SYM' => 'TERYT_SYM',
'TERYT_SYM_UL' => 'TERYT_SYM_UL',
'nrDomu' => 'A_nrDomu',
'nrLokalu' => 'A_nrLokalu',
],
'base' => '1',
],
'BI_audit_MSIG_address' => [
'fields' => [
'wojewodztwo' => 'S_wojewodztwo',
'powiat' => 'S_powiat',
'gmina' => 'S_gmina',
'miejscowosc' => 'A_miejscowosc',
'ulica' => 'A_ulica',
'kodPocztowy' => 'A_kod',
],
'fieldsTeryt' => [
'TERYT_SYM' => 'TERYT_SYM',
'TERYT_SYM_UL' => 'TERYT_SYM_UL',
'nrDomu' => 'A_nrDomu',
'nrLokalu' => 'A_nrLokalu',
],
'base' => '1',
],
];
foreach ($tables as $table => $tableConf) {
DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrDomu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrDomu']}`) = ''");
DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrLokalu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrLokalu']}`) = ''");
$where = ($full && ($forceAll || (!$tableConf['base']))) ? "" : "where `TERYT_SYM` is null and `cached` = 0";
$query = "select * from `{$table}` {$where}";
$refTable = BiAuditRefTables::getRefTable($table, 'TERYT_adresy', true);
$terytJoinArr = [];
foreach ($tableConf['fieldsTeryt'] as $terytField => $tableField) {
$terytJoinArr[] = (
$terytField == 'nrLokalu'
? "coalesce(`teryt`.`{$terytField}`, '') = coalesce(`table`.`{$tableField}`, '')"
: "`teryt`.`{$terytField}` = `table`.`{$tableField}`"
);
}
$terytJoin = implode(" and ", $terytJoinArr);
$insertFields = "`" . implode("`, `", array_keys($tableConf['fieldsTeryt'])) . "`";
$selectFields = "`" . implode("`, `", $tableConf['fieldsTeryt']) . "`";
$adresy = DB::getPDO()->query($query);
while ($adres = $adresy->fetch()) {
DB::getPDO()->query("delete from `{$refTable}` where `PRIMARY_KEY` = '{$adres['ID']}'");
if (!($forceAll and $adres['TERYT_SYM'])) {
$search = [];
foreach ($tableConf['fields'] as $field => $param) if (!empty($adres[$param])) $search[$field] = $adres[$param];
try {
$teryt = Teryt::search($search);
} catch (Exception $e) {
continue;
}
if (empty($teryt['SYM'])) continue;
$sqlArr = ['TERYT_SYM' => $teryt['SYM']];
$sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
}
if (!trim($adres[$tableConf['fieldsTeryt']['nrDomu']])) continue;
$terytID = DB::getPDO()->fetchValue("select `teryt`.`ID` from `TERYT_adresy` as `teryt` join `{$table}` as `table` on {$terytJoin} where `table`.`ID` = '{$adres['ID']}'");
if (!$terytID) {
if (DB::getPDO()->query("insert into `TERYT_adresy` ({$insertFields}) select {$selectFields} from `{$table}` where `ID` = '{$adres['ID']}'")) {
if (!($terytID = DB::getPDO()->lastInsertId())) {
throw new Exception("Błąd dodania rekordu do TERYT_adresy #1");
}
} else {
throw new Exception("Błąd dodania rekordu do TERYT_adresy #2");
}
}
DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $adres['ID'], 'REMOTE_PRIMARY_KEY' => $terytID]);
}
}
}
private static function reloadCache_updateAll($full, $onlyBase) {
$tablesConf = [
'BI_audit_CEIDG' => [
'fields' => [
'nip' => 'nip',
'regon' => 'regon',
],
'base' => '1',
],
'BI_audit_CEIDG_pelnomocnicy' => [
'fields' => [
'nip' => 'nip',
],
'base' => '1',
],
'BI_audit_CEIDG_powiazania' => [
'fields' => [
'nip' => 'nip',
'regon' => 'regon',
],
'base' => '1',
],
'BI_audit_ENERGA_PRACOWNICY' => [
'fields' => [
'nip' => 'nip',
'regon' => 'regon',
'pesel' => 'pesel',
],
'base' => '0',
//'where' => '',
],
'BI_audit_ENERGA_PRACOWNICY_adresy' => [
'fields' => [],
'base' => '0',
//'where' => '',
],
'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
'fields' => [
'krs' => 'KRS',
'nip' => 'NIP',
'regon' => 'REGON',
'pesel' => 'PESEL',
],
'base' => '0',
'where' => "and ownCompany != 'Y'",
],
'BI_audit_KRS' => [
'fields' => [
'krs' => 'krs',
'nip' => 'nip',
'regon' => 'regon',
],
'base' => '1',
],
'BI_audit_KRS_address' => [
'fields' => [],
'base' => '1',
],
'BI_audit_KRS_company' => [
'fields' => [
'regon' => 'regon',
'krs' => 'krs',
],
'base' => '1',
],
'BI_audit_KRS_person' => [
'fields' => [
'pesel' => 'pesel',
],
'base' => '1',
],
'BI_audit_MSIG' => [
'fields' => [
'krs' => 'krs',
'nip' => 'nip',
'regon' => 'regon',
],
'base' => '1',
],
'BI_audit_MSIG_address' => [
'fields' => [],
'base' => '1',
],
'BI_audit_MSIG_company' => [
'fields' => [
'regon' => 'regon',
'krs' => 'krs',
],
'base' => '1',
],
'BI_audit_MSIG_person' => [
'fields' => [
'pesel' => 'pesel',
],
'base' => '1',
],
// 'BI_audit_KW_requested_person' => [
// 'fields' => [
// 'pesel' => 'Seller_person_pesel',
// 'krs' => 'Seller_person_KRS',
// 'nip' => 'Seller_person_NIP',
// 'regon' => 'Seller_person_REGON',
// ],
// 'base' => '0',
// //'where' => '',
// ],
'TERYT_adresy' => [
'fields' => [],
'base' => '1',
],
];
$refTablesConf = [
'BI_audit_CEIDG' => [
'refTablesTo' => [
'BI_audit_CEIDG_pelnomocnicy',
'BI_audit_CEIDG_powiazania',
'TERYT_adresy',
],
'base' => 1,
],
'BI_audit_CEIDG_pelnomocnicy' => [
'refTablesTo' => [
'TERYT_adresy',
],
'base' => 1,
],
'BI_audit_ENERGA_PRACOWNICY' => [
'refTablesTo' => [
'BI_audit_ENERGA_PRACOWNICY_adresy',
'TERYT_adresy',
],
'base' => 0,
],
'BI_audit_ENERGA_PRACOWNICY_adresy' => [
'refTablesTo' => [
'TERYT_adresy',
],
'base' => 0,
],
'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
'refTablesTo' => [
'TERYT_adresy',
],
'base' => 0,
],
'BI_audit_KRS' => [
'refTablesTo' => [
'BI_audit_KRS_address',
'BI_audit_KRS_company',
'BI_audit_KRS_person',
'TERYT_adresy',
],
'base' => 1,
],
'BI_audit_KRS_address' => [
'refTablesTo' => [
'TERYT_adresy',
],
'base' => 1,
],
'BI_audit_MSIG' => [
'refTablesTo' => [
'BI_audit_MSIG_address',
'BI_audit_MSIG_company',
'BI_audit_MSIG_person',
],
'base' => 1,
],
'BI_audit_MSIG_address' => [
'refTablesTo' => [
'TERYT_adresy',
],
'base' => 1,
],
];
$sourceTables = ['BI_audit_ENERGA_PRACOWNICY'];
if ($full) {
foreach ($tablesConf as $table => $tableConf) if (!$tableConf['base']) $queries[] = "update `{$table}` set `cached` = 0";
$queries[] = "delete from `BI_audit_ALL` where `BASE` = 0";
// $queries[] = "optimize table `BI_audit_ALL`";
$queries[] = "delete from `BI_audit_ALL_ref` where `BASE` = 0";
// $queries[] = "optimize table `BI_audit_ALL_ref`";
$allTables = [];
foreach ($refTablesConf as $refTableFrom => $refTableConf) {
$allTables[] = $refTableFrom;
// if ($refTableConf['base']) continue;
foreach ($refTableConf['refTablesTo'] as $refTableTo) {
$allTables[] = $refTableTo;
if ($refTableConf['base']) continue;
$refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
$queries[] = "update `{$refTable}` set `A_STATUS` = 'WAITNG' where `A_STATUS` = 'NORMAL'";
// $queries[] = "insert into `{$refTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`, `TRANSACTION_ID`, `A_STATUS`) select `all1`.`ID`, `all2`.`ID`, '-1', 'NORMAL' from `BI_audit_ALL` as `all1` join `BI_audit_ALL_ref` as `ref` on `all1`.`ID` = `ref`.`ID1` join `BI_audit_ALL` as `all2` on `ref`.`ID2` = `all2`.`ID` where `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all2`.`REMOTE_TABLE` = '{$refTableTo}'";
}
}
$allTables = array_unique($allTables);
foreach ($allTables as $refTableFrom) {
foreach ($allTables as $refTableTo) {
if ($refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, false)) {
$queries[] = "delete from `{$refTable}` where `TRANSACTION_ID` = '-1'";
$queries[] = "optimize table `{$refTable}`";
$queries[] = "insert into `{$refTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`, `TRANSACTION_ID`, `A_STATUS`) select `all1`.`ID`, `all2`.`ID`, '-1', 'NORMAL' from `BI_audit_ALL` as `all1` join `BI_audit_ALL_ref` as `ref` on `all1`.`ID` = `ref`.`ID1` join `BI_audit_ALL` as `all2` on `ref`.`ID2` = `all2`.`ID` left join `${refTable}` as `ref2` on `all1`.`ID` = `ref2`.`PRIMARY_KEY` and `all2`.`ID` = `ref2`.`REMOTE_PRIMARY_KEY` where `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref2`.`PRIMARY_KEY` is null";
}
}
}
}
foreach ($tablesConf as $table => $tableConf) {
if ($onlyBase && (!$tableConf['base'])) continue;
$where = "where `cached` = 0";
if (!empty($tableConf['where'])) $where .= " {$tableConf['where']}";
// $queries[] = "insert into `BI_audit_ALL` (`REMOTE_TABLE`, `REMOTE_ID`, `BASE`, " . implode(", ", array_keys($tableConf['fields'])) .
// ") select '{$table}', ID, '{$tableConf['base']}', " . implode(", ", $tableConf['fields']) . " from `{$table}` {$where}";
$fields = ["`REMOTE_TABLE`", "`REMOTE_ID`", "`BASE`"];
foreach (array_keys($tableConf['fields']) as $field) $fields[] = "`{$field}`";
$values = ["'{$table}'", "`ID`", "'{$tableConf['base']}'"];
foreach ($tableConf['fields'] as $value) $values[] = "`{$value}`";
$queries[] = "insert into `BI_audit_ALL` (" . implode(", ", $fields) . ") select " . implode(", ", $values) . " from `{$table}` {$where}";
$queries[] = "update `{$table}` set `cached` = 1 {$where}";
}
$queries[] = "update `BI_audit_ALL` set `nip` = null where `nip` = 0";
$queries[] = "update `BI_audit_ALL` set `regon` = null where `regon` = 0";
$queries[] = "update `BI_audit_ALL` set `krs` = null where `krs` = 0";
$queries[] = "update `BI_audit_ALL` set `pesel` = null where `pesel` = 0";
$queries[] = "set @var = (select round(coalesce(max(`ID`), '0.5'), 1) from `BI_audit_ALL_ref_RELATIONS`)";
$queries[] = "insert into `BI_audit_ALL_ref_RELATIONS` (`ID`, `RELATION`, `BASE`) select @var:=@var*2, `a`.`RELATION`, `a`.`BASE` from (select `a`.`REMOTE_TABLE` as `RELATION`, `a`.`BASE` as `BASE` from `BI_audit_ALL` `a` where `a`.`REMOTE_TABLE` not in ('BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person') group by `a`.`REMOTE_TABLE` order by `a`.`BASE` desc) as `a` left join `BI_audit_ALL_ref_RELATIONS` `r` on `a`.`RELATION` = `r`.`RELATION` where `r`.`RELATION` is null";
foreach ($refTablesConf as $refTableFrom => $refTableConf) {
if ($onlyBase && (!$tableConf['base'])) continue;
foreach ($refTableConf['refTablesTo'] as $refTableTo) {
$refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
$queries[] = "insert into `BI_audit_ALL_ref` (`ID1`, `ID2`, `RELATION_ID`, `BASE`) select `all1`.`ID`, `all2`.`ID`, `rel`.`ID`, {$refTableConf['base']} from `BI_audit_ALL` as `all1` join `{$refTable}` as `ref` on `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all1`.`REMOTE_ID` = `ref`.`PRIMARY_KEY` and `ref`.`A_STATUS` = 'WAITING' join `BI_audit_ALL` as `all2` on `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref`.`REMOTE_PRIMARY_KEY` = `all2`.`REMOTE_ID` join `BI_audit_ALL_ref_RELATIONS` `rel` on `all1`.`REMOTE_TABLE` = `rel`.`RELATION`";
if (!in_array($refTableFrom, $sourceTables)) {
$queries[] = "insert into `BI_audit_ALL_ref` (`ID1`, `ID2`, `RELATION_ID`, `BASE`) select `all2`.`ID`, `all1`.`ID`, `rel`.`ID`, {$refTableConf['base']} from `BI_audit_ALL` as `all1` join `{$refTable}` as `ref` on `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all1`.`REMOTE_ID` = `ref`.`PRIMARY_KEY` and `ref`.`A_STATUS` = 'WAITING' join `BI_audit_ALL` as `all2` on `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref`.`REMOTE_PRIMARY_KEY` = `all2`.`REMOTE_ID` join `BI_audit_ALL_ref_RELATIONS` `rel` on `all2`.`REMOTE_TABLE` = `rel`.`RELATION`";
}
if ($backRefTable = BiAuditRefTables::getRefTable($refTableTo, $refTableFrom, false)) {
$queries[] = "insert into `{$backRefTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`, `TRANSACTION_ID`, `A_STATUS`) select `REMOTE_PRIMARY_KEY`, `PRIMARY_KEY`, '-1', 'NORMAL' from `{$refTable}` where `A_STATUS` = 'WAITING'";
}
$queries[] = "update `BI_audit_ALL` as `all1` join `{$refTable}` as `ref` on `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all1`.`REMOTE_ID` = `ref`.`PRIMARY_KEY` and `ref`.`A_STATUS` = 'WAITING' join `BI_audit_ALL` as `all2` on `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref`.`REMOTE_PRIMARY_KEY` = `all2`.`REMOTE_ID` set `ref`.`A_STATUS` = 'NORMAL'";
}
}
foreach ($queries as $query) {
echo "SQL: {$query}\n";
DB::getPDO()->query($query);
}
$BiAuditRelations = new BiAuditRelations();
$result = DB::getPDO()->query("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
while ($row = $result->fetch()) $BiAuditRelations->findRelations($row['ID']);
DB::getPDO()->query("update `BI_audit_ALL` set `reffed` = 1");
}
public function doReloadCache($full = false) {
if ($full === 'base') {
$onlyBase = true;
$full = false;
} else {
$onlyBase = false;
}
$powiazaniaDirLocation = self::getMainDirectory();
$tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
$reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
$reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
if ($full) file_put_contents($reloadCachePidFile, getmypid());
try {
//self::importPracownicy(); //TODO
error_log('now: self::reloadCache_parseUmowy');
self::reloadCache_parseUmowy($full);
error_log('now: self::reloadCache_reTeryt');
self::reloadCache_reTeryt($full);
error_log('now: self::reloadCache_updateAll');
self::reloadCache_updateAll($full, $onlyBase);
if ($full) file_put_contents($reloadCacheResultFile, "ok");
} catch (Exception $e) {
var_dump($e);
if ($full) file_put_contents($reloadCacheResultFile, $e->getMessage());
else throw new Exception($e->getMessage());
}
}
public function doGeneratePowiazania($ID) {
$powiazaniaDirLocation = self::getMainDirectory();
$tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
$resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
$xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
$pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
file_put_contents($pidFile, getmypid());
$tablesConf = [
'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
];
try {
$query = "select count(*) from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` where `FILE_STATUS` = 'IN_PROGRESS' and `BI_analiza_reloadCache` = 'Part' and ID != ${ID}";
$sqlArr = [
'BI_analiza_reloadCache' => 'Part',
'FILE_STATUS_info' => 'Odświeżam częściowo cache',
];
do {
DB::getPDO()->query("lock tables `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` write");
$activeReloadingCache = DB::getPDO()->fetchValue($query);
if (!$activeReloadingCache) DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
DB::getPDO()->query("unlock tables");
if ($activeReloadingCache) {
BiAuditPowiazania::saveToLog("Czekam na zakończenie częściowego odświeżania cache przez inne zadanie");
sleep(30);
}
} while ($activeReloadingCache);
BiAuditPowiazania::saveToLog("Uruchamiam częściowe odświeżenie cache");
$this->doReloadCache();
BiAuditPowiazania::saveToLog("Odświeżono częściowo cache");
$sqlArr = [
'BI_analiza_reloadCache' => 'No',
'FILE_STATUS_info' => 'Zakończono odświeżanie cache i wyzwolono funkcję szukania powiązań',
];
DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
$BiAuditPowiazania = new BiAuditPowiazania($ID, $tasksDirLocation);
if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
//file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
$BiAuditPowiazania->saveXml();
$BiAuditPowiazania->generatePdfAndHtml();
file_put_contents($resultFile, json_encode(['result' => 'ok', 'parts' => $BiAuditPowiazania->getPartsCount()]));
} catch (Exception $e) {
file_put_contents($resultFile, json_encode(['result' => 'error', 'message' => $e->getMessage()]));
}
}
public function reinstallAction() {
$this->reinstall();
die('OK');
}
public function reinstall() {
$sqlList = array();
//$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
$sqlList['ActivateBiAuditGenerate'] = <<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'],
];
private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
public function __construct() {
$query = "select * from BI_audit_ALL_ref_RELATIONS";
$result = DB::getPDO()->fetchAll($query);
foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
}
private function getRelationID($name) {
if (!isset($this->RELATIONS_ID[$name])) {
$query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
$newID = DB::getPDO()->fetchValue($query);
$this->RELATIONS_ID[$name] = $newID;
$query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
DB::getPDO()->query($query);
}
return $this->RELATIONS_ID[$name];
}
private function addToRefTable($fromTable, $toTable, $fromID, $toID) {
if ($refTable = BiAuditRefTables::getRefTable($fromTable, $toTable, false)) {
if (!DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = '{$fromID}' and `REMOTE_PRIMARY_KEY` = '{$toID}' and `A_STATUS` != 'DELETED'")) {
DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $fromID, 'REMOTE_PRIMARY_KEY' => $toID, 'A_STATUS' => 'NORMAL', 'TRANSACTION_ID' => '-1']);
}
}
}
public function findRelations($ID) {
$query = "select * from BI_audit_ALL where ID = '{$ID}'";
if (!($result = DB::getPDO()->fetchAll($query))) return false;
$row = $result[0];
$joins = [];
$items = '';
foreach ($this->relations as $name => $columns) {
$ok = 0;
$join = [];
foreach ($columns as $column) {
$join[] = "t1.{$column} = t2.{$column}";
if ($row[$column] !== null) $ok++;
}
if ($ok / count($columns) > 0.5) {
$joins[] = "(" . implode(" and ", $join) . ")";
$items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
}
}
if (!$joins) return false;
$query = "select t2.ID as ID, t1.REMOTE_TABLE as REMOTE_TABLE_1, 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 t1.ID = {$ID} and (t2.reffed = 1 or t2.ID > {$ID})";
$result = DB::getPDO()->fetchAll($query);
foreach ($result as $row) {
$relationID = 0;
foreach ($this->relations as $name => $v) {
if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
}
$start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
$start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
$end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
$end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
if (!($start2 || $end1)) {
$query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
$this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $ID, $row['ID']);
$this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['ID'], $ID);
DB::getPDO()->query($query);
}
if (!($start1 || $end2)) {
$query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
$this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $ID, $row['ID']);
$this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['ID'], $ID);
DB::getPDO()->query($query);
}
}
}
}
class BiAuditRefTables {
public static function getRefTable($tableFrom, $tableTo, $returnException = false) {
static $refTables = [];
if (!isset($refTables[$tableFrom][$tableTo])) {
try {
$refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
} catch (Exception $e) {
if ($returnException) throw new Exception($e->getMessage());
$refTables[$tableFrom][$tableTo] = false;
}
}
return $refTables[$tableFrom][$tableTo];
}
public static function getRefTables($tableFrom) {
static $refTables = [];
if (!isset($refTables[$tableFrom])) {
$namespace = "default_db/{$tableFrom}/{$tableFrom}";
try {
$item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
$fields = $item['field'];
$_refTables = [];
foreach ($fields as $field) {
list($type, $child) = explode(":", $field['xsdType'], 2);
if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) {
try {
$_refTable = ACL::getRefTable($namespace, $child);
$_refTables[] = $_refTable;
} catch (Exception $e) {
}
}
}
$refTables[$tableFrom] = $_refTables;
} catch (Exception $e) {
$refTables[$tableFrom] = [];
}
}
return $refTables[$tableFrom];
}
}
class BiAuditPowiazania {
private $minDepth;
private $maxDepth, $origMaxDepth;
private $onlyTargets;
private $ID;
private $nodes = [];
private $endNodes;
private $path = [];
private $results = [];
private $items_results = [];
private $relations = [];
private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
private $step = 0;
private $tasksDirLocation;
private $progressFile;
private $progress = [];
private $lastProgress = 0;
private $lastResults = 0;
private $startTimestamp = null;
private $lastTimestamp = null;
private $lowProgressCount = 0;
private $count, $i;
private $splittedResults = [];
private $maxResults = 1000000;
private $fidRow = [];
private static function generateJson($type, $data) {
return json_encode(['ts' => microtime(true), 'type' => $type, 'data' => $data]);
}
public static function saveToLog($message) {
$messageJson = self::generateJson('message', ['message' => $message]);
echo $messageJson . "\n";
}
private static function exec($cmd) {
echo "CMD :: {$cmd}\n";
shell_exec($cmd);
}
private function saveProgress($progress, $message = null) {
$timestamp = microtime(true);
if ($progress !== null && $this->i) {
$elapsed = $timestamp - $this->startTimestamp;
if ($progress) {
//$lastElapsed = $timestamp - $this->lastTimestamp;
//$lastProgress = $progress - $this->lastProgress;
//$estimated = (($elapsed * (1 - $progress)) / $progress + ($lastElapsed * (1 - $lastProgress)) / $lastProgress) / 2;
$estimated = ($elapsed * (1 - $progress)) / $progress;
} else $estimated = "N/A";
$this->lastProgress = $progress;
$this->lastTimestamp = $timestamp;
$progressJson = self::generateJson('progress', ['progress' => $progress, 'item' => $this->i . "/" . $this->count, 'results' => count($this->results), 'step' => $this->step, 'elapsed' => $elapsed, 'estimated' => $estimated]);
echo $progressJson . "\n";
$this->progress[$this->i] = ['progress' => $progress, 'results' => (count($this->results) - $this->lastResults), 'elapsed' => $elapsed, 'estimated' => $estimated];
}
if ($message !== null) $this->progress[0]['message'] = $message;
$this->progress[0]['ts'] = $timestamp;
file_put_contents($this->progressFile, json_encode($this->progress));
}
private static function throwException($message) {
self::saveToLog($message);
throw new Exception($message);
}
public function __construct($ID = 0, $tasksDirLocation = null) {
if (!$ID) self::throwException("Wrong ID parameter");
if (!$tasksDirLocation) self::throwException("Wrong directory of tasks location");
$this->tasksDirLocation = $tasksDirLocation;
$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')";
$result = DB::getPDO()->fetchAll($query);
if (!$result) self::throwException("Błąd danych");
$this->ID = $ID;
if ($this->loadResults()) {
$this->splitResults();
return;
}
self::saveToLog("Wczytuję parametry wyszukiwania powiązań");
$this->minDepth = (int) $result[0]['BI_analiza_minDepth'];
$this->maxDepth = (int) $result[0]['BI_analiza_maxDepth'];
$this->onlyTargets = ($result[0]['BI_analiza_onlyTargets'] != 'N');
if (!$this->minDepth) $this->minDepth = 1;
if (!$this->maxDepth) self::throwException("Błąd danych - nieokreślono maksymalnej głębokości analizy");
if ($this->minDepth > $this->maxDepth) self::throwException("Wartość minimalnej głębokości analizy jest większa od wartości maksymalnej głębokości analizy");
$subQueries = [];
foreach ($this->destTables as $destTable) {
$refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $destTable, true);
$subQueries[] = "select `all`.ID from BI_audit_ALL `all` join `{$refTable}` ref on `all`.REMOTE_TABLE = '{$destTable}' and `all`.REMOTE_ID = ref.REMOTE_PRIMARY_KEY and ref.PRIMARY_KEY = '{$this->ID}'";
}
$query = implode(" union ", $subQueries);
$result = DB::getPDO()->fetchAll($query);
if (!$result) self::throwException("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
$this->endNodes = array_map('reset', $result);
self::saveToLog("Rozpoczynam wyszukiwanie powiązań");
$this->progressFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.progress";
$refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
$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 = '{$this->ID}' order by `all`.`ID` asc";
$result = DB::getPDO()->fetchAll($query);
$this->count = count($result);
$this->progress[0]['count'] = $this->count;
$this->origMaxDepth = $this->maxDepth;
try {
foreach ($result as $i => $row) {
$this->i = $i + 1;
$this->startTimestamp = microtime(true);
$this->lastProgress = 0;
$this->saveProgress(0, "Wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}");
if ($this->maxDepth != $this->origMaxDepth) {
$this->maxDepth = $this->origMaxDepth;
self::saveToLog("Przywrócono oryginalną maksymalną głębokość przeszukiwania ({$this->origMaxDepth})");
}
$this->findPowiazania($row['ID']);
$this->saveProgress(1, "Zakończono wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}");
$this->lastResults = count($this->results);
}
} catch (Exception $e) {
if ($this->i < $this->count) {
$this->startTimestamp = microtime(true);
$this->lastProgress = 0;
$this->lastResults = count($this->results);
while (++$this->i <= $this->count) $this->saveProgress(0);
}
if ($message = $e->getMessage()) self::saveToLog("Wystąpił błąd podczas wyszukiwania powiązań - {$message}");
}
$this->nodes = [];
self::saveToLog("Zakończono wyszukiwanie powiązań");
$this->saveResults();
//$this->saveToDb(); 2017-12-14 - przerobiono na zapisywanie danych do bazy w locie
$this->splitResults();
}
private function addResult($progress) {
if (count($this->results) == $this->maxResults) {
$message = "Przerwano wyszukiwanie powiązań - osiągnięto maksymalną liczbę wyników {$this->maxResults}";
self::saveToLog($message);
$this->saveProgress($progress, $message);
throw new Exception('');
}
$this->results[] = $this->path;
$this->saveToDb($this->path);
}
public function findPowiazania($ID, $progress = 0, $steps = 1, $relation = "", $end = 0) {
if (((++$this->step) % 1000000) == 0) {
$progressDiff = $progress - $this->lastProgress;
if ($progressDiff < 0.00005) {
$this->lowProgressCount++;
if ($this->lowProgressCount == 10) {
$this->maxDepth--;
self::saveToLog("Zbyt dużo rekurencji, zmniejszono maksymalną głębokość poszukiwań do {$this->maxDepth} dla bieżącego pracownika");
}
} else $this->lowProgressCount = 0;
$this->saveProgress($progress);
}
if ((($this->step) % 10000) == 0) {
if (memory_get_usage(true) > 3000000000) {
$this->nodes = [];
self::saveToLog("Oczyszczam podręczny cache - zajmuje zbyt dużo pamięci");
}
}
if (isset($this->path[$ID])) return false;
$this->path[$ID] = $relation;
if (!$relation) $relation = 0;
if ($end) {
if (in_array($ID, $this->endNodes) && count($this->path) > $this->minDepth) $this->addResult($progress);
array_pop($this->path);
return;
}
if (count($this->path) > $this->maxDepth) {
if (!$this->onlyTargets) $this->addResult($progress);
array_pop($this->path);
return;
}
if (!isset($this->nodes[$ID][$relation])) {
$where = $relation ? "and ({$relation} & ref.RELATION_ID) != {$relation}" : "";
$query = "select ref.ID2, RELATION_ID, END from BI_audit_ALL_ref ref where ref.ID1 = {$ID} {$where}";
$this->nodes[$ID][$relation] = DB::getPDO()->fetchAll($query);
}
$nodes = array_values(array_filter($this->nodes[$ID][$relation], function ($node) {
if (isset($this->path[$node['ID2']])) return false;
return true;
}));
$count = count($nodes);
foreach ($nodes as $i => $node) $this->findPowiazania($node['ID2'], ($progress + ($i / ($count * $steps))), ($count * $steps), $node['RELATION_ID'], $node['END']);
array_pop($this->path);
}
private function saveResults() {
self::saveToLog("Zapisuję wyliczone dane do pliku");
if (!$this->results) {
self::saveToLog("Brak wyliczonych danych - niczego nie zapisaono");
return false;
}
$dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
$data = base64_encode(gzcompress(json_encode(['results' => $this->results, 'fidRow' => $this->fidRow])));
file_put_contents($dataFile, $data);
self::saveToLog("Zapisano wyliczone dane do pliku");
return true;
}
private function loadResults() {
self::saveToLog("Próbuję wczytać wcześniej wyliczone dane");
$dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
if (!file_exists($dataFile)) {
self::saveToLog("Nie znaleziono pliku z wyliczonymi danymi");
return false;
}
$data = file_get_contents($dataFile);
$results = @json_decode(gzuncompress(base64_decode($data)), true);
if (!$results) {
self::saveToLog("Wystąpił błąd wczytywania wcześniej wyliczonych danych");
return false;
}
if (isset($results['results'])) {
$this->results = $results['results'];
if (isset($results['fidRow'])) $this->fidRow = $results['fidRow'];
} else $this->results = $results;
self::saveToLog("Wczytano wcześniej wyliczone dane");
return true;
}
private function relationName($ID) {
if (!$ID) return '';
if (!isset($this->relations[$ID])) {
$query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
$result = DB::getPDO()->fetchAll($query);
$rels = array_map('reset', $result);
$this->relations[$ID] = implode(", ", $rels);
}
return $this->relations[$ID];
}
private function splitResults() {
$MAX = 1000;
$countBySource = [];
$resultsKeys = [];
foreach ($this->results as $resultKey => $result) {
$_keys = array_keys($result);
$countBySource[reset($_keys)][] = $resultKey;
}
foreach ($countBySource as $resultKeys) {
if (count($resultKeys) > $MAX) {
$countByDest = [];
foreach ($resultKeys as $resultKey) {
$_keys = array_keys($this->results[$resultKey]);
$countByDest[end($_keys)][] = $resultKey;
}
foreach ($countByDest as $resultKeys2) {
while (count($resultKeys2) > $MAX) $resultsKeys[] = array_splice($resultKeys2, 0, $MAX);
$resultsKeys[] = $resultKeys2;
}
} else $resultsKeys[] = $resultKeys;
}
$results = [];
while ($resultsKeys) {
$resultKeys = array_shift($resultsKeys);
while ($next = current($resultsKeys)) {
if (count($resultKeys) + count($next) <= $MAX) {
$resultKeys = array_merge($resultKeys, $next);
unset($resultsKeys[key($resultsKeys)]);
} else next($resultsKeys);
}
$results[] = array_map(function ($resultKey) {return $this->results[$resultKey];}, $resultKeys);
}
$this->splittedResults = $results;
}
public function getPartsCount() {
return count($this->splittedResults);
}
private function generateItemsResults($resultsPart = null) {
self::saveToLog("Generuję dane na potrzeby utworzenia pliku XML ({$resultsPart})");
$xmlTask = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
$xmlRow = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
$xmlObject = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object";
$this->items_results = [];
$items_kontrahenci = [];
$items_kw_person = [];
$kontrahenci = [];
$kw_person = [];
$_items_results = [];
$refUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
$refKwRequestedToKwRequestedPerson = BiAuditRefTables::getRefTable('BI_audit_KW_requested', 'BI_audit_KW_requested_person', true);
$this->items_results[$resultsPart]['@attributes'] = ['xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd'];
$this->items_results[$resultsPart][$xmlTask]['@attributes'] = ['fid' => "{$xmlTask}.{$this->ID}"];
if ($resultsPart === null) $results = $this->results;
else {
$results = (!empty($this->splittedResults[$resultsPart])) ? $this->splittedResults[$resultsPart] : [];
$this->items_results[$resultsPart][$xmlTask]['@attributes']['system_cache__dita:part'] = ($resultsPart + 1);
}
foreach ($results as $key => $result) {
if ($this->fidRow) $item_results = ['@attributes' => ['fid' => "{$xmlRow}.{$this->fidRow[$key]['fid']}"]];
foreach ($result as $ID => $rel) {
$query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
$row = DB::getPDO()->fetchFirst($query);
$query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
$obj = DB::fetch(DB::query($query));
$item_result = [];
if ($this->fidRow) $item_result['@attributes'] = ['fid' => "{$xmlObject}.{$this->fidRow[$key]['obj'][$ID]}"];
$item_result[$row['REMOTE_TABLE']] = array_merge(['@attributes' => ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"]], (array) $obj);
if ($refTable = BiAuditRefTables::getRefTable('BI_audit_operational_raport_note', $row['REMOTE_TABLE'], false)) {
$query = "select `note`.* from `BI_audit_operational_raport_note` `note` join `{$refTable}` `ref` on `note`.`ID` = `ref`.`PRIMARY_KEY` where `ref`.`REMOTE_PRIMARY_KEY` = '{$row['REMOTE_ID']}'";
if ($notes = DB::getPDO()->fetchAll($query)) $item_result[$row['REMOTE_TABLE']]['BI_audit_operational_raport_note'] = $notes;
}
if ($refTable = BiAuditRefTables::getRefTable($row['REMOTE_TABLE'], 'BI_audit_taxpayer', false)) {
$query = "select `taxpayer`.* from `{$refTable}` `ref` join `BI_audit_taxpayer` `taxpayer` on `ref`.`REMOTE_PRIMARY_KEY` = `taxpayer`.`ID` where `ref`.`PRIMARY_KEY` = '{$row['REMOTE_ID']}'";
if ($taxpayer = DB::getPDO()->fetchFirst($query)) {
$item_result[$row['REMOTE_TABLE']]['BI_audit_taxpayer'] = array_merge(['@attributes' => ['fid' => "BI_audit_taxpayer.{$taxpayer['ID']}"]], $taxpayer);
}
}
if ($rel) $item_result['relation_from'] = $this->relationName($rel);
$item_results[$xmlObject][] = $item_result;
if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
$kontrahenci[] = $row['REMOTE_ID'];
$query = "select umowy.* from BI_audit_ENERGA_RUM_UMOWY umowy join `{$refUmowyToKontrahenci}` ref on umowy.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
$res = DB::query($query);
if (mysql_num_rows($res)) {
$umowy = [];
while ($obj = DB::fetch($res)) {
$umowa = (array) $obj;
$umowa = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_RUM_UMOWY.{$umowa['ID']}"]], $umowa);
$umowy[] = $umowa;
}
$item_kontrahenci['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
$item_kontrahenci['ID'] = $row['REMOTE_ID'];
$item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
$items_kontrahenci[] = $item_kontrahenci;
}
} elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
$kw_person[] = $row['REMOTE_ID'];
$query = "select kw.* from BI_audit_KW_requested kw join `{$refKwRequestedToKwRequestedPerson}` ref on kw.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
$res = DB::query($query);
if (mysql_num_rows($res)) {
$kws = [];
while ($obj = DB::fetch($res)) {
$kw = (array) $obj;
$kw = array_merge(['@attributes' => ['fid' => "BI_audit_KW_requested.{$kw['ID']}"]], $kw);
$kws[] = $kw;
}
$item_kw_person['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
$item_kw_person['ID'] = $row['REMOTE_ID'];
$item_kw_person['BI_audit_KW_requested'] = $kws;
$items_kw_person[] = $item_kw_person;
}
}
}
$this->items_results[$resultsPart][$xmlTask][$xmlRow][] = $item_results;
}
$this->items_results[$resultsPart][$xmlTask]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
$this->items_results[$resultsPart][$xmlTask]['BI_audit_KW_requested_person'] = $items_kw_person;
self::saveToLog("Wygenerowano dane na potrzeby utworzenia pliku XML ({$resultsPart})");
}
private function saveToDb($result = null, $key = null) {
if ($result === null) {
self::saveToLog("Zapisuję wyliczone dane do bazy");
if (!$this->results) {
self::saveToLog("Brak wyliczonych danych - nie zapisaono niczego do bazy");
return null;
}
foreach ($this->results as $key => $result) $this->saveToDb($result, $key);
self::saveToLog("Zapisano wyliczone dane do bazy");
} else {
if ($key === null) {
end($this->results);
$key = key($this->results);
}
$refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
$refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
$IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
$fidObj = [];
DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
foreach ($result as $ID => $rel) {
$query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
$object = DB::getPDO()->fetchFirst($query);
$idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relationName($rel)]);
DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
$ref = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', $object['REMOTE_TABLE'], true);
DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
$fidObj[$ID] = $idPowiazaniaRowObject;
}
$this->fidRow[$key] = [
'fid' => $IdPowiazaniaRow,
'obj' => $fidObj,
];
}
}
public function saveXml() {
if ($this->getPartsCount()) {
self::saveToLog("Generuję pliki XML (liczba plików do wygenerowania: {$this->getPartsCount()})");
for ($i =0; $i < $this->getPartsCount(); $i++) {
$partNo = str_pad($i + 1, 6, '0', STR_PAD_LEFT);
$xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
file_put_contents($xmlFile, $this->asXml($i));
}
self::saveToLog("Zakończono generowanie plików XML");
} else {
$xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
file_put_contents($xmlFile, $this->asXml());
}
}
public function asXml($resultsPart = null) {
self::saveToLog("Generuję plik XML ({$resultsPart})");
if (!$this->results) {
self::saveToLog("Brak wyników (#1), nie wygenerowano pliku XML ({$resultsPart})");
return null;
}
if (!isset($this->items_results[$resultsPart])) $this->generateItemsResults($resultsPart);
if (!isset($this->items_results[$resultsPart])) {
self::saveToLog("Brak wyników (#2), nie wygenerowano pliku XML ({$resultsPart})");
return null;
}
$xmlRoot = "RelatedFeatureRoot";
$return = V::arrayToXML($this->items_results[$resultsPart], true, $xmlRoot);
self::saveToLog("Wygenerowano plik XML ({$resultsPart})");
return $return;
}
public function asArray($resultsPart = null, $subArray = null) {
if (!$this->results) return null;
if (!$this->items_results[$resultsPart]) $this->generateItemsResults($resultsPart);
if (!$this->items_results[$resultsPart]) return null;
if ($subArray) {
if (isset($this->items_results[$resultsPart][$subArray])) return $this->items_results[$subArray];
else return [];
} else return $this->items_results[$resultsPart];
}
public function powiazaniaFound() {
if ($this->results) return true;
else return false;
}
public function generatePdfAndHtml() {
if ($this->getPartsCount()) {
self::saveToLog("Generuję raporty w plikach PDF oraz HTML (liczba raportów do wygenerowania: {$this->getPartsCount()})");
for ($i =0; $i < $this->getPartsCount(); $i++) $this->_generatePdfAndHtml($i);
self::saveToLog("Zakończono generowanie raportów w plikach PDF oraz HTML");
} else $this->_generatePdfAndHtml();
}
private function _generatePdfAndHtml($resultsPart = null) {
$id_part = $resultsPart === null ? $this->ID : $this->ID . "_" . str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
self::saveToLog("Generuję raport w pliku PDF oraz HTML ({$resultsPart})");
$xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.xml";
$pdfDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.pdf";
$htmlDestDir = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.html";
$htmlZipDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.zip";
$antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
if (!is_dir($antDir)) mkdir($antDir, 0777, true);
$antXmlFilename = "relations-{$id_part}.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-{$id_part}/pdf/relations-{$id_part}.pdf";
$htmlDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}/html";
if (!file_exists($antDir)) mkdir($antDir, 0770, true);
if (!is_dir($antDir)) {
$sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików PDF i HTML";
self::saveToLog("Nie wygenerowano plików PDF oraz HTML - problem z utworzeniem katalogu dla ant ({$resultsPart})");
} else {
copy($xmlFile, $antXmlFile);
self::exec("cd /Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree && ant -f build_CRM_PROCES_tree.xml default_db:PROCES_INIT:tree:dita -Duuid=relations-{$id_part}");
self::saveToLog("Generuję plik PDF ({$resultsPart})");
self::exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o pdf -i relations-{$id_part}.ditamap -f pdf");
if (file_exists($pdfFile)) {
rename($pdfFile, $pdfDestFile);
self::saveToLog("Wygenerowano plik PDF ({$resultsPart})");
} else self::saveToLog("Nie udało się wygenerować pliku PDF ({$resultsPart})");
self::saveToLog("Generuję pliki HTML ({$resultsPart})");
self::exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o html -i relations-{$id_part}.ditamap -f tocjs");
if (file_exists($htmlDir) && is_dir($htmlDir)) {
self::exec("cd \"/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}\" && zip -r \"{$htmlZipDestFile}\" html");
if (file_exists($htmlDestDir)) self::exec("rm -rf \"{$htmlDestDir}\"");
self::exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
self::saveToLog("Wygenerowano pliki HTML ({$resultsPart})");
} else self::saveToLog("Nie udało się wygenerować plików HTML {$resultsPart})");
}
}
}