Jelajahi Sumber

Postępy w BiAuditGenerate

Mariusz Muszyński 8 tahun lalu
induk
melakukan
9d11747442
1 mengubah file dengan 188 tambahan dan 84 penghapusan
  1. 188 84
      SE/se-lib/Route/UrlAction/BiAuditGenerate.php

+ 188 - 84
SE/se-lib/Route/UrlAction/BiAuditGenerate.php

@@ -4,6 +4,8 @@ Lib::loadClass('RouteBase');
 Lib::loadClass('FoldersConfig');
 Lib::loadClass('FileUploader');
 Lib::loadClass('ProcesHelper');
+Lib::loadClass('SchemaFactory');
+Lib::loadClass('Core_AclHelper');
 
 class Route_UrlAction_BiAuditGenerate extends RouteBase {
 
@@ -59,7 +61,10 @@ class Route_UrlAction_BiAuditGenerate extends RouteBase {
           <tbody>
 	
 <?php
-		$pracownicy = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_PRACOWNICY");
+		$acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
+		$queryFeatures = $acl->buildQuery(['limit' => 0]);
+		$pracownicy = $queryFeatures->getItems();
+//echo "<pre>"; print_r($pracownicy); echo "</pre>";
 		foreach ($pracownicy as $pracownik) {
 ?>
             <tr>
@@ -117,10 +122,28 @@ function toggle(source) {
 		$sqlArr = [
 			'ID' => $this->powiazanie['ID'],
 			'FILE_STATUS' => 'TO_GENERATE',
-			'BI_analiza_employees' => implode(',', $prID),
+			'BI_analiza_employees' => implode(',', $prID),	// TODO do wyjebania
 		];
 		if ($reloadCache == 'on') $sqlArr['BI_analiza_reloadCache'] = 'Y';
 
+		$refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+			'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
+		foreach ($prID as $v) DB::getPDO()->insert($refPowiazaniaToPracownicy, ['PRIMARY_KEY' => $this->powiazanie['ID'], 'REMOTE_PRIMARY_KEY' => $v]);
+
+		$acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
+		$queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
+		$kontrahenci = $queryFeatures->getItems();
+		$refPowiazaniaToKontrahenci = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+			'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI');
+		foreach ($kontrahenci as $kontrahent) DB::getPDO()->insert($refPowiazaniaToKontrahenci, ['PRIMARY_KEY' => $this->powiazanie['ID'], 'REMOTE_PRIMARY_KEY' => $kontrahent['ID']]);
+
+		$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();
+		$refPowiazaniaToKwRequestedPreson = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+			'default_db__x3A__BI_audit_KW_requested_person:BI_audit_KW_requested_person');
+		foreach ($requestedPersons as $requestedPerson) DB::getPDO()->insert($refPowiazaniaToKwRequestedPreson, ['PRIMARY_KEY' => $this->powiazanie['ID'], 'REMOTE_PRIMARY_KEY' => $requestedPerson['ID']]);
+
 		$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)';
@@ -198,7 +221,25 @@ function toggle(source) {
 
 	public function doGenerate() {
 
+		function getRefsTables($namespace) {
+			try {
+				$item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
+				if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
+				$fields = $item['field'];
+				$refsTables = [];
+				foreach ($fields as $field) {
+					list($type, $child) = explode(":", $field['xsdType'], 2);
+					if ($type == "ref" && $field['isActive'] && (!$field['isLocal'])) $refsTables[] = ACL::getRefTable($ns, $child);
+				}
+				return $refsTables;
+			} catch (Exception $e) {
+				echo "{$ns} - {$e->getMessage}";
+				return [];
+			}
+		}
+
 		function deleteResultsFromDB($ID) {
+//DUPA
 			$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);
 		}
@@ -237,6 +278,7 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 			$powiazaniaDirLocation = $this->getMainDirectory();
 			$tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
 			$reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
+			$reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
 			$reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
 			$reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
 
@@ -246,9 +288,11 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 
 
 			### 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 = 'Y' and FILE_STATUS = 'TO_GENERATE'";
 			$result = DB::getPDO()->fetchAll($query);
 			if ($result) {
+				$doGenerate = false;
 				$sqlArr = [];
 
 				if (file_exists($reloadCachePhpFile)) {
@@ -259,6 +303,7 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 								'FILE_STATUS_info' => 'Odświeżono cache, oczekiwanie na wygenerowanie powiązań',
 								'BI_analiza_reloadCache' => 'N',
 							];
+							$doGenerate = true;
 						} else {
 							$sqlArr = [
 								'FILE_STATUS' => 'ERROR',
@@ -268,12 +313,30 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 							$result = DB::getPDO()->fetchAll($query);
 						}
 						unlink($reloadCachePhpFile);
+						unlink($reloadCachePidFile);
 						unlink($reloadCacheResultFile);
+					} elseif (file_exists($reloadCachePidFile)) {
+						$pid = file_get_contents($reloadCachePidFile);
+						$processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
+						$processShouldBeRunning = "php {$reloadCachePhpFile}";
+						if ($processRunning != $processShouldBeRunning) {
+							if (!file_exists($reloadCacheResultFile)) {
+								$sqlArr = [
+									'FILE_STATUS' => 'ERROR',
+									'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas odświeżania cache - nie znaleziono procesu potomnego",
+								];
+								$query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
+								$result = DB::getPDO()->fetchAll($query);
+								unlink($reloadCachePhpFile);
+								unlink($reloadCachePidFile);
+								unlink($reloadCacheResultFile);
+							}
+						}
 					}
 				} else {
 					$query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
-					$result = DB::getPDO()->fetchValue($query);
-					if ($result) {
+					$result2 = DB::getPDO()->fetchValue($query);
+					if ($result2) {
 						$sqlArr = [
 							'FILE_STATUS_info' => 'Wstrzymano odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
 						];
@@ -291,27 +354,29 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 						DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
 					}
 				}
-				exit;
+
 			}
 
 
 			### 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']);
+			if ($doGenerate) {
+				$query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE' and ID = 1"; //TODO usunac 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);
+					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 &"');
+					$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 &"');
+				}
 			}
 
 
@@ -321,49 +386,54 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 			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)) {
-					$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)) {
-									$powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
-									if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0777, false);
-									if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
-								} else $error = "Wystąpił nieznany błąd w przetwarzaniu";
+								$powiazanieDirLocation = $this->getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
+								if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0777, false);
+								if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
+								else $success = true;
 							} else $error = "Wystąpił 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',
-						];
-						$destXmlFile = "{$powiazanieDirLocation}/relations.xml";
-						rename($xmlFile, $destXmlFile);
+				} 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,
+					];
+					deleteResultsFromDB($row['ID']);
+					if (file_exists($xmlFile)) unlink($xmlFile);
+				} elseif ($success) {
+					$sqlArr = [
+						'FILE_STATUS' => 'GENERATED',
+						'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
+					];
+					$destXmlFile = "{$powiazanieDirLocation}/relations.xml";
+					rename($xmlFile, $destXmlFile);
+				}
+
+				if ($sqlArr) {
 					$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);
-					
+					if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
+					if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
+					if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
 				}
 			}
 
@@ -412,7 +482,7 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 			}
 		}
 
-//		reTeryt('BI_audit_ENERGA_RUM_KONTRAHENCI');
+		reTeryt('BI_audit_ENERGA_RUM_KONTRAHENCI');
 		reTeryt('BI_audit_ENERGA_PRACOWNICY_adresy');
 	}
 
@@ -468,8 +538,8 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 		$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";
+		$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 `CRM__#REF_TABLE__27` as ref on all1.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and all1.REMOTE_ID = ref.PRIMARY_KEY join BI_audit_ALL as all2 on all2.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY_adresy' and ref.REMOTE_PRIMARY_KEY = all2.REMOTE_ID join BI_audit_ALL_ref_RELATIONS rel on all1.REMOTE_TABLE = rel.RELATION";
+
 		foreach ($queries as $query) DB::getPDO()->query($query);
 		$BiAuditRelations = new BiAuditRelations();
 		$query = "select ID from BI_audit_ALL where BASE = 0";
@@ -480,9 +550,11 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 	public function doReloadCache() {
 		$powiazaniaDirLocation = $this->getMainDirectory();
 		$tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
+		$reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
 		$reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
+		file_put_contents($reloadCachePidFile, getmypid());
 		try {
-			$this->reloadCache_reTeryt();
+//			$this->reloadCache_reTeryt();	// TODO remove comment
 			$this->reloadCache_updateAll();
 			file_put_contents($reloadCacheResultFile, "ok");
 		} catch (Exception $e) {
@@ -496,7 +568,6 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 		$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 = [
@@ -513,22 +584,11 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 		];
 
 		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']);
-
+			$BiAuditPowiazania = new BiAuditPowiazania($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');
+			file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
+			$BiAuditPowiazania->saveToDb();
+/*			$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) {
@@ -548,12 +608,11 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 					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());
@@ -598,6 +657,7 @@ class BiAuditRelations {
 	];
 
 	private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
+	private $sourceTable = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
 
 	public function __construct() {
 		$query = "select * from BI_audit_ALL_ref_RELATIONS";
@@ -646,13 +706,15 @@ class BiAuditRelations {
 			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 (!$end1) {
+			if (!($start2 || $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) {
+			if (!($start1 || $end2)) {
 				$query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1})";
 				DB::getPDO()->query($query);
 			}
@@ -664,13 +726,40 @@ class BiAuditRelations {
 class BiAuditPowiazania {
 
 	private $DEPTH;
+	private $ID;
+	private $endNodes;
 	private $path = [];
 	private $results = [];
 	private $items_results = [];
 	private $relations = [];
+	private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
 
-	public function __construct($depth = 0) {
-		$this->DEPTH = (int) $depth;
+	public function __construct($ID = 0) {
+		if (!$ID) throw new Exception("Wrong ID parameter");
+		$query = "select BI_analiza_depth, BI_analiza_employees 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];
+		$this->DEPTH = (int) $powiazanie['BI_analiza_depth'];
+		$this->ID = $ID;
+
+		// TODO przerobic na refy
+		$subQueries = [];
+		foreach ($this->destTables as $destTable) {
+			$refTable = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "default_db__x3A__{$destTable}:{$destTable}");
+			$subQueries[] = "select `all`.ID from BI_audit_ALL `all` join `{$refTable}` ref on `all`.REMOTE_TABLE = '{$destTable}' and `all`.REMOTE_ID = ref.REMOTE_PRIMARY_KEY and ref.PRIMARY_KEY = '{$ID}'";
+		}
+		$query = implode(" union ", $subQueries);
+		$result = DB::getPDO()->fetchAll($query);
+		if (!$result) throw new Exception("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
+		$this->endNodes = array_map('reset', $result);
+
+		$refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+			'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
+		$query = "select `all`.ID as ID from BI_audit_ALL `all` join `{$refPowiazaniaToPracownicy}` ref 
+			on `all`.REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY' and `all`.REMOTE_ID = ref.REMOTE_PRIMARY_KEY and ref.PRIMARY_KEY = '{$ID}'";
+		$result = DB::getPDO()->fetchAll($query);
+		foreach ($result as $row) $this->findPowiazania($row['ID']);
 	}
 
 	public function findPowiazania($ID, $relation = "", $end = 0) {
@@ -680,7 +769,7 @@ class BiAuditPowiazania {
 		if (!$relation) $relation = 0;
 
 		if ($end) {
-			$this->results[] = $this->path;
+			if (in_array($ID, $this->endNodes)) $this->results[] = $this->path;
 			array_pop($this->path);
 			return true;
 		}
@@ -720,12 +809,6 @@ class BiAuditPowiazania {
 		$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) {
@@ -766,6 +849,27 @@ class BiAuditPowiazania {
 		$this->items_results[$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;
 	}
 
+	public function saveToDb() {
+		if (!$this->results) return null;
+		$refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
+			'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
+		$refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
+			'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
+		foreach ($this->results as $result) {
+			$IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
+			DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
+			foreach ($result as $ID => $rel) {
+				$query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
+				$object = DB::getPDO()->fetchFirst($query);
+				$idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $rel]);
+				DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
+				$ref = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
+					"default_db__x3A__{$object['REMOTE_TABLE']}:{$object['REMOTE_TABLE']}");
+				DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
+			}
+		}
+	}
+
 	public function asXml() {
 		if (!$this->results) return null;
 		if (!$this->items_results) $this->generateItemsResults();