Преглед изворни кода

Duża aktualizacja BiAuditGenerate - utworzenie obiektów adresowych, refy all2all etc.

Mariusz Muszyński пре 8 година
родитељ
комит
71d4840a62
1 измењених фајлова са 253 додато и 183 уклоњено
  1. 253 183
      SE/se-lib/Route/UrlAction/BiAuditGenerate.php

+ 253 - 183
SE/se-lib/Route/UrlAction/BiAuditGenerate.php

@@ -26,7 +26,6 @@ class Route_UrlAction_BiAuditGenerate extends RouteBase {
 	private $powiazanie = null;
 	private $SOURCE = null;
 	private $REFERER;
-	private $refTables;
 
 	public function handleAuth() {
 		if (!User::logged()) {
@@ -34,10 +33,6 @@ class Route_UrlAction_BiAuditGenerate extends RouteBase {
 		}
 	}
 
-	public function __construct() {
-		$this->refTables = new BiAuditRefTables();
-	}
-
 	private static function getDirectory($table, $id) {
 		$folderConf = FoldersConfig::getAll($table.'_COLUMN');
 		$record = new stdClass;
@@ -235,16 +230,13 @@ function toggle(source) {
 
 		self::truncatePowiazaniaFromDB($powiazanieID);
 
-		$refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
-			'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
+		$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 = 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');
+		$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 = 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');
+		$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);
@@ -372,8 +364,7 @@ function toggle(source) {
         <tbody>
 
 <?php
-		$refPowiazaniaToPracownicy = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
-			'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY');
+		$refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
 		$query = "select `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.*
 from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
 join `{$refPowiazaniaToPracownicy}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPracownicy}`.`PRIMARY_KEY`
@@ -758,7 +749,7 @@ function validate() {
 			$query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI kh join BI_audit_KRS krs on (kh.NIP = krs.nip or kh.REGON = krs.regon or kh.KRS = krs.krs) where krs.ID = '{$krsId}'";
 			$kontrahentExists = DB::getPDO()->fetchValue($query);
 
-			$refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
+			$refKrsToKrsPerson = BiAuditRefTables::getRefTable('BI_audit_KRS', 'BI_audit_KRS_person', true);
 			$query = "select person.*, pracownicy.ID as pracownicyId from `{$refKrsToKrsPerson}` ref join `BI_audit_KRS_person` person on ref.REMOTE_PRIMARY_KEY = person.ID left join BI_audit_ENERGA_PRACOWNICY pracownicy on person.pesel = pracownicy.pesel where ref.PRIMARY_KEY = '{$krsId}'";
 			$result = DB::getPDO()->fetchAll($query);
 			if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono osób powiązanych z podmiotem</td></tr>';
@@ -881,7 +872,7 @@ function validateCompany(source) {
         </thead>
         <tbody>
 <?php
-		$refKrsToKrsPerson = ACL::getRefTable('default_db/BI_audit_KRS/BI_audit_KRS', "default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person");
+		$refKrsToKrsPerson = BiAuditRefTables::getRefTable('BI_audit_KRS', 'BI_audit_KRS_person', true);
 		$query = "select krs.* from `{$refKrsToKrsPerson}` ref join BI_audit_KRS krs on ref.PRIMARY_KEY = krs.ID where ref.REMOTE_PRIMARY_KEY = '{$this->SOURCE['ID']}'";
 		$result = DB::getPDO()->fetchAll($query);
 
@@ -952,44 +943,23 @@ function validateCompany(source) {
 		SE_Layout::dol();
 	}
 
-	private static function getRefsTables($namespace) {
-		try {
-			$item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
-			if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
-			$fields = $item['field'];
-
-			$refsTables = [];
-			foreach ($fields as $field) {
-				list($type, $child) = explode(":", $field['xsdType'], 2);
-				if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) $refsTables[] = ACL::getRefTable($namespace, $child);
-			}
-			return $refsTables;
-		} catch (Exception $e) {
-//			echo "{$namespace} - {$e->getMessage}";
-			return [];
-		}
-	}
-
 	private static function truncatePowiazaniaFromDB($ID) {
-		$refsTables = self::getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
-		if (!$refsTables) return null;
-		$refPowiazaniaToPowiazaniaRow = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
-			'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
-		$refsTables = array_diff($refsTables, [$refPowiazaniaToPowiazaniaRow]);
+		$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("`, `", $refsTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
-		foreach ($refsTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
+		$query = "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 = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
-			'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
-		$refPowiazaniaRowToPowiazaniaRowObject = ACL::getRefTable('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
-			'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
-		$refsTables = self::getRefsTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
+		$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}`,
@@ -1005,7 +975,7 @@ join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazania
 		$sqlWhere = "
 where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
 
-		foreach ($refsTables as $refTable) {
+		foreach ($refTables as $refTable) {
 			$sqlDeleteFrom .= ",\n`{$refTable}`";
 			$sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
 		}
@@ -1025,6 +995,7 @@ define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
 define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
 
 ini_set("display_startup_errors", "0");
+ini_set("display_errors", "1");
 ini_set("log_errors", "1");
 ini_set("error_log", "/var/log/apache2/error_log");
 
@@ -1354,7 +1325,7 @@ Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
 			],
 		];
 
-		$refTable = 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');
+		$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'");
@@ -1479,7 +1450,7 @@ SQL;
 		}
 	}
 
-	private static function reloadCache_reTeryt($full = false) {
+	public static function reloadCache_reTeryt($full = false, $forceAll = false) {
 
 		Lib::loadClass('Teryt');
 
@@ -1493,7 +1464,13 @@ SQL;
 					'ulica' => 'ulica',
 					'kodPocztowy' => 'kodPocztowy',
 				],
-				'full' => false,
+				'fieldsTeryt' => [
+					'TERYT_SYM' => 'TERYT_SYM',
+					'TERYT_SYM_UL' => 'TERYT_SYM_UL',
+					'nrDomu' => 'budynek',
+					'nrLokalu' => 'lokal',
+				],
+				'base' => '1',
 			],
 			'BI_audit_CEIDG_pelnomocnicy' => [
 				'fields' => [
@@ -1504,7 +1481,13 @@ SQL;
 					'ulica' => 'ulica',
 					'kodPocztowy' => 'kodPocztowy',
 				],
-				'full' => false,
+				'fieldsTeryt' => [
+					'TERYT_SYM' => 'TERYT_SYM',
+					'TERYT_SYM_UL' => 'TERYT_SYM_UL',
+					'nrDomu' => 'budynek',
+					'nrLokalu' => 'lokal',
+				],
+				'base' => '1',
 			],
 			'BI_audit_ENERGA_PRACOWNICY' => [
 				'fields' => [
@@ -1512,15 +1495,27 @@ SQL;
 					'kodPocztowy' => 'kodPocztowy',
 					'ulica' => 'ulica',
 				],
-				'full' => true,
+				'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',
-				],      
-				'full' => true,
+				],
+				'fieldsTeryt' => [
+					'TERYT_SYM' => 'TERYT_SYM',
+					'TERYT_SYM_UL' => 'TERYT_SYM_UL',
+					'nrDomu' => 'nrBudynku',
+					'nrLokalu' => 'nrLokalu',
+				],
+				'base' => '0',
 			],
 			'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
 				'fields' => [
@@ -1528,7 +1523,13 @@ SQL;
 					'miejscowosc' => 'Miejscowosc',
 					'ulica' => 'Ulica',
 				],
-				'full' => true,
+				'fieldsTeryt' => [
+					'TERYT_SYM' => 'TERYT_SYM',
+					'TERYT_SYM_UL' => 'TERYT_SYM_UL',
+					'nrDomu' => 'Numer_budynku',
+					'nrLokalu' => 'Numer_mieszkania_lokalu',
+				],
+				'base' => '0',
 			],
 			'BI_audit_KRS' => [ 
 				'fields' => [
@@ -1539,7 +1540,13 @@ SQL;
 					'ulica' => 'A_ulica',
 					'kodPocztowy' => 'A_kod',
 				],
-				'full' => false,
+				'fieldsTeryt' => [
+					'TERYT_SYM' => 'TERYT_SYM',
+					'TERYT_SYM_UL' => 'TERYT_SYM_UL',
+					'nrDomu' => 'A_nrDomu',
+					'nrLokalu' => 'A_nrLokalu',
+				],
+				'base' => '1',
 			],
 			'BI_audit_KRS_address' => [
 				'fields' => [
@@ -1550,7 +1557,13 @@ SQL;
 					'ulica' => 'A_ulica',
 					'kodPocztowy' => 'A_kod',
 				],
-				'full' => false,
+				'fieldsTeryt' => [
+					'TERYT_SYM' => 'TERYT_SYM',
+					'TERYT_SYM_UL' => 'TERYT_SYM_UL',
+					'nrDomu' => 'A_nrDomu',
+					'nrLokalu' => 'A_nrLokalu',
+				],
+				'base' => '1',
 			],
 			'BI_audit_MSIG_address' => [
 				'fields' => [
@@ -1561,34 +1574,71 @@ SQL;
 					'ulica' => 'A_ulica',
 					'kodPocztowy' => 'A_kod',
 				],
-				'full' => false,
+				'fieldsTeryt' => [
+					'TERYT_SYM' => 'TERYT_SYM',
+					'TERYT_SYM_UL' => 'TERYT_SYM_UL',
+					'nrDomu' => 'A_nrDomu',
+					'nrLokalu' => 'A_nrLokalu',
+				],
+				'base' => '1',
 			],
 		];
 
 		foreach ($tables as $table => $tableConf) {
-			$where = ($full && $tableConf['full']) ? "" : "where `TERYT_SYM` is null and `cached` = 0";
+			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}";
-			try {
-				$adresy = DB::getPDO()->query($query);
-				while ($adres = $adresy->fetch()) {
+			$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);
-						if (!empty($teryt['SYM'])) {
-							$sqlArr = ['TERYT_SYM' => $teryt['SYM']];
-							$sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
-							DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
-						}
 					} catch (Exception $e) {
+						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);
 				}
-			} catch (Exception $e) {
+				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 function reloadCache_updateAll($full, $onlyBase) {
+	private static function reloadCache_updateAll($full, $onlyBase) {
 		$tablesConf = [
 			'BI_audit_CEIDG' => [
 				'fields' => [
@@ -1720,7 +1770,6 @@ SQL;
 				],
 				'base' => '1',
 			],
-                        
 //			'BI_audit_KW_requested_person' => [
 //				'fields' => [
 //					'pesel' => 'Seller_person_pesel',
@@ -1731,6 +1780,10 @@ SQL;
 //				'base' => '0',
 //				//'where' => '',
 //			],
+			'TERYT_adresy' => [
+				'fields' => [],
+				'base' => '1',
+			],
 		];
 
 		$refTablesConf = [
@@ -1738,12 +1791,32 @@ SQL;
 				'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,
 			],
@@ -1752,69 +1825,30 @@ SQL;
 					'BI_audit_KRS_address',
 					'BI_audit_KRS_company',
 					'BI_audit_KRS_person',
+					'TERYT_adresy',
 				],
 				'base' => 1,
 			],
-			'BI_audit_MSIG' => [
+			'BI_audit_KRS_address' => [
 				'refTablesTo' => [
-					'BI_audit_MSIG_address',
-					'BI_audit_MSIG_company',
-					'BI_audit_MSIG_person',
+					'TERYT_adresy',
 				],
 				'base' => 1,
 			],
-			
-			
-
-		];
-		
-		$extraRefTablesConf = [
-			'BI_audit_MSIG_person' => [
-				'refTablesTo' => [
-					'BI_audit_KRS_person',
-					'BI_audit_MSIG',
-					'BI_audit_CEIDG',
-					'BI_audit_ENERGA_PRACOWNICY',
-				],
-			],					
 			'BI_audit_MSIG' => [
 				'refTablesTo' => [
-					'BI_audit_KRS',
-					'BI_audit_ENERGA_RUM_KONTRAHENCI',
-				],
-			],
-			'BI_audit_MSIG_address' => [
-				'refTablesTo' => [
-					'BI_audit_KRS_address',
-					'BI_audit_CEIDG',
-					'BI_audit_ENERGA_PRACOWNICY_adresy',
 					'BI_audit_MSIG_address',
-				],
-			],	
-			'BI_audit_KRS_person' => [
-				'refTablesTo' => [
-					'BI_audit_KRS',
-					'BI_audit_ENERGA_PRACOWNICY',
+					'BI_audit_MSIG_company',
 					'BI_audit_MSIG_person',
 				],
-			],	
-			'BI_audit_MSIG_company' => [
-				'refTablesTo' => [
-					'BI_audit_MSIG',
-				],
-			],	
-			'BI_audit_KRS' => [
-				'refTablesTo' => [
-					'BI_audit_MSIG',
-					'BI_audit_ENERGA_RUM_KONTRAHENCI',
-				],
-			],	
-			'BI_audit_CEIDG' => [
+				'base' => 1,
+			],
+			'BI_audit_MSIG_address' => [
 				'refTablesTo' => [
-					'BI_audit_ENERGA_PRACOWNICY',
-					'BI_audit_ENERGA_RUM_KONTRAHENCI',
+					'TERYT_adresy',
 				],
-			],	
+				'base' => 1,
+			],
 		];
 		
 		$sourceTables = ['BI_audit_ENERGA_PRACOWNICY'];
@@ -1831,20 +1865,18 @@ SQL;
 				foreach ($refTableConf['refTablesTo'] as $refTableTo) {
 					$allTables[] = $refTableTo;
 					if ($refTableConf['base']) continue;
-					$refTable = $this->refTables->getRefTable($refTableFrom, $refTableTo);
-//					$queries[] = "delete from `{$refTable}` where `TRANSACTION_ID` = '-1'";
+					$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 ($extraRefTablesConf as $refTableFrom => $refTableConf) {
 			foreach ($allTables as $refTableFrom) {
-//				foreach ($refTableConf['refTablesTo'] as $refTableTo) {
 				foreach ($allTables as $refTableTo) {
-					if ($refTable = $this->refTables->getRefTable($refTableFrom, $refTableTo)) {
+					if ($refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, false)) {
 						$queries[] = "delete from `{$refTable}` where `TRANSACTION_ID` = '-1'";
-						$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}'";
+						$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";
 					}
 				}
 			}
@@ -1854,11 +1886,14 @@ SQL;
 			if ($onlyBase && (!$tableConf['base'])) continue;
 			$where = "where `cached` = 0";
 			if (!empty($tableConf['where'])) $where .= " {$tableConf['where']}";
-//			$queries[] = "lock tables `{$table}` write";
-			$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}";
+//			$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[] = "unlock tables";
 		}
 
 		$queries[] = "update `BI_audit_ALL` set `nip` = null where `nip` = 0";
@@ -1878,26 +1913,27 @@ SQL;
 		foreach ($refTablesConf as $refTableFrom => $refTableConf) {
 			if ($onlyBase && (!$tableConf['base'])) continue;
 			foreach ($refTableConf['refTablesTo'] as $refTableTo) {
-				$refTable = ACL::getRefTable("default_db/{$refTableFrom}/{$refTableFrom}", "default_db__x3A__{$refTableTo}:{$refTableTo}");
-//				$queries[] = "lock tables `{$refTable}` write";
+				$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 (!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'";
-//				$queries[] = "unlock tables";
 			}
 		}
-//		echo implode(";\n", $queries) . ";\n";
+
 		foreach ($queries as $query) {
 			echo "SQL: {$query}\n";
 			DB::getPDO()->query($query);
 		}
 
 		$BiAuditRelations = new BiAuditRelations();
-//		DB::getPDO()->query("lock tables `BI_audit_ALL` write");
 		$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");
-//		DB::getPDO()->query("unlock tables");
 	}
 
 	public function doReloadCache($full = false) {
@@ -1915,12 +1951,12 @@ SQL;
 		if ($full) file_put_contents($reloadCachePidFile, getmypid());
 		try {
 			//self::importPracownicy(); //TODO
-			error_log('now: self::reloadCache_reTeryt');
-			self::reloadCache_reTeryt($full);
 			error_log('now: self::reloadCache_parseUmowy');
 			self::reloadCache_parseUmowy($full);
-			error_log('now: $this->reloadCache_updateAll');
-			$this->reloadCache_updateAll($full, $onlyBase);
+			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);
@@ -1929,7 +1965,7 @@ SQL;
 		}
 	}
 
-	public static function doGeneratePowiazania($ID) {
+	public function doGeneratePowiazania($ID) {
 		$powiazaniaDirLocation = self::getMainDirectory();
 		$tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
 		$resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
@@ -2035,7 +2071,6 @@ SQL;
 
 class BiAuditRelations {
 	private $RELATIONS_ID = [];
-	private $refTables;
 
 	private $relations = [
 		'nip' => ['nip'],
@@ -2049,7 +2084,6 @@ class BiAuditRelations {
 	private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
 
 	public function __construct() {
-		$this->refTables = new BiAuditRefTables();
 		$query = "select * from BI_audit_ALL_ref_RELATIONS";
 		$result = DB::getPDO()->fetchAll($query);
 		foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
@@ -2067,7 +2101,7 @@ class BiAuditRelations {
 	}
 
 	private function addToRefTable($fromTable, $toTable, $fromID, $toID) {
-		if ($refTable = $this->refTables->getRefTable($fromTable, $toTable)) {
+		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']);
 			}
@@ -2111,10 +2145,12 @@ class BiAuditRelations {
 			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);
 			}
@@ -2123,17 +2159,45 @@ class BiAuditRelations {
 }
 
 class BiAuditRefTables {
-	private $refTables = [];
+	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 function getRefTable($tableFrom, $tableTo) {
-		if (!isset($this->refTables[$tableFrom][$tableTo])) {
+	public static function getRefTables($tableFrom) {
+		static $refTables = [];
+		if (!isset($refTables[$tableFrom])) {
+			$namespace = "default_db/{$tableFrom}/{$tableFrom}";
 			try {
-				$this->refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
+				$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) {
-				$this->refTables[$tableFrom][$tableTo] = false;
+				$refTables[$tableFrom] = [];
 			}
 		}
-		return $this->refTables[$tableFrom][$tableTo];
+		return $refTables[$tableFrom];
 	}
 }
 
@@ -2150,7 +2214,6 @@ class BiAuditPowiazania {
 	private $items_results = [];
 	private $relations = [];
 	private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
-	private $refTables = [];
 	private $step = 0;
 	private $tasksDirLocation;
 	private $progressFile;
@@ -2164,18 +2227,6 @@ class BiAuditPowiazania {
 	private $splittedResults = [];
 	private $maxResults = 1000000;
 
-	private function getRefTable($tableFrom, $tableTo, $returnException = true) {
-		if (!isset($this->refTables[$tableFrom][$tableTo])) {
-			try {
-				$this->refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
-			} catch (Exception $e) {
-				if ($returnException) throw new Exception($e->getMessage());
-				$this->refTables[$tableFrom][$tableTo] = false;
-			}
-		}
-		return $this->refTables[$tableFrom][$tableTo];
-	}
-
 	private static function generateJson($type, $data) {
 		return json_encode(['ts' => microtime(true), 'type' => $type, 'data' => $data]);
 	}
@@ -2241,7 +2292,7 @@ class BiAuditPowiazania {
 
 		$subQueries = [];
 		foreach ($this->destTables as $destTable) {
-			$refTable = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $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);
@@ -2252,7 +2303,7 @@ class BiAuditPowiazania {
 		self::saveToLog("Rozpoczynam wyszukiwanie powiązań");
 
 		$this->progressFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.progress";
-		$refPowiazaniaToPracownicy = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY');
+		$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);
@@ -2340,7 +2391,7 @@ class BiAuditPowiazania {
 		}
 
 		if (!isset($this->nodes[$ID][$relation])) {
-			if ($relation) $where = "and ({$relation} & ref.RELATION_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);
 		}
@@ -2387,6 +2438,7 @@ class BiAuditPowiazania {
 	}
 
 	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);
@@ -2401,11 +2453,17 @@ class BiAuditPowiazania {
 
 		$countBySource = [];
 		$resultsKeys = [];
-		foreach ($this->results as $resultKey => $result) $countBySource[reset(array_keys($result))][] = $resultKey;
+		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) $countByDest[end(array_keys($this->results[$resultKey]))][] = $resultKey;
+				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;
@@ -2444,8 +2502,8 @@ class BiAuditPowiazania {
 		$kw_person = [];
 		$_items_results = [];
 
-		$refUmowyToKontrahenci = $this->getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI');
-		$refKwRequestedToKwRequestedPerson = $this->getRefTable('BI_audit_KW_requested', 'BI_audit_KW_requested_person');
+		$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);
 
 		if ($resultsPart === null) $results = $this->results;
 		else $results = (!empty($this->splittedResults[$resultsPart])) ? $this->splittedResults[$resultsPart] : [];
@@ -2457,16 +2515,18 @@ class BiAuditPowiazania {
 				$row = DB::getPDO()->fetchFirst($query);
 				$query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
 				$obj = DB::fetch(DB::query($query));
-				$item_result = [$row['REMOTE_TABLE'] => (array) $obj];
+				$item_result = [$row['REMOTE_TABLE'] => array_merge(['@attributes' => ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"]], (array) $obj)];
 
-				if ($refTable = $this->getRefTable('BI_audit_operational_raport_note', $row['REMOTE_TABLE'], false)) {
+				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 = $this->getRefTable($row['REMOTE_TABLE'], 'BI_audit_taxpayer', false)) {
+				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'] = $taxpayer;
+					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);
@@ -2478,7 +2538,12 @@ class BiAuditPowiazania {
 					$res = DB::query($query);
 					if (mysql_num_rows($res)) {
 						$umowy = [];
-						while ($obj = DB::fetch($res)) $umowy[] = (array) $obj;
+						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;
@@ -2488,10 +2553,15 @@ class BiAuditPowiazania {
 					$query = "select kw.* from BI_audit_KW_requested kw join `{$refKwRequestedToKwRequestedPerson}` ref on kw.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
 					$res = DB::query($query);
 					if (mysql_num_rows($res)) {
-						$kw = [];
-						while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
+						$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'] = $kw;
+						$item_kw_person['BI_audit_KW_requested'] = $kws;
 						$items_kw_person[] = $item_kw_person;
 					}
 				}
@@ -2513,16 +2583,16 @@ class BiAuditPowiazania {
 			foreach ($this->results as $result) $this->saveToDb($result);
 			self::saveToLog("Zapisano wyliczone dane do bazy");
 		} else {
-			$refPowiazaniaToPowiazaniaRow = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row');
-			$refPowiazaniaRowToPowiazaniaRowObject = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
+			$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', []);
 			DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
 			foreach ($result as $ID => $rel) {
 				$query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
 				$object = DB::getPDO()->fetchFirst($query);
-				$idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relations[$rel]]);
+				$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 = $this->getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', $object['REMOTE_TABLE']);
+				$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']]);
 			}
 		}
@@ -2550,8 +2620,8 @@ class BiAuditPowiazania {
 			self::saveToLog("Brak wyników (#1), nie wygenerowano pliku XML ({$resultsPart})");
 			return null;
 		}
-		if (!$this->items_results[$resultsPart]) $this->generateItemsResults($resultsPart);
-		if (!$this->items_results[$resultsPart]) {
+		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;
 		}