Pārlūkot izejas kodu

fixed code style - whitespace js, Schema

Piotr Labudda 8 gadi atpakaļ
vecāks
revīzija
ff1410cd94
30 mainītis faili ar 3443 papildinājumiem un 3443 dzēšanām
  1. 1 1
      SE/se-lib/Schema/AccessGroupReadStorageAcl.php
  2. 139 139
      SE/se-lib/Schema/AccessGroupStorageAcl.php
  3. 1 1
      SE/se-lib/Schema/AccessGroupWriteStorageAcl.php
  4. 138 138
      SE/se-lib/Schema/AccessOwnerStorageAcl.php
  5. 65 65
      SE/se-lib/Schema/DefaultDb/in7_dziennik_koresp/ZaliczkaKorespStorageAcl.php
  6. 8 8
      SE/se-lib/Schema/DefaultDb/in7_mk_baza_dystrybucji/ZaliczkaProjektStorageAcl.php
  7. 16 16
      SE/se-lib/Schema/DefaultDb/zaliczka/ZaliczkaAktywnaStorageAcl.php
  8. 16 16
      SE/se-lib/Schema/DefaultDb/zaliczka/ZaliczkaAnulowanaStorageAcl.php
  9. 16 16
      SE/se-lib/Schema/DefaultDb/zaliczka/ZaliczkaArchiwalnaStorageAcl.php
  10. 418 418
      SE/se-lib/Schema/DefaultDb/zaliczka/ZaliczkaStorageAcl.php
  11. 167 167
      SE/se-lib/Schema/DefaultDb/zaliczka_pozycja/ZaliczkaPozycjaStorageAcl.php
  12. 222 222
      SE/se-lib/Schema/DefaultDb/zaliczka_wniosek/ZaliczkaWniosekStorageAcl.php
  13. 222 222
      SE/se-lib/Schema/FileStorageAcl.php
  14. 98 98
      SE/se-lib/Schema/KorespondencjaStorageAcl.php
  15. 71 71
      SE/se-lib/Schema/SystemFunctionStorageAcl.php
  16. 4 4
      SE/se-lib/Schema/SystemObjectStorageAcl.php
  17. 67 67
      SE/se-lib/Schema/SystemProcessStorageAcl.php
  18. 184 184
      SE/se-lib/Schema/SystemSourceStorageAcl.php
  19. 1 1
      SE/se-lib/Schema/TableBase.php
  20. 169 169
      SE/se-lib/Schema/TestPermsStorageAcl.php
  21. 131 131
      SE/se-lib/Schema/UserConfigStorageAcl.php
  22. 107 107
      SE/se-lib/Schema/UserObjectStorageAcl.php
  23. 130 130
      SE/se-lib/Schema/UserProcessStorageAcl.php
  24. 147 147
      SE/se-lib/Schema/UserTestStatsStorageAcl.php
  25. 120 120
      SE/se-lib/Schema/UserUrlActionStorageAcl.php
  26. 7 7
      SE/se-lib/TableAjax.php
  27. 511 511
      SE/static/p5UI/buildDom.js
  28. 7 7
      SE/static/p5UI/legacy.js
  29. 97 97
      SE/static/p5UI/menuStore.js
  30. 163 163
      SE/static/p5UI/userBookmarks.js

+ 1 - 1
SE/se-lib/Schema/AccessGroupReadStorageAcl.php

@@ -4,6 +4,6 @@ Lib::loadClass('Schema_AccessGroupStorageAcl');
 
 class Schema_AccessGroupReadStorageAcl extends Schema_AccessGroupStorageAcl {
 
-  public function getName() { return 'AccessGroupRead'; }
+	public function getName() { return 'AccessGroupRead'; }
 
 }

+ 139 - 139
SE/se-lib/Schema/AccessGroupStorageAcl.php

@@ -8,150 +8,150 @@ Lib::loadClass('SqlQueryWhereBuilder');
 
 class Schema_AccessGroupStorageAcl extends Core_AclBase {// Read only class
 
-  public function getNamespace() { return 'default_objects/' . $this->getName(); }
-  public function getSourceName() { return 'default_objects'; }
-  public function init($force = false) {}
-  public function isInitialized() { return true; }
-  public function getName() { return 'AccessGroup'; }
-  public function getRootTableName() { return 'CRM_LISTA_ZASOBOW'; }
-  public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
-  public function getVisibleFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
-  public function getVirtualFieldListByIdZasob() { return array(); }
-  public function getRealFieldListByIdZasob($force = false) {
-    $cols[100000] = 'id';// CRM_LISTA_ZASOBOW.ID
-    $cols[100001] = 'name';// CRM_LISTA_ZASOBOW.DESC
-    $cols[100002] = 'uid';// Ldap.uid -> value stored in fields: A_ADM_COMPANY, A_CLASSIFIED
-    return $cols;
-  }
-  public function getFields() {
-    $fields = array();
-    $fields[100000] = ['name'=>'id', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>100];
-    $fields[100001] = ['name'=>'name', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>101];
-    $fields[100002] = ['name'=>'uid', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>102];
-    return $fields;
-  }
-  public function getFieldType($fieldName) { return null; }
+	public function getNamespace() { return 'default_objects/' . $this->getName(); }
+	public function getSourceName() { return 'default_objects'; }
+	public function init($force = false) {}
+	public function isInitialized() { return true; }
+	public function getName() { return 'AccessGroup'; }
+	public function getRootTableName() { return 'CRM_LISTA_ZASOBOW'; }
+	public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
+	public function getVisibleFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
+	public function getVirtualFieldListByIdZasob() { return array(); }
+	public function getRealFieldListByIdZasob($force = false) {
+		$cols[100000] = 'id';// CRM_LISTA_ZASOBOW.ID
+		$cols[100001] = 'name';// CRM_LISTA_ZASOBOW.DESC
+		$cols[100002] = 'uid';// Ldap.uid -> value stored in fields: A_ADM_COMPANY, A_CLASSIFIED
+		return $cols;
+	}
+	public function getFields() {
+		$fields = array();
+		$fields[100000] = ['name'=>'id', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>100];
+		$fields[100001] = ['name'=>'name', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>101];
+		$fields[100002] = ['name'=>'uid', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>102];
+		return $fields;
+	}
+	public function getFieldType($fieldName) { return null; }
 
-  // TODO: replace legacy functions: isAllowed, hasFieldPerm, getFieldIdByName
-  public function canCreateField($fieldName) { return false; }
-  public function canReadField($fieldName) { return true; }
-  public function canReadObjectField($fieldName, $record) {return true; }
-  public function canWriteField($fieldName) { return false; }
-  public function canWriteObjectField($fieldName, $record) { return false; }
+	// TODO: replace legacy functions: isAllowed, hasFieldPerm, getFieldIdByName
+	public function canCreateField($fieldName) { return false; }
+	public function canReadField($fieldName) { return true; }
+	public function canReadObjectField($fieldName, $record) {return true; }
+	public function canWriteField($fieldName) { return false; }
+	public function canWriteObjectField($fieldName, $record) { return false; }
 
-  public function getTotal($params = array()) {
-    return count($this->getItems($params));
-  }
-  public function getItem($primaryKey, $params = []) {
-    $items = $this->getItems(['primaryKey'=>$primaryKey]);
-    return (!empty($items[$primaryKey])) ? $items[$primaryKey] : null;
-  }
-  public function getItems($params = array()) {
-    $DBG = V::get('DBG_DS', 0, $_GET, 'int');
-    if($DBG>2){echo'<pre>';}
-    if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$params:";print_r($params);echo "\n";}
-    $items = array();
-    // TODO: fetch groups connectes with current user
-  {
-    $userLdapGroups = UsersHelper::getLDAPGroupByUserName(User::getLogin());
-    if($DBG>4){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$userLdapGroups:";print_r($userLdapGroups);echo "\n";}
-    if (empty($userLdapGroups)) throw new Exception("User groups not found", 404);
+	public function getTotal($params = array()) {
+		return count($this->getItems($params));
+	}
+	public function getItem($primaryKey, $params = []) {
+		$items = $this->getItems(['primaryKey'=>$primaryKey]);
+		return (!empty($items[$primaryKey])) ? $items[$primaryKey] : null;
+	}
+	public function getItems($params = array()) {
+		$DBG = V::get('DBG_DS', 0, $_GET, 'int');
+		if($DBG>2){echo'<pre>';}
+		if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$params:";print_r($params);echo "\n";}
+		$items = array();
+		// TODO: fetch groups connectes with current user
+	{
+		$userLdapGroups = UsersHelper::getLDAPGroupByUserName(User::getLogin());
+		if($DBG>4){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$userLdapGroups:";print_r($userLdapGroups);echo "\n";}
+		if (empty($userLdapGroups)) throw new Exception("User groups not found", 404);
 
-    foreach ($userLdapGroups as $vLdapGroup) {
-      $allowGroup = false;
-      if ('workgroup' == $vLdapGroup->cn) {
-        $items[0] = ['id'=>'0', 'name'=>$vLdapGroup->name, 'uid'=>$vLdapGroup->cn];
-      } else {
-        $cnTest = str_replace('-', '_', $vLdapGroup->cn);
-        $cnTest = explode('_', $cnTest);
-        $idZasob = $cnTest[0];
-        if (!is_numeric($idZasob)) {
-          if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems - skip cn - missing id zasob \$vLdapGroup->cn:";print_r($vLdapGroup->cn);echo "\n";}
-          continue;
-        }
-        $items[$idZasob] = ['id'=>$idZasob, 'name'=>$vLdapGroup->name, 'uid'=>$vLdapGroup->cn];
-      }
-    }
-  }
-    if ($pk = V::get('primaryKey', '', $params, 'int')) {// [primaryKey] => 2948
-      if (!array_key_exists($pk, $items)) return array();
-      $items = array($pk => $items[$pk]);
-    }
-    if (!empty($params['ogc:Filter'])) {
-      $parser = new ParseOgcFilter();
-      $parser->loadOgcFilter($params['ogc:Filter']);
-      $queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
-      DBG::_('DBG_DS', '>2', "ogc:Filter \$queryWhereBuilder", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
-      if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$items:";print_r($items);echo "\n";}
-      $items = array_filter($items, array($queryWhereBuilder, 'filterRawArray'));
-    }
-    $filterId = trim(V::get('f_id', '', $params));
-    if (strlen($filterId)) {// allow '0'
-      $queryWhereBuilder = new SqlQueryWhereBuilder();
-      if (is_numeric($filterId)) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', '=', $filterId);
-      } else if (false !== strpos($filterId, '%') && is_numeric(trim($filterId, '%'))) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', 'like', $filterId);
-      } else if ('>=' == substr($filterId, 0, 2) && is_numeric(substr($filterId, 2))) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', 'GreaterThenOrEqualTo', substr($filterId, 2));
-      } else if ('<=' == substr($filterId, 0, 2) && is_numeric(substr($filterId, 2))) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', 'LessThenOrEqualTo', substr($filterId, 2));
-      } else if ('>' == substr($filterId, 0, 1) && is_numeric(substr($filterId, 1))) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', 'GreaterThen', substr($filterId, 1));
-      } else if ('<' == substr($filterId, 0, 1) && is_numeric(substr($filterId, 1))) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', 'LessThen', substr($filterId, 1));
-      } else if ('=' == substr($filterId, 0, 1) && is_numeric(substr($filterId, 1))) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', '=', substr($filterId, 1));
-      } else {
-        $filterId = null;// TODO: BUG uniimplemented comparison sign
-      }
-      if ($filterId) $items = array_filter($items, array($queryWhereBuilder, 'filterRawArray'));
-    }
+		foreach ($userLdapGroups as $vLdapGroup) {
+			$allowGroup = false;
+			if ('workgroup' == $vLdapGroup->cn) {
+				$items[0] = ['id'=>'0', 'name'=>$vLdapGroup->name, 'uid'=>$vLdapGroup->cn];
+			} else {
+				$cnTest = str_replace('-', '_', $vLdapGroup->cn);
+				$cnTest = explode('_', $cnTest);
+				$idZasob = $cnTest[0];
+				if (!is_numeric($idZasob)) {
+					if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems - skip cn - missing id zasob \$vLdapGroup->cn:";print_r($vLdapGroup->cn);echo "\n";}
+					continue;
+				}
+				$items[$idZasob] = ['id'=>$idZasob, 'name'=>$vLdapGroup->name, 'uid'=>$vLdapGroup->cn];
+			}
+		}
+	}
+		if ($pk = V::get('primaryKey', '', $params, 'int')) {// [primaryKey] => 2948
+			if (!array_key_exists($pk, $items)) return array();
+			$items = array($pk => $items[$pk]);
+		}
+		if (!empty($params['ogc:Filter'])) {
+			$parser = new ParseOgcFilter();
+			$parser->loadOgcFilter($params['ogc:Filter']);
+			$queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
+			DBG::_('DBG_DS', '>2', "ogc:Filter \$queryWhereBuilder", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
+			if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$items:";print_r($items);echo "\n";}
+			$items = array_filter($items, array($queryWhereBuilder, 'filterRawArray'));
+		}
+		$filterId = trim(V::get('f_id', '', $params));
+		if (strlen($filterId)) {// allow '0'
+			$queryWhereBuilder = new SqlQueryWhereBuilder();
+			if (is_numeric($filterId)) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', '=', $filterId);
+			} else if (false !== strpos($filterId, '%') && is_numeric(trim($filterId, '%'))) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', 'like', $filterId);
+			} else if ('>=' == substr($filterId, 0, 2) && is_numeric(substr($filterId, 2))) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', 'GreaterThenOrEqualTo', substr($filterId, 2));
+			} else if ('<=' == substr($filterId, 0, 2) && is_numeric(substr($filterId, 2))) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', 'LessThenOrEqualTo', substr($filterId, 2));
+			} else if ('>' == substr($filterId, 0, 1) && is_numeric(substr($filterId, 1))) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', 'GreaterThen', substr($filterId, 1));
+			} else if ('<' == substr($filterId, 0, 1) && is_numeric(substr($filterId, 1))) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', 'LessThen', substr($filterId, 1));
+			} else if ('=' == substr($filterId, 0, 1) && is_numeric(substr($filterId, 1))) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', '=', substr($filterId, 1));
+			} else {
+				$filterId = null;// TODO: BUG uniimplemented comparison sign
+			}
+			if ($filterId) $items = array_filter($items, array($queryWhereBuilder, 'filterRawArray'));
+		}
 
-    foreach (['name', 'uid'] as $fieldName) {
-      $filterValue = trim(V::get("f_{$fieldName}", '', $params));
-      if (strlen($filterValue)) {// allow '0'
-        $queryWhereBuilder = new SqlQueryWhereBuilder();
-        if (!is_scalar($filterValue)) {
-        } else if ('=' == substr($filterValue, 0, 1)) {
-          $queryWhereBuilder->addComparisonFieldToValue($fieldName, '=', substr($filterValue, 1));
-        } else {
-          if ('%' != substr($filterValue, 0, 1)) $filterValue = "%{$filterValue}";
-          if ('%' != substr($filterValue, -1)) $filterValue = "{$filterValue}%";
-          $queryWhereBuilder->addComparisonFieldToValue($fieldName, 'like', $filterValue);
-        }
-        $items = array_filter($items, array($queryWhereBuilder, 'filterRawArray'));
-      }
-    }
+		foreach (['name', 'uid'] as $fieldName) {
+			$filterValue = trim(V::get("f_{$fieldName}", '', $params));
+			if (strlen($filterValue)) {// allow '0'
+				$queryWhereBuilder = new SqlQueryWhereBuilder();
+				if (!is_scalar($filterValue)) {
+				} else if ('=' == substr($filterValue, 0, 1)) {
+					$queryWhereBuilder->addComparisonFieldToValue($fieldName, '=', substr($filterValue, 1));
+				} else {
+					if ('%' != substr($filterValue, 0, 1)) $filterValue = "%{$filterValue}";
+					if ('%' != substr($filterValue, -1)) $filterValue = "{$filterValue}%";
+					$queryWhereBuilder->addComparisonFieldToValue($fieldName, 'like', $filterValue);
+				}
+				$items = array_filter($items, array($queryWhereBuilder, 'filterRawArray'));
+			}
+		}
 
-    $orderBy = strtolower(V::get('order_by', 'id', $params));
-    $orderDir = strtolower(V::get('order_dir', 'desc', $params));
-    if (!in_array($orderBy, ['id', 'name', 'uid'])) throw new HttpException("Bad Request - wrong or missing order by", 400);
-    if (!in_array($orderDir, ['desc', 'asc'])) throw new HttpException("Bad Request - wrong or missing order dir", 400);
-    uasort($items, function ($a, $b) use ($orderBy, $orderDir) {
-      if ('desc' == $orderDir) {
-        return (V::geti($orderBy, '', $a) > V::geti($orderBy, '', $b)) ? -1 : 1;
-      } else if ('asc' == $orderDir) {
-        return (V::geti($orderBy, '', $a) > V::geti($orderBy, '', $b)) ? 1 : -1;
-      }
-      return 0;
-    });
+		$orderBy = strtolower(V::get('order_by', 'id', $params));
+		$orderDir = strtolower(V::get('order_dir', 'desc', $params));
+		if (!in_array($orderBy, ['id', 'name', 'uid'])) throw new HttpException("Bad Request - wrong or missing order by", 400);
+		if (!in_array($orderDir, ['desc', 'asc'])) throw new HttpException("Bad Request - wrong or missing order dir", 400);
+		uasort($items, function ($a, $b) use ($orderBy, $orderDir) {
+			if ('desc' == $orderDir) {
+				return (V::geti($orderBy, '', $a) > V::geti($orderBy, '', $b)) ? -1 : 1;
+			} else if ('asc' == $orderDir) {
+				return (V::geti($orderBy, '', $a) > V::geti($orderBy, '', $b)) ? 1 : -1;
+			}
+			return 0;
+		});
 
-    if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$items:";print_r($items);echo "\n";}
-    return $items;
-  }
-  public function addItem($itemTodo) { throw new Exception("Insert not allowed"); }
-  public function updateItem($itemPatch) { throw new Exception("Update not allowed"); }
-  public function getGeomFieldType($fieldName) { return null; }
-  public function getPrimaryKeyField() { return 'id'; }
-  public function getAttributesFromZasoby() { return array(); }
-  public function isEnumerationField($fieldName) { return false; }
-  public function getEnumerations($fieldName) { return null; }
-  public function getXsdFieldType($fieldName) {
-    if ('id' == $fieldName) return 'xsd:string';
-    if ('name' == $fieldName) return 'xsd:string';
-    if ('uid' == $fieldName) return 'xsd:string';
-  }
-  public function isGeomField($fldName) { return false; }
+		if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$items:";print_r($items);echo "\n";}
+		return $items;
+	}
+	public function addItem($itemTodo) { throw new Exception("Insert not allowed"); }
+	public function updateItem($itemPatch) { throw new Exception("Update not allowed"); }
+	public function getGeomFieldType($fieldName) { return null; }
+	public function getPrimaryKeyField() { return 'id'; }
+	public function getAttributesFromZasoby() { return array(); }
+	public function isEnumerationField($fieldName) { return false; }
+	public function getEnumerations($fieldName) { return null; }
+	public function getXsdFieldType($fieldName) {
+		if ('id' == $fieldName) return 'xsd:string';
+		if ('name' == $fieldName) return 'xsd:string';
+		if ('uid' == $fieldName) return 'xsd:string';
+	}
+	public function isGeomField($fldName) { return false; }
 
 }

+ 1 - 1
SE/se-lib/Schema/AccessGroupWriteStorageAcl.php

@@ -4,6 +4,6 @@ Lib::loadClass('Schema_AccessGroupStorageAcl');
 
 class Schema_AccessGroupWriteStorageAcl extends Schema_AccessGroupStorageAcl {
 
-  public function getName() { return 'AccessGroupWrite'; }
+	public function getName() { return 'AccessGroupWrite'; }
 
 }

+ 138 - 138
SE/se-lib/Schema/AccessOwnerStorageAcl.php

@@ -5,152 +5,152 @@ Lib::loadClass('ParseOgcFilter');
 
 class Schema_AccessOwnerStorageAcl extends Core_AclBase {
 
-  public function getNamespace() { return 'default_objects/' . $this->getName(); }
-  public function getSourceName() { return 'default_objects'; }
-  public function init($force = false) {}
-  public function isInitialized() { return true; }
-  public function getName() { return 'AccessOwner'; }
-  public function getRootTableName() { return 'ADMIN_USERS'; }// TODO: turn off - use getName for generating ref's
-  public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
-  public function getVisibleFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
-  public function getVirtualFieldListByIdZasob() { return array(); }
-  public function getXsdTypes() {// TODO: mv to Core_AclBase
-    $xsdTypes = array();
-    foreach ($this->getFields() as $idZasob => $field) {
-      $xsdTypes[ $field['name'] ] = $field;
-      $xsdTypes[ $field['name'] ][ 'xsdType' ] = $this->getXsdFieldType($field['name']);
-    }
-    return $xsdTypes;
-  }
-  public function getRealFieldListByIdZasob($force = false) {
-    $cols = array();
-    $cols[100000] = 'id';// ADMIN_USERS.ID
-    $cols[100001] = 'login';// ADMIN_USERS.ADM_ACCOUNT
-    $cols[100002] = 'name';// ADMIN_USERS.ADM_NAME
-    return $cols;
-  }
-  public function getFields() {
-    $fields = array();
-    $fields[100000] = ['name'=>'id', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>100];
-    $fields[100001] = ['name'=>'login', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>101];
-    $fields[100002] = ['name'=>'name', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>102];
-    return $fields;
-  }
-  public function getFieldType($fieldName) { return null; }
+	public function getNamespace() { return 'default_objects/' . $this->getName(); }
+	public function getSourceName() { return 'default_objects'; }
+	public function init($force = false) {}
+	public function isInitialized() { return true; }
+	public function getName() { return 'AccessOwner'; }
+	public function getRootTableName() { return 'ADMIN_USERS'; }// TODO: turn off - use getName for generating ref's
+	public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
+	public function getVisibleFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
+	public function getVirtualFieldListByIdZasob() { return array(); }
+	public function getXsdTypes() {// TODO: mv to Core_AclBase
+		$xsdTypes = array();
+		foreach ($this->getFields() as $idZasob => $field) {
+			$xsdTypes[ $field['name'] ] = $field;
+			$xsdTypes[ $field['name'] ][ 'xsdType' ] = $this->getXsdFieldType($field['name']);
+		}
+		return $xsdTypes;
+	}
+	public function getRealFieldListByIdZasob($force = false) {
+		$cols = array();
+		$cols[100000] = 'id';// ADMIN_USERS.ID
+		$cols[100001] = 'login';// ADMIN_USERS.ADM_ACCOUNT
+		$cols[100002] = 'name';// ADMIN_USERS.ADM_NAME
+		return $cols;
+	}
+	public function getFields() {
+		$fields = array();
+		$fields[100000] = ['name'=>'id', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>100];
+		$fields[100001] = ['name'=>'login', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>101];
+		$fields[100002] = ['name'=>'name', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>102];
+		return $fields;
+	}
+	public function getFieldType($fieldName) { return null; }
 
-  // TODO: replace legacy functions: isAllowed, hasFieldPerm, getFieldIdByName
-  public function canCreateField($fieldName) { return false; }
-  public function canReadField($fieldName) { return true; }
-  public function canReadObjectField($fieldName, $record) {return true; }
-  public function canWriteField($fieldName) { return false; }
-  public function canWriteObjectField($fieldName, $record) { return false; }
+	// TODO: replace legacy functions: isAllowed, hasFieldPerm, getFieldIdByName
+	public function canCreateField($fieldName) { return false; }
+	public function canReadField($fieldName) { return true; }
+	public function canReadObjectField($fieldName, $record) {return true; }
+	public function canWriteField($fieldName) { return false; }
+	public function canWriteObjectField($fieldName, $record) { return false; }
 
-  public function getTotal($params = array()) {
-    return count($this->getItems($params));
-  }
-  public function getItem($primaryKey, $params = []) {
-    $items = $this->getItems(['primaryKey'=>$primaryKey]);
-    return (!empty($items[$primaryKey])) ? $items[$primaryKey] : null;
-  }
-  public function getItems($params = array()) {
-    $DBG = V::get('DBG_DS', 0, $_GET, 'int');
-    if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$params:";print_r($params);echo "\n";}
+	public function getTotal($params = array()) {
+		return count($this->getItems($params));
+	}
+	public function getItem($primaryKey, $params = []) {
+		$items = $this->getItems(['primaryKey'=>$primaryKey]);
+		return (!empty($items[$primaryKey])) ? $items[$primaryKey] : null;
+	}
+	public function getItems($params = array()) {
+		$DBG = V::get('DBG_DS', 0, $_GET, 'int');
+		if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$params:";print_r($params);echo "\n";}
 
-    $sqlWhereAndPk = "";
-    if ($pk = V::get('@primaryKey', null, $params)) {// [@primaryKey] => TODO: int or array of int
-      if (!is_array($pk)) $sqlPk = array($pk);
-      else $sqlPk = $pk;
-      $sqlWhereAndPk = "and u.ID in (" . implode(", ", $sqlPk) . ")";
-    }
+		$sqlWhereAndPk = "";
+		if ($pk = V::get('@primaryKey', null, $params)) {// [@primaryKey] => TODO: int or array of int
+			if (!is_array($pk)) $sqlPk = array($pk);
+			else $sqlPk = $pk;
+			$sqlWhereAndPk = "and u.ID in (" . implode(", ", $sqlPk) . ")";
+		}
 
-    $items = DB::getPDO()->fetchAllByKey("
-      select u.ID as id, u.ADM_ACCOUNT as login, u.ADM_NAME as name
-      from ADMIN_USERS u
-      where u.A_STATUS = 'NORMAL'
-        and u.ADM_TECH_WORKER != 'NO'
-        {$sqlWhereAndPk}
-    ", $key = 'id');
+		$items = DB::getPDO()->fetchAllByKey("
+			select u.ID as id, u.ADM_ACCOUNT as login, u.ADM_NAME as name
+			from ADMIN_USERS u
+			where u.A_STATUS = 'NORMAL'
+				and u.ADM_TECH_WORKER != 'NO'
+				{$sqlWhereAndPk}
+		", $key = 'id');
 
-    if ($pk = V::get('primaryKey', 0, $params, 'int')) {// [primaryKey] => 2948
-      if (!array_key_exists($pk, $items)) return array();
-      $items = array($pk => $items[$pk]);
-    }
-    if (!empty($params['ogc:Filter'])) {
-      $parser = new ParseOgcFilter();
-      $parser->loadOgcFilter($params['ogc:Filter']);
-      $queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
-      DBG::_('DBG_DS', '>2', "ogc:Filter \$queryWhereBuilder", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
-      if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$items:";print_r($items);echo "\n";}
-      $items = array_filter($items, array($queryWhereBuilder, 'filterRawArray'));
-    }
+		if ($pk = V::get('primaryKey', 0, $params, 'int')) {// [primaryKey] => 2948
+			if (!array_key_exists($pk, $items)) return array();
+			$items = array($pk => $items[$pk]);
+		}
+		if (!empty($params['ogc:Filter'])) {
+			$parser = new ParseOgcFilter();
+			$parser->loadOgcFilter($params['ogc:Filter']);
+			$queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
+			DBG::_('DBG_DS', '>2', "ogc:Filter \$queryWhereBuilder", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
+			if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$items:";print_r($items);echo "\n";}
+			$items = array_filter($items, array($queryWhereBuilder, 'filterRawArray'));
+		}
 
-    $filterId = trim(V::get('f_id', '', $params));
-    if (strlen($filterId)) {// allow '0'
-      $queryWhereBuilder = new SqlQueryWhereBuilder();
-      if (is_numeric($filterId)) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', '=', $filterId);
-      } else if (false !== strpos($filterId, '%') && is_numeric(trim($filterId, '%'))) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', 'like', $filterId);
-      } else if ('>=' == substr($filterId, 0, 2) && is_numeric(substr($filterId, 2))) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', 'GreaterThenOrEqualTo', substr($filterId, 2));
-      } else if ('<=' == substr($filterId, 0, 2) && is_numeric(substr($filterId, 2))) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', 'LessThenOrEqualTo', substr($filterId, 2));
-      } else if ('>' == substr($filterId, 0, 1) && is_numeric(substr($filterId, 1))) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', 'GreaterThen', substr($filterId, 1));
-      } else if ('<' == substr($filterId, 0, 1) && is_numeric(substr($filterId, 1))) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', 'LessThen', substr($filterId, 1));
-      } else if ('=' == substr($filterId, 0, 1) && is_numeric(substr($filterId, 1))) {
-        $queryWhereBuilder->addComparisonFieldToValue('id', '=', substr($filterId, 1));
-      } else {
-        $filterId = null;// TODO: BUG uniimplemented comparison sign
-      }
-      if ($filterId) $items = array_filter($items, array($queryWhereBuilder, 'filterRawArray'));
-    }
+		$filterId = trim(V::get('f_id', '', $params));
+		if (strlen($filterId)) {// allow '0'
+			$queryWhereBuilder = new SqlQueryWhereBuilder();
+			if (is_numeric($filterId)) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', '=', $filterId);
+			} else if (false !== strpos($filterId, '%') && is_numeric(trim($filterId, '%'))) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', 'like', $filterId);
+			} else if ('>=' == substr($filterId, 0, 2) && is_numeric(substr($filterId, 2))) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', 'GreaterThenOrEqualTo', substr($filterId, 2));
+			} else if ('<=' == substr($filterId, 0, 2) && is_numeric(substr($filterId, 2))) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', 'LessThenOrEqualTo', substr($filterId, 2));
+			} else if ('>' == substr($filterId, 0, 1) && is_numeric(substr($filterId, 1))) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', 'GreaterThen', substr($filterId, 1));
+			} else if ('<' == substr($filterId, 0, 1) && is_numeric(substr($filterId, 1))) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', 'LessThen', substr($filterId, 1));
+			} else if ('=' == substr($filterId, 0, 1) && is_numeric(substr($filterId, 1))) {
+				$queryWhereBuilder->addComparisonFieldToValue('id', '=', substr($filterId, 1));
+			} else {
+				$filterId = null;// TODO: BUG uniimplemented comparison sign
+			}
+			if ($filterId) $items = array_filter($items, array($queryWhereBuilder, 'filterRawArray'));
+		}
 
-    foreach (['login', 'name'] as $fieldName) {
-      $filterValue = trim(V::get("f_{$fieldName}", '', $params));
-      if (strlen($filterValue)) {// allow '0'
-        $queryWhereBuilder = new SqlQueryWhereBuilder();
-        if (!is_scalar($filterValue)) {
-        } else if ('=' == substr($filterValue, 0, 1)) {
-          $queryWhereBuilder->addComparisonFieldToValue($fieldName, '=', substr($filterValue, 1));
-        } else {
-          if ('%' != substr($filterValue, 0, 1)) $filterValue = "%{$filterValue}";
-          if ('%' != substr($filterValue, -1)) $filterValue = "{$filterValue}%";
-          $queryWhereBuilder->addComparisonFieldToValue($fieldName, 'like', $filterValue);
-        }
-        $items = array_filter($items, array($queryWhereBuilder, 'filterRawArray'));
-      }
-    }
+		foreach (['login', 'name'] as $fieldName) {
+			$filterValue = trim(V::get("f_{$fieldName}", '', $params));
+			if (strlen($filterValue)) {// allow '0'
+				$queryWhereBuilder = new SqlQueryWhereBuilder();
+				if (!is_scalar($filterValue)) {
+				} else if ('=' == substr($filterValue, 0, 1)) {
+					$queryWhereBuilder->addComparisonFieldToValue($fieldName, '=', substr($filterValue, 1));
+				} else {
+					if ('%' != substr($filterValue, 0, 1)) $filterValue = "%{$filterValue}";
+					if ('%' != substr($filterValue, -1)) $filterValue = "{$filterValue}%";
+					$queryWhereBuilder->addComparisonFieldToValue($fieldName, 'like', $filterValue);
+				}
+				$items = array_filter($items, array($queryWhereBuilder, 'filterRawArray'));
+			}
+		}
 
-    $orderBy = strtolower(V::get('order_by', 'id', $params));
-    $orderDir = strtolower(V::get('order_dir', 'desc', $params));
-    if (!in_array($orderBy, ['id', 'login', 'name'])) throw new HttpException("Bad Request - wrong or missing order by", 400);
-    if (!in_array($orderDir, ['desc', 'asc'])) throw new HttpException("Bad Request - wrong or missing order dir", 400);
-    uasort($items, function ($a, $b) use ($orderBy, $orderDir) {
-      if ('desc' == $orderDir) {
-        return (V::geti($orderBy, '', $a) > V::geti($orderBy, '', $b)) ? -1 : 1;
-      } else if ('asc' == $orderDir) {
-        return (V::geti($orderBy, '', $a) > V::geti($orderBy, '', $b)) ? 1 : -1;
-      }
-      return 0;
-    });
+		$orderBy = strtolower(V::get('order_by', 'id', $params));
+		$orderDir = strtolower(V::get('order_dir', 'desc', $params));
+		if (!in_array($orderBy, ['id', 'login', 'name'])) throw new HttpException("Bad Request - wrong or missing order by", 400);
+		if (!in_array($orderDir, ['desc', 'asc'])) throw new HttpException("Bad Request - wrong or missing order dir", 400);
+		uasort($items, function ($a, $b) use ($orderBy, $orderDir) {
+			if ('desc' == $orderDir) {
+				return (V::geti($orderBy, '', $a) > V::geti($orderBy, '', $b)) ? -1 : 1;
+			} else if ('asc' == $orderDir) {
+				return (V::geti($orderBy, '', $a) > V::geti($orderBy, '', $b)) ? 1 : -1;
+			}
+			return 0;
+		});
 
-    if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$items:";print_r($items);echo "\n";}
-    return $items;
-  }
-  public function addItem($itemTodo) { throw new Exception("Insert not allowed"); }
-  public function updateItem($itemPatch) { throw new Exception("Update not allowed"); }
-  public function getGeomFieldType($fieldName) { return null; }
-  public function getPrimaryKeyField() { return 'id'; }
-  public function getAttributesFromZasoby() { return array(); }
-  public function isEnumerationField($fieldName) { return false; }
-  public function getEnumerations($fieldName) { return null; }
-  public function getXsdFieldType($fieldName) {
-    if ('id' == $fieldName) return 'xsd:string';
-    if ('login' == $fieldName) return 'xsd:string';
-    if ('name' == $fieldName) return 'xsd:string';
-  }
-  public function isGeomField($fldName) { return false; }
+		if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$items:";print_r($items);echo "\n";}
+		return $items;
+	}
+	public function addItem($itemTodo) { throw new Exception("Insert not allowed"); }
+	public function updateItem($itemPatch) { throw new Exception("Update not allowed"); }
+	public function getGeomFieldType($fieldName) { return null; }
+	public function getPrimaryKeyField() { return 'id'; }
+	public function getAttributesFromZasoby() { return array(); }
+	public function isEnumerationField($fieldName) { return false; }
+	public function getEnumerations($fieldName) { return null; }
+	public function getXsdFieldType($fieldName) {
+		if ('id' == $fieldName) return 'xsd:string';
+		if ('login' == $fieldName) return 'xsd:string';
+		if ('name' == $fieldName) return 'xsd:string';
+	}
+	public function isGeomField($fldName) { return false; }
 
 }

+ 65 - 65
SE/se-lib/Schema/DefaultDb/in7_dziennik_koresp/ZaliczkaKorespStorageAcl.php

@@ -5,72 +5,72 @@ Lib::loadClass('Core_AclHelper');
 
 class Schema_DefaultDb_in7_dziennik_koresp_ZaliczkaKorespStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_db/IN7_DZIENNIK_KORESP/ZaliczkaKoresp',
-      '@primaryKey' => 'id',
-      'id' => [ '@type' => 'xsd:integer', '@alias' => 'ID' ],
-      'title' => [ '@type' => 'xsd:string', '@alias' => 'K_ZAWARTOS' ],
-      'kategoriaKosztu' => [ '@type' => 'xsd:string', '@alias' => 'KATEGORIA_KOSZTU' ],
-      'projekt' => [ '@ref' => 'default_db/IN7_MK_BAZA_DYSTRYBUCJI/ZaliczkaProjekt' ],
-    ],
-  ];
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_db/IN7_DZIENNIK_KORESP/ZaliczkaKoresp',
+			'@primaryKey' => 'id',
+			'id' => [ '@type' => 'xsd:integer', '@alias' => 'ID' ],
+			'title' => [ '@type' => 'xsd:string', '@alias' => 'K_ZAWARTOS' ],
+			'kategoriaKosztu' => [ '@type' => 'xsd:string', '@alias' => 'KATEGORIA_KOSZTU' ],
+			'projekt' => [ '@ref' => 'default_db/IN7_MK_BAZA_DYSTRYBUCJI/ZaliczkaProjekt' ],
+		],
+	];
 
-  public function getItems($params = array()) {
-    DBG::log($params);// f_title' => 'kore'
-    $sqlWhereAnd = array();
-    if (empty($params)) {
-    } else if (!empty($params['@primaryKey'])) {// [@primaryKey] => Array ([0] => 59599)
-      if (is_array($params['@primaryKey'])) {
-        $sqlWhereAnd[] = "k.ID in(" . implode(", ", $params['@primaryKey']) . ")";
-      }
-    } else if (!empty($params['f_title'])) {
-      DBG::log("return filter by K_ZAWARTOS, K_OD_KOGO like '%{$params['f_title']}%' order by last created rows by user or another users");
-      $sqlParamTitle = DB::getPDO()->quote("%{$params['f_title']}%", PDO::PARAM_STR);
-      $sqlWhereAnd[] = " (
-        k.ID like {$sqlParamTitle}
-        or k.K_ZAWARTOS like {$sqlParamTitle}
-        or k.K_OD_KOGO like {$sqlParamTitle}
-      ) ";
-    }
-    $sqlWhere = (!empty($sqlWhereAnd)) ? implode(" and ", $sqlWhereAnd) : "1=1";
+	public function getItems($params = array()) {
+		DBG::log($params);// f_title' => 'kore'
+		$sqlWhereAnd = array();
+		if (empty($params)) {
+		} else if (!empty($params['@primaryKey'])) {// [@primaryKey] => Array ([0] => 59599)
+			if (is_array($params['@primaryKey'])) {
+				$sqlWhereAnd[] = "k.ID in(" . implode(", ", $params['@primaryKey']) . ")";
+			}
+		} else if (!empty($params['f_title'])) {
+			DBG::log("return filter by K_ZAWARTOS, K_OD_KOGO like '%{$params['f_title']}%' order by last created rows by user or another users");
+			$sqlParamTitle = DB::getPDO()->quote("%{$params['f_title']}%", PDO::PARAM_STR);
+			$sqlWhereAnd[] = " (
+				k.ID like {$sqlParamTitle}
+				or k.K_ZAWARTOS like {$sqlParamTitle}
+				or k.K_OD_KOGO like {$sqlParamTitle}
+			) ";
+		}
+		$sqlWhere = (!empty($sqlWhereAnd)) ? implode(" and ", $sqlWhereAnd) : "1=1";
 
-    return array_map(
-      function ($row) {
-        return [
-          'id' => $row['id'],
-          'title' => $row['title'],
-          'kategoriaKosztu' => $row['kategoriaKosztu'],
-          'projekt' => ($row['ID_PROJECT'] > 0)
-            ? array(DB::getPDO()->fetchFirst("
-              select p.ID as id
-                  , p.M_DIST_DEALNUM as nrBudowy
-              from IN7_MK_BAZA_DYSTRYBUCJI p
-              where p.ID = {$row['ID_PROJECT']}
-            "))
-            : null,
-        ];
-      },
-      DB::getPDO()->fetchAll("
-        select k.ID as id
-          , CONCAT(
-              k.K_ZAWARTOS
-              , ' (' , k.K_OD_KOGO , ')'
-              , ' [', k.ID, ']'
-            ) as title
-          , k.KATEGORIA_KOSZTU as kategoriaKosztu
-          , k.ID_PROJECT
-        from IN7_DZIENNIK_KORESP k
-        where {$sqlWhere}
-        order by ID desc
-        limit 30
-      ")
-    );
-    // return [
-    //   [ 'id' => "65432", 'title' => "testowa koresp 1", 'kategoriaKosztu' => "KOSZT1" ],
-    //   [ 'id' => "10008", 'title' => "testowa koresp 8", 'kategoriaKosztu' => "KOSZT8" ],
-    //   [ 'id' => "10009", 'title' => "testowa koresp 9", 'kategoriaKosztu' => "KOSZT9" ],
-    // ];
-  }
+		return array_map(
+			function ($row) {
+				return [
+					'id' => $row['id'],
+					'title' => $row['title'],
+					'kategoriaKosztu' => $row['kategoriaKosztu'],
+					'projekt' => ($row['ID_PROJECT'] > 0)
+						? array(DB::getPDO()->fetchFirst("
+							select p.ID as id
+									, p.M_DIST_DEALNUM as nrBudowy
+							from IN7_MK_BAZA_DYSTRYBUCJI p
+							where p.ID = {$row['ID_PROJECT']}
+						"))
+						: null,
+				];
+			},
+			DB::getPDO()->fetchAll("
+				select k.ID as id
+					, CONCAT(
+							k.K_ZAWARTOS
+							, ' (' , k.K_OD_KOGO , ')'
+							, ' [', k.ID, ']'
+						) as title
+					, k.KATEGORIA_KOSZTU as kategoriaKosztu
+					, k.ID_PROJECT
+				from IN7_DZIENNIK_KORESP k
+				where {$sqlWhere}
+				order by ID desc
+				limit 30
+			")
+		);
+		// return [
+		//	 [ 'id' => "65432", 'title' => "testowa koresp 1", 'kategoriaKosztu' => "KOSZT1" ],
+		//	 [ 'id' => "10008", 'title' => "testowa koresp 8", 'kategoriaKosztu' => "KOSZT8" ],
+		//	 [ 'id' => "10009", 'title' => "testowa koresp 9", 'kategoriaKosztu' => "KOSZT9" ],
+		// ];
+	}
 
 }

+ 8 - 8
SE/se-lib/Schema/DefaultDb/in7_mk_baza_dystrybucji/ZaliczkaProjektStorageAcl.php

@@ -5,13 +5,13 @@ Lib::loadClass('Core_AclHelper');
 
 class Schema_DefaultDb_in7_mk_baza_dystrybucji_ZaliczkaProjektStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_db/IN7_MK_BAZA_DYSTRYBUCJI/ZaliczkaProjekt',
-      '@primaryKey' => 'id',
-      'id' => [ '@type' => 'xsd:integer', '@alias' => 'ID' ],
-      'nrBudowy' => [ '@type' => 'xsd:string', '@alias' => 'M_DIST_DEALNUM' ],// TODO: ? M_DIST_DESC (szerszy opis)
-    ],
-  ];
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_db/IN7_MK_BAZA_DYSTRYBUCJI/ZaliczkaProjekt',
+			'@primaryKey' => 'id',
+			'id' => [ '@type' => 'xsd:integer', '@alias' => 'ID' ],
+			'nrBudowy' => [ '@type' => 'xsd:string', '@alias' => 'M_DIST_DEALNUM' ],// TODO: ? M_DIST_DESC (szerszy opis)
+		],
+	];
 
 }

+ 16 - 16
SE/se-lib/Schema/DefaultDb/zaliczka/ZaliczkaAktywnaStorageAcl.php

@@ -6,21 +6,21 @@ Lib::loadClass('Schema_DefaultDb_zaliczka_ZaliczkaStorageAcl');
 
 class Schema_DefaultDb_zaliczka_ZaliczkaAktywnaStorageAcl extends Schema_DefaultDb_zaliczka_ZaliczkaStorageAcl {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_db/ZALICZKA/ZaliczkaAktywna',// Api_WfsNs::getBaseWfsUri() . '/default_db/Zaliczka'
-      '@derived' => [
-        'default_db/ZALICZKA/Zaliczka'
-      ],
-      '@primaryKey' => 'id',
-      'id' => 'xsd:integer',
-      'created' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_CREATE_DATE' ],
-      'worker' => [ '@ref' => 'default_objects/AccessOwner' ],// 'alias_ref:default_objects:AccessOwner'
-      // 'worker' => [ '@ref' => 'Worker' ],
-      'kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
-      'nierozliczona_kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
-      'pozycja' => [ '@ref' => 'default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja', '@maxOccurs' => 'unbounded' ]
-    ],
-  ];
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_db/ZALICZKA/ZaliczkaAktywna',// Api_WfsNs::getBaseWfsUri() . '/default_db/Zaliczka'
+			'@derived' => [
+				'default_db/ZALICZKA/Zaliczka'
+			],
+			'@primaryKey' => 'id',
+			'id' => 'xsd:integer',
+			'created' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_CREATE_DATE' ],
+			'worker' => [ '@ref' => 'default_objects/AccessOwner' ],// 'alias_ref:default_objects:AccessOwner'
+			// 'worker' => [ '@ref' => 'Worker' ],
+			'kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
+			'nierozliczona_kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
+			'pozycja' => [ '@ref' => 'default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja', '@maxOccurs' => 'unbounded' ]
+		],
+	];
 
 }

+ 16 - 16
SE/se-lib/Schema/DefaultDb/zaliczka/ZaliczkaAnulowanaStorageAcl.php

@@ -6,21 +6,21 @@ Lib::loadClass('Schema_DefaultDb_zaliczka_ZaliczkaStorageAcl');
 
 class Schema_DefaultDb_zaliczka_ZaliczkaAnulowanaStorageAcl extends Schema_DefaultDb_zaliczka_ZaliczkaStorageAcl {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_db/ZALICZKA/ZaliczkaAnulowana',// Api_WfsNs::getBaseWfsUri() . '/default_db/Zaliczka'
-      '@derived' => [
-        'default_db/ZALICZKA/Zaliczka'
-      ],
-      '@primaryKey' => 'id',
-      'id' => 'xsd:integer',
-      'created' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_CREATE_DATE' ],
-      'worker' => [ '@ref' => 'default_objects/AccessOwner' ],// 'alias_ref:default_objects:AccessOwner'
-      // 'worker' => [ '@ref' => 'Worker' ],
-      'kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
-      'nierozliczona_kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
-      'pozycja' => [ '@ref' => 'default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja', '@maxOccurs' => 'unbounded' ]
-    ],
-  ];
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_db/ZALICZKA/ZaliczkaAnulowana',// Api_WfsNs::getBaseWfsUri() . '/default_db/Zaliczka'
+			'@derived' => [
+				'default_db/ZALICZKA/Zaliczka'
+			],
+			'@primaryKey' => 'id',
+			'id' => 'xsd:integer',
+			'created' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_CREATE_DATE' ],
+			'worker' => [ '@ref' => 'default_objects/AccessOwner' ],// 'alias_ref:default_objects:AccessOwner'
+			// 'worker' => [ '@ref' => 'Worker' ],
+			'kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
+			'nierozliczona_kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
+			'pozycja' => [ '@ref' => 'default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja', '@maxOccurs' => 'unbounded' ]
+		],
+	];
 
 }

+ 16 - 16
SE/se-lib/Schema/DefaultDb/zaliczka/ZaliczkaArchiwalnaStorageAcl.php

@@ -6,21 +6,21 @@ Lib::loadClass('Schema_DefaultDb_zaliczka_ZaliczkaStorageAcl');
 
 class Schema_DefaultDb_zaliczka_ZaliczkaArchiwalnaStorageAcl extends Schema_DefaultDb_zaliczka_ZaliczkaStorageAcl {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_db/ZALICZKA/ZaliczkaArchiwalna',// Api_WfsNs::getBaseWfsUri() . '/default_db/Zaliczka'
-      '@derived' => [
-        'default_db/ZALICZKA/Zaliczka'
-      ],
-      '@primaryKey' => 'id',
-      'id' => 'xsd:integer',
-      'created' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_CREATE_DATE' ],
-      'worker' => [ '@ref' => 'default_objects/AccessOwner' ],// 'alias_ref:default_objects:AccessOwner'
-      // 'worker' => [ '@ref' => 'Worker' ],
-      'kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
-      'nierozliczona_kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
-      'pozycja' => [ '@ref' => 'default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja', '@maxOccurs' => 'unbounded' ]
-    ],
-  ];
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_db/ZALICZKA/ZaliczkaArchiwalna',// Api_WfsNs::getBaseWfsUri() . '/default_db/Zaliczka'
+			'@derived' => [
+				'default_db/ZALICZKA/Zaliczka'
+			],
+			'@primaryKey' => 'id',
+			'id' => 'xsd:integer',
+			'created' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_CREATE_DATE' ],
+			'worker' => [ '@ref' => 'default_objects/AccessOwner' ],// 'alias_ref:default_objects:AccessOwner'
+			// 'worker' => [ '@ref' => 'Worker' ],
+			'kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
+			'nierozliczona_kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
+			'pozycja' => [ '@ref' => 'default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja', '@maxOccurs' => 'unbounded' ]
+		],
+	];
 
 }

+ 418 - 418
SE/se-lib/Schema/DefaultDb/zaliczka/ZaliczkaStorageAcl.php

@@ -6,191 +6,191 @@ Lib::loadClass('DBG');
 
 class Schema_DefaultDb_zaliczka_ZaliczkaStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_db/ZALICZKA/Zaliczka',// Api_WfsNs::getBaseWfsUri() . '/default_db/Zaliczka'
-      '@primaryKey' => 'id',
-      'id' => [ '@type' => 'xsd:integer', '@alias' => 'ID' ],
-      'created' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_CREATE_DATE' ],
-      'worker' => [ '@ref' => 'default_objects/AccessOwner' ],// 'alias_ref:default_objects:AccessOwner'
-      'kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2, '@alias' => 'KWOTA' ],
-      'uwagi' => [ '@type' => 'xsd:string', '@alias' => 'UWAGI' ],
-      'nierozliczona_kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2, '@alias' => 'NIEROZLICZONA_KWOTA' ],
-      'korespondencja' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/ZaliczkaKoresp' ],
-      'pozycja' => [ '@ref' => 'default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja', '@maxOccurs' => 'unbounded' ],
-      'A_STATUS' => [ '@type' => 'xsd:string' ],
-      'L_APPOITMENT_USER' => [ '@type' => 'xsd:string' ],
-      'approvedBy' => [ '@type' => 'xsd:string', '@alias' => 'APPROVED_BY' ],
-    ],
-  ];
-
-  public function getTotal($params = array()) {
-    if (!isset($params['#refFrom'])) {
-      throw new Exception("Missing param #refFrom/primaryKey (id user)");
-    }
-    $idUser = V::get('primaryKey', 0, $params['#refFrom'], 'int');
-    return DB::getPDO()->fetchValue("
-      select count(*) as cnt
-      from ZALICZKA z
-        join ADMIN_USERS u on(z.L_APPOITMENT_USER = u.ADM_ACCOUNT and u.ID = {$idUser})
-    ");
-  }
-
-  public function getItems($params = array()) {
-    // '#refFrom' => [
-    //   'namespace' => 'default_db__x3A__ADMIN_USERS/Worker',
-    //   'primaryKey' => $idUser
-    // ]
-    if (!isset($params['#refFrom'])) {
-      throw new Exception("Missing param #refFrom/primaryKey (id user)");
-    }
-    $idUser = V::get('primaryKey', 0, $params['#refFrom'], 'int');
-
-    return array_map(
-      function ($row) use ($params) {
-        return $this->buildFromSqlRow($row, $params);
-      },
-      DB::getPDO()->fetchAll("
-        select z.*
-        from ZALICZKA z
-          join ADMIN_USERS u on(z.L_APPOITMENT_USER = u.ADM_ACCOUNT and u.ID = {$idUser})
-        order by z.ID DESC
-      ")
-    );
-  }
-
-  public function addItem($itemTodo) {
-    DBG::log(['msg' => '$itemTodo', 'log' => $itemTodo]);
-
-    if (!is_array($itemTodo) || empty($itemTodo['worker'])) throw new Exception("Missing worker");
-    if (empty($itemTodo['worker']['id'])) throw new Exception("Missing worker id");
-    if (empty($itemTodo['kwota'])) throw new Exception("Nie podano kwoty");
-    $itemTodo['kwota'] = floatval($itemTodo['kwota']);
-    if ($itemTodo['kwota'] <= 0) throw new Exception("Podano błędną kwotę");
-
-    $idUser = intval($itemTodo['worker']['id']);
-    if ($idUser <= 0) throw new Exception("Wrong worker id");
-
-    // TODO: use default_objects/AccessOwner -> getItem($idUser)
-    $userLogin = DB::getPDO()->fetchValue("
-      select u.ADM_ACCOUNT
-      from `ADMIN_USERS` u
-      where u.ID = {$idUser}
-    ");
-    if (empty($userLogin)) throw new Exception("User not exists ID={$idUser}");
-    DBG::log(['msg' => '$userLogin', 'log' => $userLogin]);
-
-    $idTransaction = Core_AclHelper::startTransaction('ZALICZKA', $idUser, $userLogin);
-
-    $zaliczkaRefWorker = ACL::getRefTable('default_db/ZALICZKA/Zaliczka', 'worker');
-    $idActiveZaliczka = DB::getPDO()->fetchValue("
-      select MAX(t.ID)
-      from `ZALICZKA` t
-        -- join `ADMIN_USERS` u on(t.L_APPOITMENT_USER = u.ADM_ACCOUNT)
-        left join `{$zaliczkaRefWorker}` ref on(ref.PRIMARY_KEY = t.ID and ref.A_STATUS != 'DELETED')
-        left join `ADMIN_USERS` r on(r.ID = ref.REMOTE_PRIMARY_KEY)
-      where r.ID = {$idUser}
-        and t.A_STATUS in('WAITING', 'NORMAL') -- TODO cache use #INSTANCE table
-    ");
-    DBG::log(['msg' => '$idActiveZaliczka', 'log' => $idActiveZaliczka]);
-
-    $userSaldo = 0;
-    if ($idActiveZaliczka > 0) {
-      $zaliczkaRefPozycja = ACL::getRefTable('default_db/ZALICZKA/Zaliczka', 'pozycja');
-      $userSaldo = DB::getPDO()->fetchValue("
-    		select t.KWOTA + t.NIEROZLICZONA_KWOTA - sum(COALESCE(r.KWOTA, 0))
-    		from `ZALICZKA` t
-    			left join `{$zaliczkaRefPozycja}` ref on(ref.PRIMARY_KEY = t.ID and ref.A_STATUS != 'DELETED')
-    			left join `ZALICZKA_POZYCJA` r on(r.ID = ref.REMOTE_PRIMARY_KEY and (r.A_STATUS is null or r.A_STATUS != 'DELETED'))
-        where t.ID = {$idActiveZaliczka}
-    	");
-    }
-    DBG::log(['msg' => '$userSaldo', 'log' => $userSaldo]);
-
-    $usrLogin = User::getLogin();
-    $sqlUwagi = DB::getPDO()->quote(V::get('uwagi', '', $itemTodo), PDO::PARAM_STR);
-    $sqlApprovedBy = DB::getPDO()->quote(V::get('approvedBy', '', $itemTodo), PDO::PARAM_STR);
-    $execRet = DB::getPDO()->execSql("
-      insert into `ZALICZKA` (A_RECORD_CREATE_AUTHOR, A_RECORD_CREATE_DATE
-          , L_APPOITMENT_USER, NIEROZLICZONA_KWOTA
-          , KWOTA, UWAGI, APPROVED_BY)
-        select '{$usrLogin}' as A_RECORD_CREATE_AUTHOR, NOW() as A_RECORD_CREATE_DATE
-          , u.ADM_ACCOUNT, '{$userSaldo}'
-          , '{$itemTodo['kwota']}', {$sqlUwagi}, {$sqlApprovedBy}
-        from ADMIN_USERS u
-        where u.ID = {$idUser}
-    ");
-    DBG::log(['msg' => '$execRet', 'log' => $execRet]);
-    $id = DB::getPDO()->lastInsertId();
-    DBG::log(['msg' => '$id', 'log' => $id]);
-    if (!$id) throw new Exception("Wystąpiły błędy podczas dodawania Zaliczki do bazy danych");
-
-    DB::getPDO()->execSql("
-      insert into `ZALICZKA__#INSTANCE` (PRIMARY_KEY, INSTANCE_NAME)
-        values({$id}, 'ZaliczkaAktywna')
-      ON DUPLICATE KEY UPDATE INSTANCE_NAME = 'ZaliczkaAktywna'
-    ");
-    foreach (DB::getPDO()->fetchAll("
-      select z.ID as ID_ZALICZKA, i.*
-      from `ZALICZKA` z
-        left join `ZALICZKA__#INSTANCE` i on(i.PRIMARY_KEY = z.ID)
-      where z.ID != {$id}
-        and z.L_APPOITMENT_USER = '{$userLogin}'
-    ") as $instance) {
-      DBG::log(['msg' => 'old $instance', 'log' => $instance]);
-
-      // FIX Instance name
-      foreach (DB::getPDO()->fetchAll("
-        select z.ID as ID_ZALICZKA
-  				, IF(i.PRIMARY_KEY IS NOT NULL, 1, 0) as has_instance
-  				, i.*
-        from `ZALICZKA` z
-          left join `ZALICZKA__#INSTANCE` i on(i.PRIMARY_KEY = z.ID)
-        where z.ID != {$id}
-          and z.L_APPOITMENT_USER = '{$userLogin}'
-      ") as $instance) {
-        DBG::log(['msg' => 'fix instance name $instance', 'log' => $instance]);
-  			if (!$instance['has_instance']) {
-          DB::getPDO()->insert('ZALICZKA__#INSTANCE_HIST', [
-            'PRIMARY_KEY' => $instance['ID_ZALICZKA'],
-            'INSTANCE_NAME' => 'ZaliczkaArchiwalna'
-    			]);
-  				DB::getPDO()->insert('ZALICZKA__#INSTANCE', [
-            'PRIMARY_KEY' => $instance['ID_ZALICZKA'],
-            'INSTANCE_NAME' => 'ZaliczkaArchiwalna'
-  				]);
-  			} else if ('ZaliczkaAktywna' == $instance['INSTANCE_NAME']) {
-          DB::getPDO()->insert('ZALICZKA__#INSTANCE_HIST', [
-            'PRIMARY_KEY' => $instance['ID_ZALICZKA'],
-            'INSTANCE_NAME' => 'ZaliczkaArchiwalna'
-    			]);
-  				DB::getPDO()->execSql("
-  					update `ZALICZKA__#INSTANCE`
-  					set INSTANCE_NAME = 'ZaliczkaArchiwalna'
-  						, A_RECORD_UPDATE_DATE = NOW()
-  					where PRIMARY_KEY = {$instance['ID_ZALICZKA']}
-  				");
-  			}
-      }
-    }
-
-    $this->insertRef('worker', $id, $idUser);// TODO: add to hist table
-
-    $childTableKwota = $this->getChildHistTable('kwota');
-    DB::getPDO()->insert($childTableKwota, [
-      'VALUE' => $itemTodo['kwota'],
-      'A_TRANSACTION_ID' => $idTransaction
-    ]);
-
-    DB::getPDO()->execSql("
-      update ZALICZKA
-      set A_STATUS = 'OFF_HARD'
-      where L_APPOITMENT_USER = '{$userLogin}'
-        and ID < {$id}
-    ");
-
-    // TODO: legacy fill table ZALICZKA_HIST
-    // $itemTodo['A_RECORD_UPDATE_AUTHOR'] = User::getLogin();
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_db/ZALICZKA/Zaliczka',// Api_WfsNs::getBaseWfsUri() . '/default_db/Zaliczka'
+			'@primaryKey' => 'id',
+			'id' => [ '@type' => 'xsd:integer', '@alias' => 'ID' ],
+			'created' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_CREATE_DATE' ],
+			'worker' => [ '@ref' => 'default_objects/AccessOwner' ],// 'alias_ref:default_objects:AccessOwner'
+			'kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2, '@alias' => 'KWOTA' ],
+			'uwagi' => [ '@type' => 'xsd:string', '@alias' => 'UWAGI' ],
+			'nierozliczona_kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2, '@alias' => 'NIEROZLICZONA_KWOTA' ],
+			'korespondencja' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/ZaliczkaKoresp' ],
+			'pozycja' => [ '@ref' => 'default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja', '@maxOccurs' => 'unbounded' ],
+			'A_STATUS' => [ '@type' => 'xsd:string' ],
+			'L_APPOITMENT_USER' => [ '@type' => 'xsd:string' ],
+			'approvedBy' => [ '@type' => 'xsd:string', '@alias' => 'APPROVED_BY' ],
+		],
+	];
+
+	public function getTotal($params = array()) {
+		if (!isset($params['#refFrom'])) {
+			throw new Exception("Missing param #refFrom/primaryKey (id user)");
+		}
+		$idUser = V::get('primaryKey', 0, $params['#refFrom'], 'int');
+		return DB::getPDO()->fetchValue("
+			select count(*) as cnt
+			from ZALICZKA z
+				join ADMIN_USERS u on(z.L_APPOITMENT_USER = u.ADM_ACCOUNT and u.ID = {$idUser})
+		");
+	}
+
+	public function getItems($params = array()) {
+		// '#refFrom' => [
+		//	 'namespace' => 'default_db__x3A__ADMIN_USERS/Worker',
+		//	 'primaryKey' => $idUser
+		// ]
+		if (!isset($params['#refFrom'])) {
+			throw new Exception("Missing param #refFrom/primaryKey (id user)");
+		}
+		$idUser = V::get('primaryKey', 0, $params['#refFrom'], 'int');
+
+		return array_map(
+			function ($row) use ($params) {
+				return $this->buildFromSqlRow($row, $params);
+			},
+			DB::getPDO()->fetchAll("
+				select z.*
+				from ZALICZKA z
+					join ADMIN_USERS u on(z.L_APPOITMENT_USER = u.ADM_ACCOUNT and u.ID = {$idUser})
+				order by z.ID DESC
+			")
+		);
+	}
+
+	public function addItem($itemTodo) {
+		DBG::log(['msg' => '$itemTodo', 'log' => $itemTodo]);
+
+		if (!is_array($itemTodo) || empty($itemTodo['worker'])) throw new Exception("Missing worker");
+		if (empty($itemTodo['worker']['id'])) throw new Exception("Missing worker id");
+		if (empty($itemTodo['kwota'])) throw new Exception("Nie podano kwoty");
+		$itemTodo['kwota'] = floatval($itemTodo['kwota']);
+		if ($itemTodo['kwota'] <= 0) throw new Exception("Podano błędną kwotę");
+
+		$idUser = intval($itemTodo['worker']['id']);
+		if ($idUser <= 0) throw new Exception("Wrong worker id");
+
+		// TODO: use default_objects/AccessOwner -> getItem($idUser)
+		$userLogin = DB::getPDO()->fetchValue("
+			select u.ADM_ACCOUNT
+			from `ADMIN_USERS` u
+			where u.ID = {$idUser}
+		");
+		if (empty($userLogin)) throw new Exception("User not exists ID={$idUser}");
+		DBG::log(['msg' => '$userLogin', 'log' => $userLogin]);
+
+		$idTransaction = Core_AclHelper::startTransaction('ZALICZKA', $idUser, $userLogin);
+
+		$zaliczkaRefWorker = ACL::getRefTable('default_db/ZALICZKA/Zaliczka', 'worker');
+		$idActiveZaliczka = DB::getPDO()->fetchValue("
+			select MAX(t.ID)
+			from `ZALICZKA` t
+				-- join `ADMIN_USERS` u on(t.L_APPOITMENT_USER = u.ADM_ACCOUNT)
+				left join `{$zaliczkaRefWorker}` ref on(ref.PRIMARY_KEY = t.ID and ref.A_STATUS != 'DELETED')
+				left join `ADMIN_USERS` r on(r.ID = ref.REMOTE_PRIMARY_KEY)
+			where r.ID = {$idUser}
+				and t.A_STATUS in('WAITING', 'NORMAL') -- TODO cache use #INSTANCE table
+		");
+		DBG::log(['msg' => '$idActiveZaliczka', 'log' => $idActiveZaliczka]);
+
+		$userSaldo = 0;
+		if ($idActiveZaliczka > 0) {
+			$zaliczkaRefPozycja = ACL::getRefTable('default_db/ZALICZKA/Zaliczka', 'pozycja');
+			$userSaldo = DB::getPDO()->fetchValue("
+				select t.KWOTA + t.NIEROZLICZONA_KWOTA - sum(COALESCE(r.KWOTA, 0))
+				from `ZALICZKA` t
+					left join `{$zaliczkaRefPozycja}` ref on(ref.PRIMARY_KEY = t.ID and ref.A_STATUS != 'DELETED')
+					left join `ZALICZKA_POZYCJA` r on(r.ID = ref.REMOTE_PRIMARY_KEY and (r.A_STATUS is null or r.A_STATUS != 'DELETED'))
+				where t.ID = {$idActiveZaliczka}
+			");
+		}
+		DBG::log(['msg' => '$userSaldo', 'log' => $userSaldo]);
+
+		$usrLogin = User::getLogin();
+		$sqlUwagi = DB::getPDO()->quote(V::get('uwagi', '', $itemTodo), PDO::PARAM_STR);
+		$sqlApprovedBy = DB::getPDO()->quote(V::get('approvedBy', '', $itemTodo), PDO::PARAM_STR);
+		$execRet = DB::getPDO()->execSql("
+			insert into `ZALICZKA` (A_RECORD_CREATE_AUTHOR, A_RECORD_CREATE_DATE
+					, L_APPOITMENT_USER, NIEROZLICZONA_KWOTA
+					, KWOTA, UWAGI, APPROVED_BY)
+				select '{$usrLogin}' as A_RECORD_CREATE_AUTHOR, NOW() as A_RECORD_CREATE_DATE
+					, u.ADM_ACCOUNT, '{$userSaldo}'
+					, '{$itemTodo['kwota']}', {$sqlUwagi}, {$sqlApprovedBy}
+				from ADMIN_USERS u
+				where u.ID = {$idUser}
+		");
+		DBG::log(['msg' => '$execRet', 'log' => $execRet]);
+		$id = DB::getPDO()->lastInsertId();
+		DBG::log(['msg' => '$id', 'log' => $id]);
+		if (!$id) throw new Exception("Wystąpiły błędy podczas dodawania Zaliczki do bazy danych");
+
+		DB::getPDO()->execSql("
+			insert into `ZALICZKA__#INSTANCE` (PRIMARY_KEY, INSTANCE_NAME)
+				values({$id}, 'ZaliczkaAktywna')
+			ON DUPLICATE KEY UPDATE INSTANCE_NAME = 'ZaliczkaAktywna'
+		");
+		foreach (DB::getPDO()->fetchAll("
+			select z.ID as ID_ZALICZKA, i.*
+			from `ZALICZKA` z
+				left join `ZALICZKA__#INSTANCE` i on(i.PRIMARY_KEY = z.ID)
+			where z.ID != {$id}
+				and z.L_APPOITMENT_USER = '{$userLogin}'
+		") as $instance) {
+			DBG::log(['msg' => 'old $instance', 'log' => $instance]);
+
+			// FIX Instance name
+			foreach (DB::getPDO()->fetchAll("
+				select z.ID as ID_ZALICZKA
+					, IF(i.PRIMARY_KEY IS NOT NULL, 1, 0) as has_instance
+					, i.*
+				from `ZALICZKA` z
+					left join `ZALICZKA__#INSTANCE` i on(i.PRIMARY_KEY = z.ID)
+				where z.ID != {$id}
+					and z.L_APPOITMENT_USER = '{$userLogin}'
+			") as $instance) {
+				DBG::log(['msg' => 'fix instance name $instance', 'log' => $instance]);
+				if (!$instance['has_instance']) {
+					DB::getPDO()->insert('ZALICZKA__#INSTANCE_HIST', [
+						'PRIMARY_KEY' => $instance['ID_ZALICZKA'],
+						'INSTANCE_NAME' => 'ZaliczkaArchiwalna'
+					]);
+					DB::getPDO()->insert('ZALICZKA__#INSTANCE', [
+						'PRIMARY_KEY' => $instance['ID_ZALICZKA'],
+						'INSTANCE_NAME' => 'ZaliczkaArchiwalna'
+					]);
+				} else if ('ZaliczkaAktywna' == $instance['INSTANCE_NAME']) {
+					DB::getPDO()->insert('ZALICZKA__#INSTANCE_HIST', [
+						'PRIMARY_KEY' => $instance['ID_ZALICZKA'],
+						'INSTANCE_NAME' => 'ZaliczkaArchiwalna'
+					]);
+					DB::getPDO()->execSql("
+						update `ZALICZKA__#INSTANCE`
+						set INSTANCE_NAME = 'ZaliczkaArchiwalna'
+							, A_RECORD_UPDATE_DATE = NOW()
+						where PRIMARY_KEY = {$instance['ID_ZALICZKA']}
+					");
+				}
+			}
+		}
+
+		$this->insertRef('worker', $id, $idUser);// TODO: add to hist table
+
+		$childTableKwota = $this->getChildHistTable('kwota');
+		DB::getPDO()->insert($childTableKwota, [
+			'VALUE' => $itemTodo['kwota'],
+			'A_TRANSACTION_ID' => $idTransaction
+		]);
+
+		DB::getPDO()->execSql("
+			update ZALICZKA
+			set A_STATUS = 'OFF_HARD'
+			where L_APPOITMENT_USER = '{$userLogin}'
+				and ID < {$id}
+		");
+
+		// TODO: legacy fill table ZALICZKA_HIST
+		// $itemTodo['A_RECORD_UPDATE_AUTHOR'] = User::getLogin();
 		// $itemTodo['A_RECORD_UPDATE_DATE'] = "NOW()";
 		// $affected = DB::getPDO()->update($rootTableName, $pkField, $pk, $itemTodo);
 		// if ($affected && $histTableName) {
@@ -198,24 +198,24 @@ class Schema_DefaultDb_zaliczka_ZaliczkaStorageAcl extends Core_AclSimpleSchemaB
 		// 	$itemTodo['A_RECORD_CREATE_AUTHOR'] = User::getLogin();
 		// 	$itemTodo['A_RECORD_CREATE_DATE'] = "NOW()";
 
-    DB::getPDO()->execSql("
-      insert into `ZALICZKA_HIST` (ID_USERS2, L_APPOITMENT_USER, NIEROZLICZONA_KWOTA, KWOTA
-        , A_RECORD_CREATE_AUTHOR, A_RECORD_CREATE_DATE)
-        select z.ID as ID_USERS2, z.L_APPOITMENT_USER, z.NIEROZLICZONA_KWOTA, z.KWOTA
-          , z.A_RECORD_CREATE_AUTHOR, z.A_RECORD_CREATE_DATE
-        from ZALICZKA z
-        where z.ID = {$id}
-    ");
-    return $id;
-  }
-
-  public function updateItem($itemPatch) {
-    DBG::log(['msg' => '$itemPatch', $itemPatch]);
-    $pkField = $this->getPrimaryKeyField();
-    if (!array_key_exists($pkField, $itemPatch)) throw new Exception("Missing primary key");
-    $pk = (int)$itemPatch[$pkField];
-    if ($pk <= 0) throw new Exception("Wrong primary key format");
-    $oldItem = $this->getItem($pk, [
+		DB::getPDO()->execSql("
+			insert into `ZALICZKA_HIST` (ID_USERS2, L_APPOITMENT_USER, NIEROZLICZONA_KWOTA, KWOTA
+				, A_RECORD_CREATE_AUTHOR, A_RECORD_CREATE_DATE)
+				select z.ID as ID_USERS2, z.L_APPOITMENT_USER, z.NIEROZLICZONA_KWOTA, z.KWOTA
+					, z.A_RECORD_CREATE_AUTHOR, z.A_RECORD_CREATE_DATE
+				from ZALICZKA z
+				where z.ID = {$id}
+		");
+		return $id;
+	}
+
+	public function updateItem($itemPatch) {
+		DBG::log(['msg' => '$itemPatch', $itemPatch]);
+		$pkField = $this->getPrimaryKeyField();
+		if (!array_key_exists($pkField, $itemPatch)) throw new Exception("Missing primary key");
+		$pk = (int)$itemPatch[$pkField];
+		if ($pk <= 0) throw new Exception("Wrong primary key format");
+		$oldItem = $this->getItem($pk, [
 			'cols' => [
 				'id',
 				'kwota',
@@ -225,148 +225,148 @@ class Schema_DefaultDb_zaliczka_ZaliczkaStorageAcl extends Core_AclSimpleSchemaB
 				// 'worker',
 			]
 		]);
-    DBG::log(['msg' => '$oldItem', $oldItem]);
-
-    // pozycja
-    $pozAcl = ACL::getAclByNamespace('default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja');
-    $pozPkField = $pozAcl->getPrimaryKeyField();
-    if (empty($oldItem['pozycja'])) {
-      DBG::log("empty \$oldItem['pozycja']");
-      if (!empty($itemPatch['pozycja'])) {
-        foreach ($itemPatch['pozycja'] as $pozTodo) {
-          if ($pozTodo[ $pozPkField ] !== -1) throw new Exception("BUG ZaliczkaPozycja id not equal -1");
-          unset($pozTodo[ $pozPkField ]);
-          $pkPoz = $pozAcl->addItem($pozTodo);
-          DBG::log(['msg'=> '$pkPoz', $pkPoz]);
-          $this->insertRef('pozycja', $pk, $pkPoz);
-        }
-      }
-    } else {
-      DBG::log("not empty \$oldItem['pozycja'] " . ((!empty($itemPatch['pozycja'])) ? "not empty" : "empty") . " patch pozycja");
-      $pozToAdd = array();
-      $pozToUpdate = array();
-      $pozToRemove = array();
-      if (!empty($itemPatch['pozycja'])) {
-        foreach ($itemPatch['pozycja'] as $pozTodo) {
-          if ($pozTodo[ $pozPkField ] == -1) {
-            unset($pozTodo[ $pozPkField ]);
-            $pozToAdd[] = $pozTodo;
-          } else {
-            $pozToUpdate[ $pozTodo[ $pozPkField ] ] = $pozTodo;
-          }
-        }
-      }
-      foreach ($oldItem['pozycja'] as $pozOld) {
-        if ($pozOld[ $pozPkField ] > 0 && !array_key_exists($pozOld[ $pozPkField ], $pozToUpdate)) {
-          $pozToRemove[] = $pozOld[ $pozPkField ];
-        }
-      }
-
-      DBG::log(['msg'=> '$pozToAdd', $pozToAdd]);
-      DBG::log(['msg'=> '$pozToUpdate', $pozToUpdate]);
-      DBG::log(['msg'=> '$pozToRemove', $pozToRemove]);
-
-      foreach ($pozToAdd as $pozTodo) {
-        $pkPoz = $pozAcl->addItem($pozTodo);
-        DBG::log(['msg'=> '$pkPoz', $pkPoz]);
-        $this->insertRef('pozycja', $pk, $pkPoz);
-      }
-      foreach ($pozToRemove as $idPoz) {
-        // $rmPozItem = [];
-        // $rmPozItem[$pozPkField] = $idPoz;
-        // $rmPozItem['A_STATUS'] = 'DELETED';
-        // $pozAcl->updateItem($rmPozItem);// TODO: update instance and A_STATUS (cache)
-        $this->removeRef('pozycja', $pk, $idPoz);
-      }
-      foreach ($pozToUpdate as $pozTodo) {
-        $pozAcl->updateItem($pozTodo);
-      }
-    }
-
-    // korespondencja
-    if (empty($oldItem['korespondencja'])) {
-      DBG::log("empty \$oldItem['korespondencja']");
-      if (!empty($itemPatch['korespondencja'])) {
-        if (empty($itemPatch['korespondencja'][0]['id'])) throw new Exception("BUG: Missing Koresp id");
-        $pkKoresp = $itemPatch['korespondencja'][0]['id'];
-        $this->insertRef('korespondencja', $pk, $pkKoresp);
-      }
-    } else {
-      DBG::log("not empty \$oldItem['korespondencja'] " . ((!empty($itemPatch['korespondencja'])) ? "not empty" : "empty") . " patch koresp");
-      // if (id != id) => update : clearRefs, insertRef
-      if (empty($oldItem['korespondencja'][0]['id'])) throw new Exception("BUG: Missing Koresp id in current object");
-
-      if (!empty($itemPatch['korespondencja'])) {
-        if (empty($itemPatch['korespondencja'][0]['id'])) throw new Exception("BUG: Missing Koresp id");
-        $pkOldKoresp = $oldItem['korespondencja'][0]['id'];
-        $pkKoresp = $itemPatch['korespondencja'][0]['id'];
-        DBG::log("\$pkOldKoresp({$pkOldKoresp}), \$pkKoresp({$pkKoresp})");
-        if ($pkOldKoresp != $pkKoresp) {
-          $this->cleanRefs('korespondencja', $pk);
-          $this->insertRef('korespondencja', $pk, $pkKoresp);
-        }
-      } else {
-        DBG::log("cleanRefs \$pk({$pk})");
-        $this->cleanRefs('korespondencja', $pk);
-      }
-    }
+		DBG::log(['msg' => '$oldItem', $oldItem]);
+
+		// pozycja
+		$pozAcl = ACL::getAclByNamespace('default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja');
+		$pozPkField = $pozAcl->getPrimaryKeyField();
+		if (empty($oldItem['pozycja'])) {
+			DBG::log("empty \$oldItem['pozycja']");
+			if (!empty($itemPatch['pozycja'])) {
+				foreach ($itemPatch['pozycja'] as $pozTodo) {
+					if ($pozTodo[ $pozPkField ] !== -1) throw new Exception("BUG ZaliczkaPozycja id not equal -1");
+					unset($pozTodo[ $pozPkField ]);
+					$pkPoz = $pozAcl->addItem($pozTodo);
+					DBG::log(['msg'=> '$pkPoz', $pkPoz]);
+					$this->insertRef('pozycja', $pk, $pkPoz);
+				}
+			}
+		} else {
+			DBG::log("not empty \$oldItem['pozycja'] " . ((!empty($itemPatch['pozycja'])) ? "not empty" : "empty") . " patch pozycja");
+			$pozToAdd = array();
+			$pozToUpdate = array();
+			$pozToRemove = array();
+			if (!empty($itemPatch['pozycja'])) {
+				foreach ($itemPatch['pozycja'] as $pozTodo) {
+					if ($pozTodo[ $pozPkField ] == -1) {
+						unset($pozTodo[ $pozPkField ]);
+						$pozToAdd[] = $pozTodo;
+					} else {
+						$pozToUpdate[ $pozTodo[ $pozPkField ] ] = $pozTodo;
+					}
+				}
+			}
+			foreach ($oldItem['pozycja'] as $pozOld) {
+				if ($pozOld[ $pozPkField ] > 0 && !array_key_exists($pozOld[ $pozPkField ], $pozToUpdate)) {
+					$pozToRemove[] = $pozOld[ $pozPkField ];
+				}
+			}
+
+			DBG::log(['msg'=> '$pozToAdd', $pozToAdd]);
+			DBG::log(['msg'=> '$pozToUpdate', $pozToUpdate]);
+			DBG::log(['msg'=> '$pozToRemove', $pozToRemove]);
+
+			foreach ($pozToAdd as $pozTodo) {
+				$pkPoz = $pozAcl->addItem($pozTodo);
+				DBG::log(['msg'=> '$pkPoz', $pkPoz]);
+				$this->insertRef('pozycja', $pk, $pkPoz);
+			}
+			foreach ($pozToRemove as $idPoz) {
+				// $rmPozItem = [];
+				// $rmPozItem[$pozPkField] = $idPoz;
+				// $rmPozItem['A_STATUS'] = 'DELETED';
+				// $pozAcl->updateItem($rmPozItem);// TODO: update instance and A_STATUS (cache)
+				$this->removeRef('pozycja', $pk, $idPoz);
+			}
+			foreach ($pozToUpdate as $pozTodo) {
+				$pozAcl->updateItem($pozTodo);
+			}
+		}
+
+		// korespondencja
+		if (empty($oldItem['korespondencja'])) {
+			DBG::log("empty \$oldItem['korespondencja']");
+			if (!empty($itemPatch['korespondencja'])) {
+				if (empty($itemPatch['korespondencja'][0]['id'])) throw new Exception("BUG: Missing Koresp id");
+				$pkKoresp = $itemPatch['korespondencja'][0]['id'];
+				$this->insertRef('korespondencja', $pk, $pkKoresp);
+			}
+		} else {
+			DBG::log("not empty \$oldItem['korespondencja'] " . ((!empty($itemPatch['korespondencja'])) ? "not empty" : "empty") . " patch koresp");
+			// if (id != id) => update : clearRefs, insertRef
+			if (empty($oldItem['korespondencja'][0]['id'])) throw new Exception("BUG: Missing Koresp id in current object");
+
+			if (!empty($itemPatch['korespondencja'])) {
+				if (empty($itemPatch['korespondencja'][0]['id'])) throw new Exception("BUG: Missing Koresp id");
+				$pkOldKoresp = $oldItem['korespondencja'][0]['id'];
+				$pkKoresp = $itemPatch['korespondencja'][0]['id'];
+				DBG::log("\$pkOldKoresp({$pkOldKoresp}), \$pkKoresp({$pkKoresp})");
+				if ($pkOldKoresp != $pkKoresp) {
+					$this->cleanRefs('korespondencja', $pk);
+					$this->insertRef('korespondencja', $pk, $pkKoresp);
+				}
+			} else {
+				DBG::log("cleanRefs \$pk({$pk})");
+				$this->cleanRefs('korespondencja', $pk);
+			}
+		}
 
 /* { "updates": {
-        "@instance": "ZaliczkaAktywna",
-        "id": "8",
-        "created": "2017-01-27 11:10:59",
-        "worker": [{ "id": "1", "login": "magdalena.cichosz", "name": "Magdalena Cichosz" }],
-        "kwota": "0.01",
-        "nierozliczona_kwota": "300.02",
-        "pozycja": [{
-            "id": -1,
-            "nr_faktury": "fv 2017/1/1",
-            "kwota": 100,
-            "vat": 23,
-            "kwota_netto": 0,
-            "kategoria_kosztu": "BUDOWA: Usługi obce"
-        }],
-        "korespondencja": {
-            "id": "6013",
-            "title": "faktura Vat (MULTI-TAB) [6013]",
-            "kategoriaKosztu": "do uzgodnienia",
-            "projekt": { "id": "64", "nrBudowy": "20/2016" }
-        }
-    }
+				"@instance": "ZaliczkaAktywna",
+				"id": "8",
+				"created": "2017-01-27 11:10:59",
+				"worker": [{ "id": "1", "login": "magdalena.cichosz", "name": "Magdalena Cichosz" }],
+				"kwota": "0.01",
+				"nierozliczona_kwota": "300.02",
+				"pozycja": [{
+						"id": -1,
+						"nr_faktury": "fv 2017/1/1",
+						"kwota": 100,
+						"vat": 23,
+						"kwota_netto": 0,
+						"kategoria_kosztu": "BUDOWA: Usługi obce"
+				}],
+				"korespondencja": {
+						"id": "6013",
+						"title": "faktura Vat (MULTI-TAB) [6013]",
+						"kategoriaKosztu": "do uzgodnienia",
+						"projekt": { "id": "64", "nrBudowy": "20/2016" }
+				}
+		}
 } */
 
-    $patch = [];
-    // $itemPatch['kwota'] = str_replace(',', '.', $itemPatch['kwota']);
-    // if ($itemPatch['kwota'] != $oldItem['kwota']) $patch['kwota'] = $itemPatch['kwota'];
-
-    // TODO: diff $itemPatch['pozycja'] != $oldItem['pozycja']
-    if (!empty($patch)) {
-      // if (array_key_exists('kwota', $patch)) {
-      //   DB::getPDO()->update('ZALICZKA', 'ID', $pk, [ 'kwota' => $patch['kwota'] ]);
-      // }
-    }
-  }
-
-  public function getItem($primaryKey, $params = []) {
-    $zaliczkaRaw = DB::getPDO()->fetchAll("
-      select t.*
-      from `ZALICZKA` t
-      where t.ID = {$primaryKey}
-    ");
-    $zaliczkaRaw = (!empty($zaliczkaRaw)) ? reset($zaliczkaRaw) : null;
-    // DBG::nicePrint($zaliczkaRaw, '$zaliczkaRaw');
-    if (!$zaliczkaRaw) return null;
-    return $this->buildFromSqlRow($zaliczkaRaw, $params);
-  }
-
-  public function reinstall() {
-    // TODO: mv to Core_AclSimpleSchemaBase and reainstall by _simpleSchema - read current data from `information_schema`
+		$patch = [];
+		// $itemPatch['kwota'] = str_replace(',', '.', $itemPatch['kwota']);
+		// if ($itemPatch['kwota'] != $oldItem['kwota']) $patch['kwota'] = $itemPatch['kwota'];
+
+		// TODO: diff $itemPatch['pozycja'] != $oldItem['pozycja']
+		if (!empty($patch)) {
+			// if (array_key_exists('kwota', $patch)) {
+			//	 DB::getPDO()->update('ZALICZKA', 'ID', $pk, [ 'kwota' => $patch['kwota'] ]);
+			// }
+		}
+	}
+
+	public function getItem($primaryKey, $params = []) {
+		$zaliczkaRaw = DB::getPDO()->fetchAll("
+			select t.*
+			from `ZALICZKA` t
+			where t.ID = {$primaryKey}
+		");
+		$zaliczkaRaw = (!empty($zaliczkaRaw)) ? reset($zaliczkaRaw) : null;
+		// DBG::nicePrint($zaliczkaRaw, '$zaliczkaRaw');
+		if (!$zaliczkaRaw) return null;
+		return $this->buildFromSqlRow($zaliczkaRaw, $params);
+	}
+
+	public function reinstall() {
+		// TODO: mv to Core_AclSimpleSchemaBase and reainstall by _simpleSchema - read current data from `information_schema`
 		DB::getPDO()->execSql("
 			CREATE TABLE IF NOT EXISTS `ZALICZKA` (
 				`ID` int(11) NOT NULL AUTO_INCREMENT,
-				`A_RECORD_CREATE_DATE` datetime  DEFAULT NULL,
-				`A_RECORD_CREATE_AUTHOR` varchar(20)  DEFAULT NULL,
-				`A_RECORD_UPDATE_DATE` datetime  DEFAULT NULL,
+				`A_RECORD_CREATE_DATE` datetime	DEFAULT NULL,
+				`A_RECORD_CREATE_AUTHOR` varchar(20)	DEFAULT NULL,
+				`A_RECORD_UPDATE_DATE` datetime	DEFAULT NULL,
 				`A_RECORD_UPDATE_AUTHOR` varchar(20) NOT NULL DEFAULT '',
 				`A_STATUS` enum('WAITING','NORMAL','MONITOR','WARNING','OFF_SOFT','OFF_HARD','DELETED') DEFAULT 'WAITING',
 				`A_ADM_COMPANY` varchar(100) NOT NULL DEFAULT '',
@@ -375,9 +375,9 @@ class Schema_DefaultDb_zaliczka_ZaliczkaStorageAcl extends Core_AclSimpleSchemaB
 				`KWOTA` decimal(16,2) NOT NULL DEFAULT 0,
 				`NIEROZLICZONA_KWOTA` decimal(16,2) NOT NULL DEFAULT 0,
 				`UWAGI` varchar(255) NOT NULL DEFAULT '',
-        `PAYMENT_METHOD` enum('', 'wypłacono gotówka', 'wypłacono przelew karta', 'wypłacono przelew konto') NOT NULL DEFAULT '',
-        `DOKUMENTY` enum('', 'TAK', 'NIE') NOT NULL DEFAULT '',
-        `APPROVED_BY` varchar(255) NOT NULL DEFAULT '',
+				`PAYMENT_METHOD` enum('', 'wypłacono gotówka', 'wypłacono przelew karta', 'wypłacono przelew konto') NOT NULL DEFAULT '',
+				`DOKUMENTY` enum('', 'TAK', 'NIE') NOT NULL DEFAULT '',
+				`APPROVED_BY` varchar(255) NOT NULL DEFAULT '',
 				PRIMARY KEY (`ID`)
 			) ENGINE=MyISAM DEFAULT CHARSET=latin2;
 		");
@@ -395,30 +395,30 @@ class Schema_DefaultDb_zaliczka_ZaliczkaStorageAcl extends Core_AclSimpleSchemaB
 				`L_APPOITMENT_USER` varchar(100) NOT NULL DEFAULT 'N/S;',
 				`KWOTA` varchar(16) NOT NULL DEFAULT 'N/S;',
 				`NIEROZLICZONA_KWOTA` varchar(16) NOT NULL DEFAULT 'N/S;',
-        `UWAGI` varchar(255) NOT NULL DEFAULT 'N/S;',
-        `PAYMENT_METHOD` varchar(255) NOT NULL DEFAULT 'N/S;',
-        `DOKUMENTY` varchar(255) NOT NULL DEFAULT 'N/S;',
-        `APPROVED_BY` varchar(255) NOT NULL DEFAULT 'N/S;',
+				`UWAGI` varchar(255) NOT NULL DEFAULT 'N/S;',
+				`PAYMENT_METHOD` varchar(255) NOT NULL DEFAULT 'N/S;',
+				`DOKUMENTY` varchar(255) NOT NULL DEFAULT 'N/S;',
+				`APPROVED_BY` varchar(255) NOT NULL DEFAULT 'N/S;',
 				PRIMARY KEY (`ID`),
-			  KEY `ID_USERS2` (`ID_USERS2`)
-			) ENGINE=MyISAM  DEFAULT CHARSET=latin2;
+				KEY `ID_USERS2` (`ID_USERS2`)
+			) ENGINE=MyISAM	DEFAULT CHARSET=latin2;
 		");
 		DB::getPDO()->execSql("
 			CREATE TABLE IF NOT EXISTS `ZALICZKA_POZYCJA` (
 				`ID` int(11) NOT NULL AUTO_INCREMENT,
-				`A_RECORD_CREATE_DATE` datetime  DEFAULT NULL,
-				`A_RECORD_CREATE_AUTHOR` varchar(20)  DEFAULT NULL,
-				`A_RECORD_UPDATE_DATE` datetime  DEFAULT NULL,
+				`A_RECORD_CREATE_DATE` datetime	DEFAULT NULL,
+				`A_RECORD_CREATE_AUTHOR` varchar(20)	DEFAULT NULL,
+				`A_RECORD_UPDATE_DATE` datetime	DEFAULT NULL,
 				`A_RECORD_UPDATE_AUTHOR` varchar(20) NOT NULL DEFAULT '',
 				`A_STATUS` enum('WAITING','NORMAL','MONITOR','WARNING','OFF_SOFT','OFF_HARD','DELETED') DEFAULT 'WAITING',
 				`A_ADM_COMPANY` varchar(100) NOT NULL DEFAULT '',
 				`A_CLASSIFIED` varchar(100) NOT NULL DEFAULT '',
 				`L_APPOITMENT_USER` varchar(100) NOT NULL DEFAULT '',
-        `nr_faktury` varchar(255) NOT NULL DEFAULT '',
+				`nr_faktury` varchar(255) NOT NULL DEFAULT '',
 				`kwota` decimal(16,2) NOT NULL DEFAULT 0,
 				`vat` int(11) NOT NULL DEFAULT 23,
 				`kwota_netto` decimal(16,2) NOT NULL DEFAULT 0,
-        `kategoria_kosztu` varchar(255) NOT NULL DEFAULT '',
+				`kategoria_kosztu` varchar(255) NOT NULL DEFAULT '',
 				PRIMARY KEY (`ID`)
 			) ENGINE=MyISAM DEFAULT CHARSET=latin2;
 		");
@@ -439,75 +439,75 @@ class Schema_DefaultDb_zaliczka_ZaliczkaStorageAcl extends Core_AclSimpleSchemaB
 				`kwota` varchar(16) NOT NULL DEFAULT 'N/S;',
 				`vat` varchar(5) NOT NULL DEFAULT 'N/S;',
 				`kwota_netto` varchar(16) NOT NULL DEFAULT 'N/S;',
-        `kategoria_kosztu` varchar(255) NOT NULL DEFAULT 'N/S;',
+				`kategoria_kosztu` varchar(255) NOT NULL DEFAULT 'N/S;',
 				PRIMARY KEY (`ID`),
-			  KEY `ID_USERS2` (`ID_USERS2`)
-			) ENGINE=MyISAM  DEFAULT CHARSET=latin2;
+				KEY `ID_USERS2` (`ID_USERS2`)
+			) ENGINE=MyISAM	DEFAULT CHARSET=latin2;
 		");
 
-    echo UI::h('div', [ 'class' => "container", 'style' => "background:#ffe5b6; margin-top:6px" ], "<p style=\"margin:0; padding:6px\">Upgrade schema</p>");
-    UI::startContainer([ 'style' => "max-height:200px; overflow-y:scroll; border:1px solid #ffe5b6" ]);
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA` ADD `nr_faktury` varchar(255) NOT NULL DEFAULT '' ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA` ADD `vat` int(11) NOT NULL DEFAULT 23 ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA` ADD `kwota_netto` decimal(16,2) NOT NULL DEFAULT 0 ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA` ADD `kategoria_kosztu` varchar(255) NOT NULL DEFAULT '' ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA_HIST` ADD `nr_faktury` varchar(255) NOT NULL DEFAULT 'N/S;' ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA_HIST` ADD `vat` varchar(5) NOT NULL DEFAULT 'N/S;' ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA_HIST` ADD `kwota_netto` varchar(16) NOT NULL DEFAULT 'N/S;' ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA_HIST` ADD `kategoria_kosztu` varchar(255) NOT NULL DEFAULT 'N/S;' ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    UI::endContainer();
-    UI::startContainer([ 'style' => "max-height:200px; overflow-y:scroll; border:1px solid #ffe5b6" ]);
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA` ADD `UWAGI` varchar(255) NOT NULL DEFAULT '' ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_HIST` ADD `UWAGI` varchar(255) NOT NULL DEFAULT 'N/S;' ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA` ADD `PAYMENT_METHOD` enum('', 'wypłacono gotówka', 'wypłacono przelew karta', 'wypłacono przelew konto') NOT NULL DEFAULT '' ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_HIST` ADD `PAYMENT_METHOD` varchar(255) NOT NULL DEFAULT 'N/S;' ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA` ADD `APPROVED_BY` varchar(255) NOT NULL DEFAULT '' ");
-    } catch (Exception $e) { DBG::log($e); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_HIST` ADD `APPROVED_BY` varchar(255) NOT NULL DEFAULT 'N/S;' ");
-    } catch (Exception $e) { DBG::log($e); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA` ADD `DOKUMENTY` enum('', 'TAK', 'NIE') NOT NULL DEFAULT '' ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_HIST` ADD `DOKUMENTY` varchar(255) NOT NULL DEFAULT 'N/S;' ");
-    } catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
-    UI::endContainer();
-
-    ACL::getRefTable('default_db/ZALICZKA/Zaliczka', 'worker');
-    ACL::getRefTable('default_db/ZALICZKA/Zaliczka', 'pozycja');
-    ACL::getRefTable('default_db/ZALICZKA/Zaliczka', 'korespondencja');
-    // ACL::getRefTable('default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja', 'projekt');
-    // ACL::getRefTable('default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja', 'korespondencja');
-
-    Core_AclHelper::getInstanceTable('ZALICZKA');// `ZALICZKA__#INSTANCE`
-    // TODO: ZaliczkaOczekujaca   A_STATUS = WAITING  -- dodane przez pracownika
-    // TODO: ZaliczkaAktywna      A_STATUS = NORMAL   -- zakceptowane / wyplacone przez ...
-      // TODO: pole na dane wypłacającego zaliczkę
-      // TODO: dopiero teraz wyliczyć saldo / nierozliczona_kwota? Saldo pokazywać zawsze, aktualizować po akceptacji (Oczekujaca --> Aktywna)
-    // TODO: ZaliczkaArchiwalna   A_STATUS = OFF_HARD -- poprzednie zaliczki
-    // TODO: ZaliczkaUsunieta     A_STATUS = DELETED  -- usunieta przez workera lub anulowana przez osobę uprawnioną
-
-    Core_AclHelper::getTransactionTable('ZALICZKA');// `ZALICZKA__#TRANSACTION`
-    Core_AclHelper::getTransactionTable('ZALICZKA_POZYCJA');// `ZALICZKA_POZYCJA__#TRANSACTION`
-
-    echo UI::h('div', [ 'class' => "container", 'style' => "background:#ffe5b6; margin-top:6px" ], "<p style=\"margin:0; padding:6px\">create ChildHistTable</p>");
-    UI::startContainer([ 'style' => "max-height:200px; overflow-y:scroll; border:1px solid #ffe5b6" ]);
-    foreach ($this->_simpleSchema['root'] as $childName => $schema) {
-      if ('@' == substr($childName, 0, 1)) continue;
-      $this->getChildHistTable($childName);
-      DBG::nicePrint($schema, '$childName('.$childName.')');// TODO: DBG
-    }
-    UI::endContainer();
+		echo UI::h('div', [ 'class' => "container", 'style' => "background:#ffe5b6; margin-top:6px" ], "<p style=\"margin:0; padding:6px\">Upgrade schema</p>");
+		UI::startContainer([ 'style' => "max-height:200px; overflow-y:scroll; border:1px solid #ffe5b6" ]);
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA` ADD `nr_faktury` varchar(255) NOT NULL DEFAULT '' ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA` ADD `vat` int(11) NOT NULL DEFAULT 23 ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA` ADD `kwota_netto` decimal(16,2) NOT NULL DEFAULT 0 ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA` ADD `kategoria_kosztu` varchar(255) NOT NULL DEFAULT '' ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA_HIST` ADD `nr_faktury` varchar(255) NOT NULL DEFAULT 'N/S;' ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA_HIST` ADD `vat` varchar(5) NOT NULL DEFAULT 'N/S;' ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA_HIST` ADD `kwota_netto` varchar(16) NOT NULL DEFAULT 'N/S;' ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_POZYCJA_HIST` ADD `kategoria_kosztu` varchar(255) NOT NULL DEFAULT 'N/S;' ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		UI::endContainer();
+		UI::startContainer([ 'style' => "max-height:200px; overflow-y:scroll; border:1px solid #ffe5b6" ]);
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA` ADD `UWAGI` varchar(255) NOT NULL DEFAULT '' ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_HIST` ADD `UWAGI` varchar(255) NOT NULL DEFAULT 'N/S;' ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA` ADD `PAYMENT_METHOD` enum('', 'wypłacono gotówka', 'wypłacono przelew karta', 'wypłacono przelew konto') NOT NULL DEFAULT '' ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_HIST` ADD `PAYMENT_METHOD` varchar(255) NOT NULL DEFAULT 'N/S;' ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA` ADD `APPROVED_BY` varchar(255) NOT NULL DEFAULT '' ");
+		} catch (Exception $e) { DBG::log($e); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_HIST` ADD `APPROVED_BY` varchar(255) NOT NULL DEFAULT 'N/S;' ");
+		} catch (Exception $e) { DBG::log($e); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA` ADD `DOKUMENTY` enum('', 'TAK', 'NIE') NOT NULL DEFAULT '' ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_HIST` ADD `DOKUMENTY` varchar(255) NOT NULL DEFAULT 'N/S;' ");
+		} catch (Exception $e) { UI::alert('warning', $e->getMessage()); }
+		UI::endContainer();
+
+		ACL::getRefTable('default_db/ZALICZKA/Zaliczka', 'worker');
+		ACL::getRefTable('default_db/ZALICZKA/Zaliczka', 'pozycja');
+		ACL::getRefTable('default_db/ZALICZKA/Zaliczka', 'korespondencja');
+		// ACL::getRefTable('default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja', 'projekt');
+		// ACL::getRefTable('default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja', 'korespondencja');
+
+		Core_AclHelper::getInstanceTable('ZALICZKA');// `ZALICZKA__#INSTANCE`
+		// TODO: ZaliczkaOczekujaca	 A_STATUS = WAITING	-- dodane przez pracownika
+		// TODO: ZaliczkaAktywna			A_STATUS = NORMAL	 -- zakceptowane / wyplacone przez ...
+			// TODO: pole na dane wypłacającego zaliczkę
+			// TODO: dopiero teraz wyliczyć saldo / nierozliczona_kwota? Saldo pokazywać zawsze, aktualizować po akceptacji (Oczekujaca --> Aktywna)
+		// TODO: ZaliczkaArchiwalna	 A_STATUS = OFF_HARD -- poprzednie zaliczki
+		// TODO: ZaliczkaUsunieta		 A_STATUS = DELETED	-- usunieta przez workera lub anulowana przez osobę uprawnioną
+
+		Core_AclHelper::getTransactionTable('ZALICZKA');// `ZALICZKA__#TRANSACTION`
+		Core_AclHelper::getTransactionTable('ZALICZKA_POZYCJA');// `ZALICZKA_POZYCJA__#TRANSACTION`
+
+		echo UI::h('div', [ 'class' => "container", 'style' => "background:#ffe5b6; margin-top:6px" ], "<p style=\"margin:0; padding:6px\">create ChildHistTable</p>");
+		UI::startContainer([ 'style' => "max-height:200px; overflow-y:scroll; border:1px solid #ffe5b6" ]);
+		foreach ($this->_simpleSchema['root'] as $childName => $schema) {
+			if ('@' == substr($childName, 0, 1)) continue;
+			$this->getChildHistTable($childName);
+			DBG::nicePrint($schema, '$childName('.$childName.')');// TODO: DBG
+		}
+		UI::endContainer();
 	}
 
 }

+ 167 - 167
SE/se-lib/Schema/DefaultDb/zaliczka_pozycja/ZaliczkaPozycjaStorageAcl.php

@@ -5,183 +5,183 @@ Lib::loadClass('Core_AclHelper');
 
 class Schema_DefaultDb_zaliczka_pozycja_ZaliczkaPozycjaStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja',// Api_WfsNs::getBaseWfsUri() . '/default_db/Zaliczka'
-      '@primaryKey' => 'id',
-      'id' => [ '@type' => 'xsd:integer', '@alias' => 'ID' ],
-      'nr_faktury' => [ '@type' => "xsd:string" ],
-      'kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
-      'vat' => [ '@type' => "xsd:integer", '@default' => 23 ],
-      'kwota_netto' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
-      'kategoria_kosztu' => [ '@type' => 'p5:enum', '@aliasFieldValues' => [
-        'namespace' => 'default_db/IN7_DZIENNIK_KORESP',
-        'childName' => 'KATEGORIA_KOSZTU'
-      ] ],// default_db__x3A__ZALICZKA_POZYCJA:kategoria_kosztuType, default_db__x3A__IN7_DZIENNIK_KORESP:kategoria_kosztuType
-      'typ_dokumentu' => [ '@type' => 'p5:enum' ], // enum('faktura', 'inne')
-      // 'korespondencja' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/ZaliczkaKoresp' ],
-      // 'projekt' => [ '@ref' => 'default_db/IN7_MK_BAZA_DYSTRYBUCJI/ZaliczkaProjekt' ]
-    ],
-    // 'kategoria_kosztuType' => [// TODO: enumeration or config for remote data fetch - Typespecial
-      // <xsd:simpleType name="A_STATUSType">
-      //   <xsd:restriction base="xsd:string">
-      //     <xsd:enumeration value="DELETED"/>
-      //     <xsd:enumeration value="MONITOR"/>
-      //     <xsd:enumeration value="NORMAL"/>
-      //     <xsd:enumeration value="OFF_HARD"/>
-      //     <xsd:enumeration value="OFF_SOFT"/>
-      //     <xsd:enumeration value="WAITING"/>
-      //     <xsd:enumeration value="WARNING"/>
-      //   </xsd:restriction>
-      // </xsd:simpleType>
-    // ]
-  ];
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja',// Api_WfsNs::getBaseWfsUri() . '/default_db/Zaliczka'
+			'@primaryKey' => 'id',
+			'id' => [ '@type' => 'xsd:integer', '@alias' => 'ID' ],
+			'nr_faktury' => [ '@type' => "xsd:string" ],
+			'kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
+			'vat' => [ '@type' => "xsd:integer", '@default' => 23 ],
+			'kwota_netto' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2 ],
+			'kategoria_kosztu' => [ '@type' => 'p5:enum', '@aliasFieldValues' => [
+				'namespace' => 'default_db/IN7_DZIENNIK_KORESP',
+				'childName' => 'KATEGORIA_KOSZTU'
+			] ],// default_db__x3A__ZALICZKA_POZYCJA:kategoria_kosztuType, default_db__x3A__IN7_DZIENNIK_KORESP:kategoria_kosztuType
+			'typ_dokumentu' => [ '@type' => 'p5:enum' ], // enum('faktura', 'inne')
+			// 'korespondencja' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/ZaliczkaKoresp' ],
+			// 'projekt' => [ '@ref' => 'default_db/IN7_MK_BAZA_DYSTRYBUCJI/ZaliczkaProjekt' ]
+		],
+		// 'kategoria_kosztuType' => [// TODO: enumeration or config for remote data fetch - Typespecial
+			// <xsd:simpleType name="A_STATUSType">
+			//	 <xsd:restriction base="xsd:string">
+			//		 <xsd:enumeration value="DELETED"/>
+			//		 <xsd:enumeration value="MONITOR"/>
+			//		 <xsd:enumeration value="NORMAL"/>
+			//		 <xsd:enumeration value="OFF_HARD"/>
+			//		 <xsd:enumeration value="OFF_SOFT"/>
+			//		 <xsd:enumeration value="WAITING"/>
+			//		 <xsd:enumeration value="WARNING"/>
+			//	 </xsd:restriction>
+			// </xsd:simpleType>
+		// ]
+	];
 
-  public function addItem($itemTodo) {
-    DBG::log(['msg'=> 'addItem', $itemTodo]);
-    $sqlItem = array();
-    $kwota = V::get('kwota', 0, $itemTodo, 'price');
-    if ($kwota > 0) $sqlItem[ $this->getSqlFieldName('kwota') ] = $kwota;
-    if (!empty($itemTodo['nr_faktury'])) {
-      $sqlItem[ $this->getSqlFieldName('nr_faktury') ] = $itemTodo['nr_faktury'];
-    }
-    if (array_key_exists('vat', $itemTodo)) {
-      $sqlItem[ $this->getSqlFieldName('vat') ] = (int)$itemTodo['vat'];
-    }
-    if (!empty($itemTodo['kategoria_kosztu'])) {
-      $sqlItem[ $this->getSqlFieldName('kategoria_kosztu') ] = $itemTodo['kategoria_kosztu'];
-    }
-    if (!empty($itemTodo['typ_dokumentu'])) {
-      $sqlItem[ $this->getSqlFieldName('typ_dokumentu') ] = $itemTodo['typ_dokumentu'];
-    }
+	public function addItem($itemTodo) {
+		DBG::log(['msg'=> 'addItem', $itemTodo]);
+		$sqlItem = array();
+		$kwota = V::get('kwota', 0, $itemTodo, 'price');
+		if ($kwota > 0) $sqlItem[ $this->getSqlFieldName('kwota') ] = $kwota;
+		if (!empty($itemTodo['nr_faktury'])) {
+			$sqlItem[ $this->getSqlFieldName('nr_faktury') ] = $itemTodo['nr_faktury'];
+		}
+		if (array_key_exists('vat', $itemTodo)) {
+			$sqlItem[ $this->getSqlFieldName('vat') ] = (int)$itemTodo['vat'];
+		}
+		if (!empty($itemTodo['kategoria_kosztu'])) {
+			$sqlItem[ $this->getSqlFieldName('kategoria_kosztu') ] = $itemTodo['kategoria_kosztu'];
+		}
+		if (!empty($itemTodo['typ_dokumentu'])) {
+			$sqlItem[ $this->getSqlFieldName('typ_dokumentu') ] = $itemTodo['typ_dokumentu'];
+		}
 
-    $vat = V::get('vat', 23, $itemTodo, 'int');
-    $sqlItem[ $this->getSqlFieldName('kwota_netto') ] = ($kwota > 0 && $vat > 0)
-      ? $kwota / (1 + $vat / 100)
-      : $kwota;
+		$vat = V::get('vat', 23, $itemTodo, 'int');
+		$sqlItem[ $this->getSqlFieldName('kwota_netto') ] = ($kwota > 0 && $vat > 0)
+			? $kwota / (1 + $vat / 100)
+			: $kwota;
 
-    if (empty($sqlItem)) throw new Exception("Empty record");
-    $sqlItem['A_RECORD_CREATE_DATE'] = 'NOW()';
-    $sqlItem['A_RECORD_CREATE_AUTHOR'] = User::getLogin();
-    $idCreated = DB::getPDO()->insert($this->getRootTableName(), $sqlItem);
-    if ($idCreated > 0) {
-      $sqlHistItem = $sqlItem;
-      $sqlHistItem['ID_USERS2'] = $idCreated;
-      DB::getPDO()->insert($this->getRootTableName() . "_HIST", $sqlHistItem);
-    }
-    return $idCreated;
-  }
+		if (empty($sqlItem)) throw new Exception("Empty record");
+		$sqlItem['A_RECORD_CREATE_DATE'] = 'NOW()';
+		$sqlItem['A_RECORD_CREATE_AUTHOR'] = User::getLogin();
+		$idCreated = DB::getPDO()->insert($this->getRootTableName(), $sqlItem);
+		if ($idCreated > 0) {
+			$sqlHistItem = $sqlItem;
+			$sqlHistItem['ID_USERS2'] = $idCreated;
+			DB::getPDO()->insert($this->getRootTableName() . "_HIST", $sqlHistItem);
+		}
+		return $idCreated;
+	}
 
-  public function updateItem($itemPatch) {
-    DBG::log(['msg'=> 'updateItem: $itemPatch', $itemPatch]);
-    // 'id' => '1',
-    //   'nr_faktury' => '100.',
-    //   'kwota' => '123.46',
-    //   'vat' => '23',
-    //   'kwota_netto' => '100.37',
-    //   'kategoria_kosztu' => 'BUDOWA: Wynagrodzenia osobowe + ZUS',
-    $pkField = $this->getPrimaryKeyField();
-    $pk = V::get($pkField, null, $itemPatch);
-    if (null === $pk) throw new Exception("BUG missing primary key field for {$this->_namespace}");
-    $oldItem = $this->getItem($pk);// TODO: only cols: ['id', 'nr_faktury', 'kwota', 'vat', 'kategoria_kosztu']
-    DBG::log(['msg'=> 'updateItem: $oldItem', $oldItem]);
-    if (!$oldItem) throw new Exception("BUG item '{$pk}' not found ({$this->_namespace})");
-    $sqlPatch = array();
-    if (array_key_exists('nr_faktury', $itemPatch) && $oldItem['nr_faktury'] != $itemPatch['nr_faktury']) {
-      $sqlPatch[ $this->getSqlFieldName('nr_faktury') ] = $itemPatch['nr_faktury'];
-    }
-    $nettoToUpdate = false;
-    $kwota = V::get('kwota', 0, $oldItem, 'price');
-    if (array_key_exists('kwota', $itemPatch) && $oldItem['kwota'] != $itemPatch['kwota']) {
-      $nettoToUpdate = true;
-      $kwota = V::get('kwota', 0, $itemPatch, 'price');
-      $sqlPatch[ $this->getSqlFieldName('kwota') ] = $kwota;
-    }
-    $vat = V::get('vat', 0, $oldItem, 'int');
-    if (array_key_exists('vat', $itemPatch) && $oldItem['vat'] != $itemPatch['vat']) {
-      $nettoToUpdate = true;
-      $vat = V::get('vat', 0, $itemPatch, 'int');
-      $sqlPatch[ $this->getSqlFieldName('vat') ] = $vat;
-    }
-    // DBG::log("\$nettoToUpdate = ({$nettoToUpdate})");
-    if ($nettoToUpdate) {
-      $vat = V::get('vat', 0, $oldItem, 'int');
-      $vat = V::get('vat', $vat, $itemPatch, 'int');
-      // DBG::log("\$vat = ({$vat}) \$kwota=({$kwota})");
-      $sqlPatch[ $this->getSqlFieldName('kwota_netto') ] = ($kwota > 0)
-        ? $kwota / (1 + $vat / 100)
-        : 0;
-    }
-    if (array_key_exists('kategoria_kosztu', $itemPatch) && $oldItem['kategoria_kosztu'] != $itemPatch['kategoria_kosztu']) {
-      $sqlPatch[ $this->getSqlFieldName('kategoria_kosztu') ] = $itemPatch['kategoria_kosztu'];
-    }
-    if (array_key_exists('typ_dokumentu', $itemPatch) && $oldItem['typ_dokumentu'] != $itemPatch['typ_dokumentu']) {
-      $sqlPatch[ $this->getSqlFieldName('typ_dokumentu') ] = $itemPatch['typ_dokumentu'];
-    }
-    DBG::log(['msg'=> 'updateItem: $sqlPatch', $sqlPatch]);
-    if (empty($sqlPatch)) return 0;
-    return DB::getPDO()->update(
-      $this->getRootTableName(),
-      $this->getSqlPrimaryKeyField(),
-      $pk,
-      $sqlPatch
-    );
-  }
+	public function updateItem($itemPatch) {
+		DBG::log(['msg'=> 'updateItem: $itemPatch', $itemPatch]);
+		// 'id' => '1',
+		//	 'nr_faktury' => '100.',
+		//	 'kwota' => '123.46',
+		//	 'vat' => '23',
+		//	 'kwota_netto' => '100.37',
+		//	 'kategoria_kosztu' => 'BUDOWA: Wynagrodzenia osobowe + ZUS',
+		$pkField = $this->getPrimaryKeyField();
+		$pk = V::get($pkField, null, $itemPatch);
+		if (null === $pk) throw new Exception("BUG missing primary key field for {$this->_namespace}");
+		$oldItem = $this->getItem($pk);// TODO: only cols: ['id', 'nr_faktury', 'kwota', 'vat', 'kategoria_kosztu']
+		DBG::log(['msg'=> 'updateItem: $oldItem', $oldItem]);
+		if (!$oldItem) throw new Exception("BUG item '{$pk}' not found ({$this->_namespace})");
+		$sqlPatch = array();
+		if (array_key_exists('nr_faktury', $itemPatch) && $oldItem['nr_faktury'] != $itemPatch['nr_faktury']) {
+			$sqlPatch[ $this->getSqlFieldName('nr_faktury') ] = $itemPatch['nr_faktury'];
+		}
+		$nettoToUpdate = false;
+		$kwota = V::get('kwota', 0, $oldItem, 'price');
+		if (array_key_exists('kwota', $itemPatch) && $oldItem['kwota'] != $itemPatch['kwota']) {
+			$nettoToUpdate = true;
+			$kwota = V::get('kwota', 0, $itemPatch, 'price');
+			$sqlPatch[ $this->getSqlFieldName('kwota') ] = $kwota;
+		}
+		$vat = V::get('vat', 0, $oldItem, 'int');
+		if (array_key_exists('vat', $itemPatch) && $oldItem['vat'] != $itemPatch['vat']) {
+			$nettoToUpdate = true;
+			$vat = V::get('vat', 0, $itemPatch, 'int');
+			$sqlPatch[ $this->getSqlFieldName('vat') ] = $vat;
+		}
+		// DBG::log("\$nettoToUpdate = ({$nettoToUpdate})");
+		if ($nettoToUpdate) {
+			$vat = V::get('vat', 0, $oldItem, 'int');
+			$vat = V::get('vat', $vat, $itemPatch, 'int');
+			// DBG::log("\$vat = ({$vat}) \$kwota=({$kwota})");
+			$sqlPatch[ $this->getSqlFieldName('kwota_netto') ] = ($kwota > 0)
+				? $kwota / (1 + $vat / 100)
+				: 0;
+		}
+		if (array_key_exists('kategoria_kosztu', $itemPatch) && $oldItem['kategoria_kosztu'] != $itemPatch['kategoria_kosztu']) {
+			$sqlPatch[ $this->getSqlFieldName('kategoria_kosztu') ] = $itemPatch['kategoria_kosztu'];
+		}
+		if (array_key_exists('typ_dokumentu', $itemPatch) && $oldItem['typ_dokumentu'] != $itemPatch['typ_dokumentu']) {
+			$sqlPatch[ $this->getSqlFieldName('typ_dokumentu') ] = $itemPatch['typ_dokumentu'];
+		}
+		DBG::log(['msg'=> 'updateItem: $sqlPatch', $sqlPatch]);
+		if (empty($sqlPatch)) return 0;
+		return DB::getPDO()->update(
+			$this->getRootTableName(),
+			$this->getSqlPrimaryKeyField(),
+			$pk,
+			$sqlPatch
+		);
+	}
 
-  public function getItem($primaryKey, $params = []) {
-    $row = DB::getPDO()->fetchAll("
-      select t.*
-      from `ZALICZKA_POZYCJA` t
-      where t.ID = {$primaryKey}
-    ");
-    $row = (!empty($row)) ? reset($row) : null;
-    if (!$row) return null;
-    return $this->buildFromSqlRow($row, $params);
-  }
+	public function getItem($primaryKey, $params = []) {
+		$row = DB::getPDO()->fetchAll("
+			select t.*
+			from `ZALICZKA_POZYCJA` t
+			where t.ID = {$primaryKey}
+		");
+		$row = (!empty($row)) ? reset($row) : null;
+		if (!$row) return null;
+		return $this->buildFromSqlRow($row, $params);
+	}
 
-  public function getItems($params = array()) {
-    DBG::log(['msg'=> 'getItems', $params]);
-    // $idUser = V::get('primaryKey', 0, $params['#refFrom'], 'int');
-    $sqlWhereAnd = array();
-    if (empty($params)) {
-    } else if (!empty($params['@primaryKey'])) {// [@primaryKey] => Array ([0] => 59599)
-      if (is_array($params['@primaryKey'])) {
-        $sqlWhereAnd[] = "z.ID in(" . implode(", ", $params['@primaryKey']) . ")";
-      }
-    // } else if (!empty($params['f_title'])) {
-    //   DBG::log("return filter by K_ZAWARTOS, K_OD_KOGO like '%{$params['f_title']}%' order by last created rows by user or another users");
-    //   $sqlParamTitle = DB::getPDO()->quote("%{$params['f_title']}%", PDO::PARAM_STR);
-    //   $sqlWhereAnd[] = " (
-    //     k.ID like {$sqlParamTitle}
-    //     or k.K_ZAWARTOS like {$sqlParamTitle}
-    //     or k.K_OD_KOGO like {$sqlParamTitle}
-    //   ) ";
-    }
-    $sqlWhere = (!empty($sqlWhereAnd)) ? implode(" and ", $sqlWhereAnd) : "1=1";
-    return array_map(
-      function ($row) use ($params) {
-        return $this->buildFromSqlRow($row, $params);
-      },
-      DB::getPDO()->fetchAll("
-        select z.*
-        from ZALICZKA_POZYCJA z
-        where {$sqlWhere}
-        order by z.ID ASC
-      ")
-    );
-  }
+	public function getItems($params = array()) {
+		DBG::log(['msg'=> 'getItems', $params]);
+		// $idUser = V::get('primaryKey', 0, $params['#refFrom'], 'int');
+		$sqlWhereAnd = array();
+		if (empty($params)) {
+		} else if (!empty($params['@primaryKey'])) {// [@primaryKey] => Array ([0] => 59599)
+			if (is_array($params['@primaryKey'])) {
+				$sqlWhereAnd[] = "z.ID in(" . implode(", ", $params['@primaryKey']) . ")";
+			}
+		// } else if (!empty($params['f_title'])) {
+		//	 DBG::log("return filter by K_ZAWARTOS, K_OD_KOGO like '%{$params['f_title']}%' order by last created rows by user or another users");
+		//	 $sqlParamTitle = DB::getPDO()->quote("%{$params['f_title']}%", PDO::PARAM_STR);
+		//	 $sqlWhereAnd[] = " (
+		//		 k.ID like {$sqlParamTitle}
+		//		 or k.K_ZAWARTOS like {$sqlParamTitle}
+		//		 or k.K_OD_KOGO like {$sqlParamTitle}
+		//	 ) ";
+		}
+		$sqlWhere = (!empty($sqlWhereAnd)) ? implode(" and ", $sqlWhereAnd) : "1=1";
+		return array_map(
+			function ($row) use ($params) {
+				return $this->buildFromSqlRow($row, $params);
+			},
+			DB::getPDO()->fetchAll("
+				select z.*
+				from ZALICZKA_POZYCJA z
+				where {$sqlWhere}
+				order by z.ID ASC
+			")
+		);
+	}
 
 }
 
 /* FIX BUG kwota_netto = 0
 
-    SELECT p.ID, p.kwota, p.kwota_netto , p.vat , round(p.kwota / (1 + (p.vat / 100)), 2), p.A_RECORD_CREATE_DATE, p.A_RECORD_CREATE_AUTHOR, p.A_RECORD_UPDATE_DATE, p.A_RECORD_UPDATE_AUTHOR
-      , j.*
-      , z.*
-    FROM `ZALICZKA_POZYCJA` p
-      left join `CRM__#REF_TABLE__2` j on (j.REMOTE_PRIMARY_KEY = p.ID)
-      left join `ZALICZKA` z on(z.ID = j.PRIMARY_KEY)
-    where p.kwota > 0 and p.kwota_netto = 0
+		SELECT p.ID, p.kwota, p.kwota_netto , p.vat , round(p.kwota / (1 + (p.vat / 100)), 2), p.A_RECORD_CREATE_DATE, p.A_RECORD_CREATE_AUTHOR, p.A_RECORD_UPDATE_DATE, p.A_RECORD_UPDATE_AUTHOR
+			, j.*
+			, z.*
+		FROM `ZALICZKA_POZYCJA` p
+			left join `CRM__#REF_TABLE__2` j on (j.REMOTE_PRIMARY_KEY = p.ID)
+			left join `ZALICZKA` z on(z.ID = j.PRIMARY_KEY)
+		where p.kwota > 0 and p.kwota_netto = 0
 
-    update `ZALICZKA_POZYCJA` set kwota_netto = round(kwota / (1 + (vat / 100)), 2) where kwota > 0 and kwota_netto = 0
+		update `ZALICZKA_POZYCJA` set kwota_netto = round(kwota / (1 + (vat / 100)), 2) where kwota > 0 and kwota_netto = 0
 */

+ 222 - 222
SE/se-lib/Schema/DefaultDb/zaliczka_wniosek/ZaliczkaWniosekStorageAcl.php

@@ -6,237 +6,237 @@ Lib::loadClass('DBG');
 
 class Schema_DefaultDb_zaliczka_wniosek_ZaliczkaWniosekStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_db/ZALICZKA_WNIOSEK/ZaliczkaWniosek',// Api_WfsNs::getBaseWfsUri() . '/default_db/Zaliczka'
-      '@primaryKey' => 'id',
-      'id' => [ '@type' => 'xsd:integer', '@alias' => 'ID' ],
-      'created' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_CREATE_DATE' ],
-      'kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2, '@alias' => 'KWOTA' ],
-      'uwagi' => [ '@type' => 'xsd:string', '@alias' => 'UWAGI' ],
-      'status' => [ '@type' => 'p5:enum', '@alias' => 'A_STATUS', '@aliasMap' => [
-        'WAITING' => "Oczekuje zatwierdzenia",
-        'NORMAL' => "Zatwierdzony",
-        'OFF_HARD' => "Odrzucony",
-        'DELETED' => "Anulowany",
-      ], '@default' => 'WAITING' ],
-      'workerLogin' => [ '@type' => 'xsd:string', '@alias' => 'L_APPOITMENT_USER' ],
-      'approvedBy' => [ '@type' => 'xsd:string', '@alias' => 'APPROVED_BY' ],
-    ],
-  ];
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_db/ZALICZKA_WNIOSEK/ZaliczkaWniosek',// Api_WfsNs::getBaseWfsUri() . '/default_db/Zaliczka'
+			'@primaryKey' => 'id',
+			'id' => [ '@type' => 'xsd:integer', '@alias' => 'ID' ],
+			'created' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_CREATE_DATE' ],
+			'kwota' => [ '@type' => 'xsd:decimal', '@totalDigits' => 16, '@fractionDigits' => 2, '@alias' => 'KWOTA' ],
+			'uwagi' => [ '@type' => 'xsd:string', '@alias' => 'UWAGI' ],
+			'status' => [ '@type' => 'p5:enum', '@alias' => 'A_STATUS', '@aliasMap' => [
+				'WAITING' => "Oczekuje zatwierdzenia",
+				'NORMAL' => "Zatwierdzony",
+				'OFF_HARD' => "Odrzucony",
+				'DELETED' => "Anulowany",
+			], '@default' => 'WAITING' ],
+			'workerLogin' => [ '@type' => 'xsd:string', '@alias' => 'L_APPOITMENT_USER' ],
+			'approvedBy' => [ '@type' => 'xsd:string', '@alias' => 'APPROVED_BY' ],
+		],
+	];
 
-  public function getField($idField) {
-    $idField = (int)$idField;
-    $fieldName = DB::getPDO()->fetchValue("
-      select z.`DESC`
-      from CRM_LISTA_ZASOBOW z
-      where z.ID = $idField
-    ");
-    if ('id' == $fieldName) {
-      return [
-        'name' => 'id',
-        'type' => 'int(11)',
-        'perms' => 'R'
-      ];
-    }
-  }
+	public function getField($idField) {
+		$idField = (int)$idField;
+		$fieldName = DB::getPDO()->fetchValue("
+			select z.`DESC`
+			from CRM_LISTA_ZASOBOW z
+			where z.ID = $idField
+		");
+		if ('id' == $fieldName) {
+			return [
+				'name' => 'id',
+				'type' => 'int(11)',
+				'perms' => 'R'
+			];
+		}
+	}
 
-  public function addItem($itemTodo) {
-    DBG::log(['msg' => 'addItem($itemTodo)', 'log' => $itemTodo]);
-    if (empty($itemTodo['kwota'])) throw new Exception("Nie podano kwoty");
-    if (empty($itemTodo['workerLogin'])) throw new Exception("Nie podano pracownika");
+	public function addItem($itemTodo) {
+		DBG::log(['msg' => 'addItem($itemTodo)', 'log' => $itemTodo]);
+		if (empty($itemTodo['kwota'])) throw new Exception("Nie podano kwoty");
+		if (empty($itemTodo['workerLogin'])) throw new Exception("Nie podano pracownika");
 
-    $sqlItem = [
-      'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
-      'A_RECORD_CREATE_DATE' => "NOW()",
-      'L_APPOITMENT_USER' => $itemTodo['workerLogin'],
-      'KWOTA' => $itemTodo['kwota'],
-      'UWAGI' => $itemTodo['uwagi'],
-    ];
-    $id = DB::getPDO()->insert('ZALICZKA_WNIOSEK', $sqlItem);
-    DBG::log(['msg' => '$id', 'log' => $id]);
-    if (!$id) throw new Exception("Wystąpiły błędy podczas dodawania Wniosku o zaliczkę do bazy danych");
+		$sqlItem = [
+			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_CREATE_DATE' => "NOW()",
+			'L_APPOITMENT_USER' => $itemTodo['workerLogin'],
+			'KWOTA' => $itemTodo['kwota'],
+			'UWAGI' => $itemTodo['uwagi'],
+		];
+		$id = DB::getPDO()->insert('ZALICZKA_WNIOSEK', $sqlItem);
+		DBG::log(['msg' => '$id', 'log' => $id]);
+		if (!$id) throw new Exception("Wystąpiły błędy podczas dodawania Wniosku o zaliczkę do bazy danych");
 
-    $sqlItem['ID_USERS2'] = $id;
-    DB::getPDO()->insert('ZALICZKA_WNIOSEK_HIST', $sqlItem);
-    return $id;
-  }
+		$sqlItem['ID_USERS2'] = $id;
+		DB::getPDO()->insert('ZALICZKA_WNIOSEK_HIST', $sqlItem);
+		return $id;
+	}
 
-  public function updateItem($itemPatch) {
-    DBG::log(['msg' => '$itemPatch', $itemPatch]);
-    $pkField = $this->getPrimaryKeyField();
-    if (!array_key_exists($pkField, $itemPatch)) throw new Exception("Missing primary key");
-    $pk = (int)$itemPatch[$pkField];
-    if ($pk <= 0) throw new Exception("Wrong primary key format");
+	public function updateItem($itemPatch) {
+		DBG::log(['msg' => '$itemPatch', $itemPatch]);
+		$pkField = $this->getPrimaryKeyField();
+		if (!array_key_exists($pkField, $itemPatch)) throw new Exception("Missing primary key");
+		$pk = (int)$itemPatch[$pkField];
+		if ($pk <= 0) throw new Exception("Wrong primary key format");
 
-    $sqlItemTodo = [];
-    if (array_key_exists('status', $itemPatch)) {
-      $sqlItemTodo['A_STATUS'] = $this->enumValueToSql('status', $itemPatch['status']);
-    }
-    if (array_key_exists('approvedBy', $itemPatch)) {
-      $sqlItemTodo['APPROVED_BY'] = $itemPatch['approvedBy'];
-    }
-    if (empty($sqlItemTodo)) throw new Exception("Nothing to change");
+		$sqlItemTodo = [];
+		if (array_key_exists('status', $itemPatch)) {
+			$sqlItemTodo['A_STATUS'] = $this->enumValueToSql('status', $itemPatch['status']);
+		}
+		if (array_key_exists('approvedBy', $itemPatch)) {
+			$sqlItemTodo['APPROVED_BY'] = $itemPatch['approvedBy'];
+		}
+		if (empty($sqlItemTodo)) throw new Exception("Nothing to change");
 
-    unset($sqlItemTodo[$pkField]);
-    $sqlItemTodo['A_RECORD_UPDATE_AUTHOR'] = User::getLogin();
-    $sqlItemTodo['A_RECORD_UPDATE_DATE'] = "NOW()";
-    DB::getPDO()->update($this->getRootTableName(), $pkField, $pk, $sqlItemTodo);
-    $sqlItemTodo['ID_USERS2'] = $pk;
-    DB::getPDO()->insert($this->getRootTableName() . "_HIST", $sqlItemTodo);
-  }
+		unset($sqlItemTodo[$pkField]);
+		$sqlItemTodo['A_RECORD_UPDATE_AUTHOR'] = User::getLogin();
+		$sqlItemTodo['A_RECORD_UPDATE_DATE'] = "NOW()";
+		DB::getPDO()->update($this->getRootTableName(), $pkField, $pk, $sqlItemTodo);
+		$sqlItemTodo['ID_USERS2'] = $pk;
+		DB::getPDO()->insert($this->getRootTableName() . "_HIST", $sqlItemTodo);
+	}
 
-  public function getItem($primaryKey, $params = []) {
-    $sqlWhere = $this->_parseSqlWhere([
-      '@primaryKey' => $primaryKey
-    ]);
-    $row = DB::getPDO()->fetchFirst("
-      select t.*
-        , (select u.ID from ADMIN_USERS u where u.ADM_ACCOUNT = t.L_APPOITMENT_USER limit 1) as ID_USER
-      from ZALICZKA_WNIOSEK t
-      {$sqlWhere}
-    ");
-    return [
-      'id' => $row['ID'],
-      'created' => $row['A_RECORD_CREATE_DATE'],
-      'status' => $this->enumValueFromSql('status', $row['A_STATUS']),
-      'kwota' => $row['KWOTA'],
-      'uwagi' => $row['UWAGI'],
-      'workerLogin' => $row['L_APPOITMENT_USER'],
-      'workerID' => $row['ID_USER'],
-    ];
-  }
+	public function getItem($primaryKey, $params = []) {
+		$sqlWhere = $this->_parseSqlWhere([
+			'@primaryKey' => $primaryKey
+		]);
+		$row = DB::getPDO()->fetchFirst("
+			select t.*
+				, (select u.ID from ADMIN_USERS u where u.ADM_ACCOUNT = t.L_APPOITMENT_USER limit 1) as ID_USER
+			from ZALICZKA_WNIOSEK t
+			{$sqlWhere}
+		");
+		return [
+			'id' => $row['ID'],
+			'created' => $row['A_RECORD_CREATE_DATE'],
+			'status' => $this->enumValueFromSql('status', $row['A_STATUS']),
+			'kwota' => $row['KWOTA'],
+			'uwagi' => $row['UWAGI'],
+			'workerLogin' => $row['L_APPOITMENT_USER'],
+			'workerID' => $row['ID_USER'],
+		];
+	}
 
-  public function getTotal($params = []) {
-    $sqlWhere = $this->_parseSqlWhere($params);
-    return DB::getPDO()->fetchValue("
-      select count(*) as cnt
-      from ZALICZKA_WNIOSEK t
-      {$sqlWhere}
-    ");
-  }
+	public function getTotal($params = []) {
+		$sqlWhere = $this->_parseSqlWhere($params);
+		return DB::getPDO()->fetchValue("
+			select count(*) as cnt
+			from ZALICZKA_WNIOSEK t
+			{$sqlWhere}
+		");
+	}
 
-  public function getItems($params = []) {
-    DBG::log(['msg'=>'getItems $params', '$params' => $params]);
-    $sqlWhere = $this->_parseSqlWhere($params);
-    $sqlOrderBy = "";
-    if (!empty($params['sortBy'])) {
-      $sqlOrderBy = $this->parseSqlSortBy($params['sortBy'], 't');
-    } else if (array_key_exists('order_by', $params) && array_key_exists('order_dir', $params)) {
-      $sqlOrderBy = $this->parseSqlSortBy("{$params['order_by']} {$params['order_dir']}", 't');
-    }
-    return array_map(function ($row) {
-      return [
-        'id' => $row['ID'],
-        'created' => $row['A_RECORD_CREATE_DATE'],
-        'status' => $this->enumValueFromSql('status', $row['A_STATUS']),
-        'kwota' => $row['KWOTA'],
-        'uwagi' => $row['UWAGI'],
-        'workerLogin' => $row['L_APPOITMENT_USER'],
-        'approvedBy' => $row['APPROVED_BY'],
-      ];
-    }, DB::getPDO()->fetchAll("
-      select t.*
-      from ZALICZKA_WNIOSEK t
-      {$sqlWhere}
-      {$sqlOrderBy}
-    "));
-  }
+	public function getItems($params = []) {
+		DBG::log(['msg'=>'getItems $params', '$params' => $params]);
+		$sqlWhere = $this->_parseSqlWhere($params);
+		$sqlOrderBy = "";
+		if (!empty($params['sortBy'])) {
+			$sqlOrderBy = $this->parseSqlSortBy($params['sortBy'], 't');
+		} else if (array_key_exists('order_by', $params) && array_key_exists('order_dir', $params)) {
+			$sqlOrderBy = $this->parseSqlSortBy("{$params['order_by']} {$params['order_dir']}", 't');
+		}
+		return array_map(function ($row) {
+			return [
+				'id' => $row['ID'],
+				'created' => $row['A_RECORD_CREATE_DATE'],
+				'status' => $this->enumValueFromSql('status', $row['A_STATUS']),
+				'kwota' => $row['KWOTA'],
+				'uwagi' => $row['UWAGI'],
+				'workerLogin' => $row['L_APPOITMENT_USER'],
+				'approvedBy' => $row['APPROVED_BY'],
+			];
+		}, DB::getPDO()->fetchAll("
+			select t.*
+			from ZALICZKA_WNIOSEK t
+			{$sqlWhere}
+			{$sqlOrderBy}
+		"));
+	}
 
-  public function _parseSqlWhere($params = []) {
-    DBG::log(['msg'=>'_parseSqlWhere $params', '$params' => $params]);
-    $sqlWhere = [];
-    if (!empty($params['f_workerLogin'])) {
-      $sqlUserLogin = DB::getPDO()->quote($params['f_workerLogin'], PDO::PARAM_STR);
-      $sqlWhere[] = "t.`L_APPOITMENT_USER` = {$sqlUserLogin}";
-    }
-    if (!empty($params['f_id'])) {
-      $sqlWhere[] = "t.`ID` = " . DB::getPDO()->quote($params['f_id'], PDO::PARAM_STR);
-    }
-    if (!empty($params['@primaryKey'])) {
-      $sqlWhere[] = "t.`ID` = " . DB::getPDO()->quote($params['@primaryKey'], PDO::PARAM_STR);
-    }
-    return (!empty($sqlWhere)) ? " where " . implode("\n and ", $sqlWhere) : "";
-  }
+	public function _parseSqlWhere($params = []) {
+		DBG::log(['msg'=>'_parseSqlWhere $params', '$params' => $params]);
+		$sqlWhere = [];
+		if (!empty($params['f_workerLogin'])) {
+			$sqlUserLogin = DB::getPDO()->quote($params['f_workerLogin'], PDO::PARAM_STR);
+			$sqlWhere[] = "t.`L_APPOITMENT_USER` = {$sqlUserLogin}";
+		}
+		if (!empty($params['f_id'])) {
+			$sqlWhere[] = "t.`ID` = " . DB::getPDO()->quote($params['f_id'], PDO::PARAM_STR);
+		}
+		if (!empty($params['@primaryKey'])) {
+			$sqlWhere[] = "t.`ID` = " . DB::getPDO()->quote($params['@primaryKey'], PDO::PARAM_STR);
+		}
+		return (!empty($sqlWhere)) ? " where " . implode("\n and ", $sqlWhere) : "";
+	}
 
-  public function enumValueFromSql($fieldName, $sqlValue) {
-    DBG::log(['msg'=>'enumValueFromSql $type', '$type' => $this->getXsdFieldType($fieldName)]);
-    if ('p5:enum' == $this->getXsdFieldType($fieldName)) {
-      $aliasMap = V::get('@aliasMap', '', $this->_simpleSchema['root'][$fieldName]);
-      if (!empty($aliasMap) && is_array($aliasMap)) {
-        if (array_key_exists($sqlValue, $aliasMap)) {
-          return $aliasMap[$sqlValue];
-        }
-      }
-    }
-    return $sqlValue;
-  }
-  public function enumValueToSql($fieldName, $value) {
-    DBG::log(['msg'=>'enumValueToSql $type', '$type' => $this->getXsdFieldType($fieldName)]);
-    if ('p5:enum' == $this->getXsdFieldType($fieldName)) {
-      $aliasMap = V::get('@aliasMap', '', $this->_simpleSchema['root'][$fieldName]);
-      if (empty($aliasMap) || !is_array($aliasMap)) throw new Exception("Schema error - missing @aliasMap for field '{$fieldName}'");
-      $aliasMap = array_flip($aliasMap);
-      if (!array_key_exists($value, $aliasMap)) throw new Exception("Schema error - value not exists in alias map");
-      return $aliasMap[$value];
-    }
-    throw new Exception("Schema error - field is not enum '{$fieldName}'");
-  }
+	public function enumValueFromSql($fieldName, $sqlValue) {
+		DBG::log(['msg'=>'enumValueFromSql $type', '$type' => $this->getXsdFieldType($fieldName)]);
+		if ('p5:enum' == $this->getXsdFieldType($fieldName)) {
+			$aliasMap = V::get('@aliasMap', '', $this->_simpleSchema['root'][$fieldName]);
+			if (!empty($aliasMap) && is_array($aliasMap)) {
+				if (array_key_exists($sqlValue, $aliasMap)) {
+					return $aliasMap[$sqlValue];
+				}
+			}
+		}
+		return $sqlValue;
+	}
+	public function enumValueToSql($fieldName, $value) {
+		DBG::log(['msg'=>'enumValueToSql $type', '$type' => $this->getXsdFieldType($fieldName)]);
+		if ('p5:enum' == $this->getXsdFieldType($fieldName)) {
+			$aliasMap = V::get('@aliasMap', '', $this->_simpleSchema['root'][$fieldName]);
+			if (empty($aliasMap) || !is_array($aliasMap)) throw new Exception("Schema error - missing @aliasMap for field '{$fieldName}'");
+			$aliasMap = array_flip($aliasMap);
+			if (!array_key_exists($value, $aliasMap)) throw new Exception("Schema error - value not exists in alias map");
+			return $aliasMap[$value];
+		}
+		throw new Exception("Schema error - field is not enum '{$fieldName}'");
+	}
 
-  /**
-  * @param sortBy ID A,COL_X D,COL_Y A,...
-  * @return sql string "order by ..."
-  */
-  public function parseSqlSortBy($sortBy, $sqlTablePrefix = 't') {
-    $list = $this->parseSortBy($sortBy);
-    DBG::log(['msg'=>'parseSqlSortBy $list', '$list' => $list]);
-    if (empty($list)) return "";
-    return "order by " . implode(", ", array_map(function ($orderItem) use ($sqlTablePrefix) {
-      list($fieldName, $order) = $orderItem;
-      $sqlFieldName = $this->getSqlFieldName($fieldName);
-      return "{$sqlTablePrefix}.`{$sqlFieldName}` {$order}";
-    }, $list));
-  }
+	/**
+	* @param sortBy ID A,COL_X D,COL_Y A,...
+	* @return sql string "order by ..."
+	*/
+	public function parseSqlSortBy($sortBy, $sqlTablePrefix = 't') {
+		$list = $this->parseSortBy($sortBy);
+		DBG::log(['msg'=>'parseSqlSortBy $list', '$list' => $list]);
+		if (empty($list)) return "";
+		return "order by " . implode(", ", array_map(function ($orderItem) use ($sqlTablePrefix) {
+			list($fieldName, $order) = $orderItem;
+			$sqlFieldName = $this->getSqlFieldName($fieldName);
+			return "{$sqlTablePrefix}.`{$sqlFieldName}` {$order}";
+		}, $list));
+	}
 
-  /**
-  * @param sortBy ID A,COL_X D,COL_Y A,...
-  * @return array with field names and sort order: [ fieldName => order ( ASC | DESC ) ]
-  * TODO: require convert to sql names / validate if field exists or is allowed to sort
-  */
-  public function parseSortBy($sortBy) {
-    if (!$sortBy) return [];
-    return array_filter(
-      array_map(
-        function ($sortPart) {
-          DBG::log(['msg'=>'parseSortBy $sortPart', '$sortPart' => $sortPart]);
-          if (!$sortPart) return null;
-          list($fieldName, $order, $error) = explode(' ', trim($sortPart));
-          DBG::log("parseSortBy \$fieldName='{$fieldName}', \$order='{$order}', \$error='{$error}'");
-          if ($error) throw new Exception("sortBy parse error '{$sortPart}'");
-          if (!array_key_exists($fieldName, $this->_simpleSchema['root'])) throw new Exception("Parse sort by error - field not exists! '{$fieldName}'");
-          $order = strtoupper($order);
-          if ('A' == $order || 'ASC' == $order) {
-            $order = 'ASC';
-  				} else if ('D' == $order || 'DESC' == $order) {
-  					$order = 'DESC';
-  				} else throw new Exception("sortBy parse error - unknown sort order '{$order}' #" . __LINE__);
-          return [ $fieldName, $order ];
-        }, explode(',', $sortBy)
-      )
-      , function ($orderItem) {
-        return !empty($orderItem);
-      }
-    );
-  }
+	/**
+	* @param sortBy ID A,COL_X D,COL_Y A,...
+	* @return array with field names and sort order: [ fieldName => order ( ASC | DESC ) ]
+	* TODO: require convert to sql names / validate if field exists or is allowed to sort
+	*/
+	public function parseSortBy($sortBy) {
+		if (!$sortBy) return [];
+		return array_filter(
+			array_map(
+				function ($sortPart) {
+					DBG::log(['msg'=>'parseSortBy $sortPart', '$sortPart' => $sortPart]);
+					if (!$sortPart) return null;
+					list($fieldName, $order, $error) = explode(' ', trim($sortPart));
+					DBG::log("parseSortBy \$fieldName='{$fieldName}', \$order='{$order}', \$error='{$error}'");
+					if ($error) throw new Exception("sortBy parse error '{$sortPart}'");
+					if (!array_key_exists($fieldName, $this->_simpleSchema['root'])) throw new Exception("Parse sort by error - field not exists! '{$fieldName}'");
+					$order = strtoupper($order);
+					if ('A' == $order || 'ASC' == $order) {
+						$order = 'ASC';
+					} else if ('D' == $order || 'DESC' == $order) {
+						$order = 'DESC';
+					} else throw new Exception("sortBy parse error - unknown sort order '{$order}' #" . __LINE__);
+					return [ $fieldName, $order ];
+				}, explode(',', $sortBy)
+			)
+			, function ($orderItem) {
+				return !empty($orderItem);
+			}
+		);
+	}
 
-  public function reinstall() {
-    // TODO: mv to Core_AclSimpleSchemaBase and reainstall by _simpleSchema - read current data from `information_schema`
+	public function reinstall() {
+		// TODO: mv to Core_AclSimpleSchemaBase and reainstall by _simpleSchema - read current data from `information_schema`
 		DB::getPDO()->execSql("
 			CREATE TABLE IF NOT EXISTS `ZALICZKA_WNIOSEK` (
 				`ID` int(11) NOT NULL AUTO_INCREMENT,
-				`A_RECORD_CREATE_DATE` datetime  DEFAULT NULL,
-				`A_RECORD_CREATE_AUTHOR` varchar(20)  DEFAULT NULL,
-				`A_RECORD_UPDATE_DATE` datetime  DEFAULT NULL,
+				`A_RECORD_CREATE_DATE` datetime	DEFAULT NULL,
+				`A_RECORD_CREATE_AUTHOR` varchar(20)	DEFAULT NULL,
+				`A_RECORD_UPDATE_DATE` datetime	DEFAULT NULL,
 				`A_RECORD_UPDATE_AUTHOR` varchar(20) NOT NULL DEFAULT '',
 				`A_STATUS` enum('WAITING','NORMAL','MONITOR','WARNING','OFF_SOFT','OFF_HARD','DELETED') DEFAULT 'WAITING',
 				`A_ADM_COMPANY` varchar(100) NOT NULL DEFAULT '',
@@ -261,16 +261,16 @@ class Schema_DefaultDb_zaliczka_wniosek_ZaliczkaWniosekStorageAcl extends Core_A
 				`A_CLASSIFIED` varchar(100) NOT NULL DEFAULT 'N/S;',
 				`L_APPOITMENT_USER` varchar(100) NOT NULL DEFAULT 'N/S;',
 				`KWOTA` varchar(16) NOT NULL DEFAULT 'N/S;',
-        `UWAGI` varchar(255) NOT NULL DEFAULT 'N/S;',
-        `APPROVED_BY` varchar(255) NOT NULL DEFAULT 'N/S;',
+				`UWAGI` varchar(255) NOT NULL DEFAULT 'N/S;',
+				`APPROVED_BY` varchar(255) NOT NULL DEFAULT 'N/S;',
 				PRIMARY KEY (`ID`),
-			  KEY `ID_USERS2` (`ID_USERS2`)
-			) ENGINE=MyISAM  DEFAULT CHARSET=latin2;
+				KEY `ID_USERS2` (`ID_USERS2`)
+			) ENGINE=MyISAM	DEFAULT CHARSET=latin2;
 		");
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_WNIOSEK` ADD `APPROVED_BY` varchar(255) NOT NULL DEFAULT '' ");
-    } catch (Exception $e) { DBG::log($e); }
-    try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_WNIOSEK_HIST` ADD `APPROVED_BY` varchar(255) NOT NULL DEFAULT 'N/S;' ");
-    } catch (Exception $e) { DBG::log($e); }
-  }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_WNIOSEK` ADD `APPROVED_BY` varchar(255) NOT NULL DEFAULT '' ");
+		} catch (Exception $e) { DBG::log($e); }
+		try { DB::getPDO()->execSql(" ALTER TABLE `ZALICZKA_WNIOSEK_HIST` ADD `APPROVED_BY` varchar(255) NOT NULL DEFAULT 'N/S;' ");
+		} catch (Exception $e) { DBG::log($e); }
+	}
 
 }

+ 222 - 222
SE/se-lib/Schema/FileStorageAcl.php

@@ -5,254 +5,254 @@ Lib::loadClass('FileStorage');
 
 class Schema_FileStorageAcl extends Core_AclBase {
 
-  public function __construct() {}
-  public function getNamespace() { return 'default_objects/' . $this->getName(); }
-  public function getSourceName() { return 'default_objects'; }
-  public function init($force = false) {}
-  public function isInitialized() { return true; }
-  public function getName() { return 'File'; }
-  public function getRootTableName() { return 'CRM_FILES'; }
-  public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
-  public function getVisibleFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
-  public function getVirtualFieldListByIdZasob() { return array(); }
-  public function getRealFieldListByIdZasob() {
-    $cols = array();// FileStorage::getFileById()
-    $cols[1] = 'id';
-    $cols[2] = 'name';
-    $cols[3] = 'size';
-    $cols[4] = 'mimeType';
-    $cols[5] = 'version';
-    $cols[6] = 'content';
-    // $cols[] = 'relativePath';
-    // $cols[] = 'absolutePath';
-    // $cols[] = 'exists';
-    return $cols;
-  }
-  public function getFields() {// @returns array - $this->_fields
-    $fields[1] = ['name'=>'id', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>999];
-    $fields[2] = ['name'=>'name', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>999];
-    $fields[3] = ['name'=>'size', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>999];
-    $fields[4] = ['name'=>'mimeType', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>999];
-    $fields[5] = ['name'=>'version', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>999];
-    $fields[6] = ['name'=>'content', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>999];
-    return $fields;
-  }
-  public function getFieldIdByName($fieldName) {
-    $fields = $this->getRealFieldListByIdZasob();
+	public function __construct() {}
+	public function getNamespace() { return 'default_objects/' . $this->getName(); }
+	public function getSourceName() { return 'default_objects'; }
+	public function init($force = false) {}
+	public function isInitialized() { return true; }
+	public function getName() { return 'File'; }
+	public function getRootTableName() { return 'CRM_FILES'; }
+	public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
+	public function getVisibleFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
+	public function getVirtualFieldListByIdZasob() { return array(); }
+	public function getRealFieldListByIdZasob() {
+		$cols = array();// FileStorage::getFileById()
+		$cols[1] = 'id';
+		$cols[2] = 'name';
+		$cols[3] = 'size';
+		$cols[4] = 'mimeType';
+		$cols[5] = 'version';
+		$cols[6] = 'content';
+		// $cols[] = 'relativePath';
+		// $cols[] = 'absolutePath';
+		// $cols[] = 'exists';
+		return $cols;
+	}
+	public function getFields() {// @returns array - $this->_fields
+		$fields[1] = ['name'=>'id', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>999];
+		$fields[2] = ['name'=>'name', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>999];
+		$fields[3] = ['name'=>'size', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>999];
+		$fields[4] = ['name'=>'mimeType', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>999];
+		$fields[5] = ['name'=>'version', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>999];
+		$fields[6] = ['name'=>'content', 'perms'=>'R', 'opis'=>'', 'label'=>'', 'sort_prio'=>999];
+		return $fields;
+	}
+	public function getFieldIdByName($fieldName) {
+		$fields = $this->getRealFieldListByIdZasob();
 		if (empty($fieldName)) return null;
 		foreach ($fields as $idField => $vFieldName) {
 			if ($vFieldName == $fieldName) return $idField;
 		}
 		return null;
 	}
-  public function isDecimalField($fieldName) { return false; }
+	public function isDecimalField($fieldName) { return false; }
 	public function isGeomField($fieldName) { return false; }
 	public function isDateField($fieldName) { return false; }
 	public function isDateTimeField($fieldName) { return false; }
 	public function isStringField($fieldName) {
-    if ('name' == $fieldName) return true;
-    if ('mimeType' == $fieldName) return true;
-    return false;
-  }
+		if ('name' == $fieldName) return true;
+		if ('mimeType' == $fieldName) return true;
+		return false;
+	}
 	public function isTextField($fieldName) { return false; }
-  public function isBinaryField($fieldName) {
-    if ('content' == $fieldName) return true;
-    return false;
-  }
+	public function isBinaryField($fieldName) {
+		if ('content' == $fieldName) return true;
+		return false;
+	}
 	public function isEnumerationField($fieldName) { return false; }
-  public function getFieldType($fieldName) {
-    switch ($fieldName) {
-      case 'id': return ['name'=>'id', 'type'=>'int']; break;
-      case 'name': return ['name'=>'name', 'type'=>'string']; break;
-    }
-    return null;
+	public function getFieldType($fieldName) {
+		switch ($fieldName) {
+			case 'id': return ['name'=>'id', 'type'=>'int']; break;
+			case 'name': return ['name'=>'name', 'type'=>'string']; break;
+		}
+		return null;
+	}
+	public function isAllowed($idZasob, $taskPerm, $record = null) {
+		if ('C' == $taskPerm && $idZasob > 1 && $idZasob < 7) return true;
+		if ('R' == $taskPerm && $idZasob > 0 && $idZasob < 7) return true;
+		return false;
+	}
+	public function hasFieldPerm($idZasob, $taskPerm) {
+		if ('C' == $taskPerm && $idZasob > 1 && $idZasob < 7) return true;
+		if ('R' == $taskPerm && $idZasob > 0 && $idZasob < 7) return true;
+		return false;
 	}
-  public function isAllowed($idZasob, $taskPerm, $record = null) {
-    if ('C' == $taskPerm && $idZasob > 1 && $idZasob < 7) return true;
-    if ('R' == $taskPerm && $idZasob > 0 && $idZasob < 7) return true;
-    return false;
-  }
-  public function hasFieldPerm($idZasob, $taskPerm) {
-    if ('C' == $taskPerm && $idZasob > 1 && $idZasob < 7) return true;
-    if ('R' == $taskPerm && $idZasob > 0 && $idZasob < 7) return true;
-    return false;
-  }
 
-  // TODO: replace legacy functions: isAllowed, hasFieldPerm, getFieldIdByName
-  public function canCreateField($fieldName) {
-    $fields = $this->getRealFieldListByIdZasob();
-    if (!in_array($fieldName, $fields)) return false;
-    return true;
-  }
-  public function canReadField($fieldName) {
-    $fields = $this->getRealFieldListByIdZasob();
-    if (!in_array($fieldName, $fields)) return false;
-    return true;
-  }
-  public function canReadObjectField($fieldName, $record) {
-    return $this->canReadField($fieldName);
-  }
-  public function canWriteField($fieldName) {
-    $fields = $this->getRealFieldListByIdZasob();
-    if (!in_array($fieldName, $fields)) return false;
-    return true;
-  }
-  public function canWriteObjectField($fieldName, $record) {
-    return $this->canWriteField($fieldName);
-  }
+	// TODO: replace legacy functions: isAllowed, hasFieldPerm, getFieldIdByName
+	public function canCreateField($fieldName) {
+		$fields = $this->getRealFieldListByIdZasob();
+		if (!in_array($fieldName, $fields)) return false;
+		return true;
+	}
+	public function canReadField($fieldName) {
+		$fields = $this->getRealFieldListByIdZasob();
+		if (!in_array($fieldName, $fields)) return false;
+		return true;
+	}
+	public function canReadObjectField($fieldName, $record) {
+		return $this->canReadField($fieldName);
+	}
+	public function canWriteField($fieldName) {
+		$fields = $this->getRealFieldListByIdZasob();
+		if (!in_array($fieldName, $fields)) return false;
+		return true;
+	}
+	public function canWriteObjectField($fieldName, $record) {
+		return $this->canWriteField($fieldName);
+	}
 
-  public function getTotal($params = array()) {// TODO: use ParseOgcQuery
-    $sqlLimit = V::get('limit', 10000, $params);
-    $sqlOffset = V::get('limitstart', 0, $params);
-    // TODO: parse params:
-    //   [sortBy] => ID D,test_date A
-    //   [cols] => Array( [0] => ID
-    //                    [1] => test_date
-    //                    [2] => A_STATUS )
-    //   [ogc:Filter] => "<ogc:Filter><ogc:PropertyIsEqualTo><ogc:PropertyName>id</ogc:PropertyName><ogc:Literal>35</ogc:Literal></ogc:Filter>"
-    $sqlWhereAddOgcFilter = '';
-    $ogcFilter = V::get('ogc:Filter', '', $params);
-    if (!empty($ogcFilter)) {
-      Lib::loadClass('ParseOgcFilter');
-      $parser = new ParseOgcFilter();
-      $parser->loadOgcFilter($ogcFilter);
-      $queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
-      $usedFields = $queryWhereBuilder->getUsedFields();
-      foreach ($usedFields as $fieldName) {
-        if (!$this->getFieldIdByName($fieldName)) throw new Exception("Not allowed PropertyName '{$fieldName}'");
-      }
-      $sqlWhereAddOgcFilter = $queryWhereBuilder->getQueryWhere('t');
-      if (!empty($sqlWhereAddOgcFilter)) $sqlWhereAddOgcFilter = " and {$sqlWhereAddOgcFilter}";
-      DBG::_('DBG_DS', '>1', "ogc:Filter parser", $parser, __CLASS__, __FUNCTION__, __LINE__);
-      DBG::_('DBG_DS', '>1', "ogc:Filter queryWhereBuilder", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
-      DBG::_('DBG_DS', '>1', "ogc:Filter usedFields", $usedFields, __CLASS__, __FUNCTION__, __LINE__);
-      DBG::_('DBG_DS', '>1', "ogc:Filter sqlWhereAddOgcFilter", $sqlWhereAddOgcFilter, __CLASS__, __FUNCTION__, __LINE__);
-    }
-    $sqlTblName = FileStorage::getTableName();
-    $sqlUserLogin = User::getLogin();
-    $sqlWhere = "1=1";
-    // $sqlWhere .= " and t.`A_RECORD_CREATE_AUTHOR` = '{$sqlUserLogin}' ";// TODO: Acl to read file
-    $sqlWhere .= $sqlWhereAddOgcFilter;
-    if ($pk = V::get('primaryKey', 0, $params, 'int')) $sqlWhere .= " and t.`ID` = {$pk} ";
-    return DB::getPDO()->fetchValue("
-    	select count(1) as total
-    	from `{$sqlTblName}` t
-      where {$sqlWhere}
-    ");
-  }
+	public function getTotal($params = array()) {// TODO: use ParseOgcQuery
+		$sqlLimit = V::get('limit', 10000, $params);
+		$sqlOffset = V::get('limitstart', 0, $params);
+		// TODO: parse params:
+		//	 [sortBy] => ID D,test_date A
+		//	 [cols] => Array( [0] => ID
+		//										[1] => test_date
+		//										[2] => A_STATUS )
+		//	 [ogc:Filter] => "<ogc:Filter><ogc:PropertyIsEqualTo><ogc:PropertyName>id</ogc:PropertyName><ogc:Literal>35</ogc:Literal></ogc:Filter>"
+		$sqlWhereAddOgcFilter = '';
+		$ogcFilter = V::get('ogc:Filter', '', $params);
+		if (!empty($ogcFilter)) {
+			Lib::loadClass('ParseOgcFilter');
+			$parser = new ParseOgcFilter();
+			$parser->loadOgcFilter($ogcFilter);
+			$queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
+			$usedFields = $queryWhereBuilder->getUsedFields();
+			foreach ($usedFields as $fieldName) {
+				if (!$this->getFieldIdByName($fieldName)) throw new Exception("Not allowed PropertyName '{$fieldName}'");
+			}
+			$sqlWhereAddOgcFilter = $queryWhereBuilder->getQueryWhere('t');
+			if (!empty($sqlWhereAddOgcFilter)) $sqlWhereAddOgcFilter = " and {$sqlWhereAddOgcFilter}";
+			DBG::_('DBG_DS', '>1', "ogc:Filter parser", $parser, __CLASS__, __FUNCTION__, __LINE__);
+			DBG::_('DBG_DS', '>1', "ogc:Filter queryWhereBuilder", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
+			DBG::_('DBG_DS', '>1', "ogc:Filter usedFields", $usedFields, __CLASS__, __FUNCTION__, __LINE__);
+			DBG::_('DBG_DS', '>1', "ogc:Filter sqlWhereAddOgcFilter", $sqlWhereAddOgcFilter, __CLASS__, __FUNCTION__, __LINE__);
+		}
+		$sqlTblName = FileStorage::getTableName();
+		$sqlUserLogin = User::getLogin();
+		$sqlWhere = "1=1";
+		// $sqlWhere .= " and t.`A_RECORD_CREATE_AUTHOR` = '{$sqlUserLogin}' ";// TODO: Acl to read file
+		$sqlWhere .= $sqlWhereAddOgcFilter;
+		if ($pk = V::get('primaryKey', 0, $params, 'int')) $sqlWhere .= " and t.`ID` = {$pk} ";
+		return DB::getPDO()->fetchValue("
+			select count(1) as total
+			from `{$sqlTblName}` t
+			where {$sqlWhere}
+		");
+	}
 
-  public function getItem($primaryKey, $params = []) {
-    $items = $this->getItems(['primaryKey'=>$primaryKey]);
-    return (!empty($items[$primaryKey])) ? $items[$primaryKey] : null;
-  }
-  public function getItems($params = array()) {// TODO: use ParseOgcQuery
-    $sqlLimit = V::get('limit', 10000, $params);
-    $sqlOffset = V::get('limitstart', 0, $params);
-    // TODO: parse params:
-    //   [sortBy] => ID D,test_date A
-    //   [cols] => Array( [0] => ID
-    //                    [1] => test_date
-    //                    [2] => A_STATUS )
-    //   [ogc:Filter] => "<ogc:Filter><ogc:PropertyIsEqualTo><ogc:PropertyName>id</ogc:PropertyName><ogc:Literal>35</ogc:Literal></ogc:Filter>"
-    $sqlWhereAddOgcFilter = '';
-    $ogcFilter = V::get('ogc:Filter', '', $params);
-    if (!empty($ogcFilter)) {
-      Lib::loadClass('ParseOgcFilter');
-      $parser = new ParseOgcFilter();
-      $parser->loadOgcFilter($ogcFilter);
-      $queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
-      $usedFields = $queryWhereBuilder->getUsedFields();
-      foreach ($usedFields as $fieldName) {
-        if (!$this->getFieldIdByName($fieldName)) throw new Exception("Not allowed PropertyName '{$fieldName}'");
-      }
-      $sqlWhereAddOgcFilter = $queryWhereBuilder->getQueryWhere('t');
-      if (!empty($sqlWhereAddOgcFilter)) $sqlWhereAddOgcFilter = " and {$sqlWhereAddOgcFilter}";
-      DBG::_('DBG_DS', '>1', "ogc:Filter parser", $parser, __CLASS__, __FUNCTION__, __LINE__);
-      DBG::_('DBG_DS', '>1', "ogc:Filter queryWhereBuilder", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
-      DBG::_('DBG_DS', '>1', "ogc:Filter usedFields", $usedFields, __CLASS__, __FUNCTION__, __LINE__);
-      DBG::_('DBG_DS', '>1', "ogc:Filter sqlWhereAddOgcFilter", $sqlWhereAddOgcFilter, __CLASS__, __FUNCTION__, __LINE__);
-    }
+	public function getItem($primaryKey, $params = []) {
+		$items = $this->getItems(['primaryKey'=>$primaryKey]);
+		return (!empty($items[$primaryKey])) ? $items[$primaryKey] : null;
+	}
+	public function getItems($params = array()) {// TODO: use ParseOgcQuery
+		$sqlLimit = V::get('limit', 10000, $params);
+		$sqlOffset = V::get('limitstart', 0, $params);
+		// TODO: parse params:
+		//	 [sortBy] => ID D,test_date A
+		//	 [cols] => Array( [0] => ID
+		//										[1] => test_date
+		//										[2] => A_STATUS )
+		//	 [ogc:Filter] => "<ogc:Filter><ogc:PropertyIsEqualTo><ogc:PropertyName>id</ogc:PropertyName><ogc:Literal>35</ogc:Literal></ogc:Filter>"
+		$sqlWhereAddOgcFilter = '';
+		$ogcFilter = V::get('ogc:Filter', '', $params);
+		if (!empty($ogcFilter)) {
+			Lib::loadClass('ParseOgcFilter');
+			$parser = new ParseOgcFilter();
+			$parser->loadOgcFilter($ogcFilter);
+			$queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
+			$usedFields = $queryWhereBuilder->getUsedFields();
+			foreach ($usedFields as $fieldName) {
+				if (!$this->getFieldIdByName($fieldName)) throw new Exception("Not allowed PropertyName '{$fieldName}'");
+			}
+			$sqlWhereAddOgcFilter = $queryWhereBuilder->getQueryWhere('t');
+			if (!empty($sqlWhereAddOgcFilter)) $sqlWhereAddOgcFilter = " and {$sqlWhereAddOgcFilter}";
+			DBG::_('DBG_DS', '>1', "ogc:Filter parser", $parser, __CLASS__, __FUNCTION__, __LINE__);
+			DBG::_('DBG_DS', '>1', "ogc:Filter queryWhereBuilder", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
+			DBG::_('DBG_DS', '>1', "ogc:Filter usedFields", $usedFields, __CLASS__, __FUNCTION__, __LINE__);
+			DBG::_('DBG_DS', '>1', "ogc:Filter sqlWhereAddOgcFilter", $sqlWhereAddOgcFilter, __CLASS__, __FUNCTION__, __LINE__);
+		}
 
-    $sqlTblName = FileStorage::getTableName();
-    $sqlUserLogin = User::getLogin();
-    $sqlWhere = "1=1";
-    // $sqlWhere .= " and t.`A_RECORD_CREATE_AUTHOR` = '{$sqlUserLogin}' ";// TODO: Acl to read file
-    $sqlWhere .= $sqlWhereAddOgcFilter;
-    if ($pk = V::get('primaryKey', 0, $params, 'int')) $sqlWhere .= " and t.`ID` = {$pk} ";
-    $rows = array_map(function($row) {
-      $wfsItem = array();
-      $wfsItem['id'] = $row['ID'];
-      $wfsItem['name'] = V::get('FILE_LABEL', $row['ID'], $row);
-      $wfsItem['size'] = $row['FILE_SIZE'];
-      $wfsItem['mimeType'] = $row['FILE_MIME_TYPE'];
-      $wfsItem['version'] = $row['FILE_VERSION'];
-      {// fetch file content
-        $objectFile = FileStorage::getFileById($row['ID']);// TODO: avoid sql in FileStorage::convertFromDBRow($row)
-        $wfsItem['content'] = ($objectFile['exists']) ? base64_encode(file_get_contents($objectFile['absolutePath'])) : null;
-      }
-    	return $wfsItem;
-    }, DB::getPDO()->fetchAll("
-    	select t.ID
-    		, t.FILE_HASH
-    		, t.FILE_LABEL
-    		, t.FILE_TYPE
-    		, t.FILE_MIME_TYPE
-    		, t.FILE_MTIME
-    		, t.FILE_SIZE
-    		, t.FILE_VERSION
-    		, t.A_STATUS
-    		, t.A_RECORD_CREATE_DATE
-    		, t.A_RECORD_CREATE_AUTHOR
-    		, t.A_RECORD_UPDATE_DATE
-    		, t.A_RECORD_UPDATE_AUTHOR
-    		, t.A_ADM_COMPANY
-    		, t.A_CLASSIFIED
-    		, INET_NTOA(t.A_USER_IP) as IP
-    	from `{$sqlTblName}` t
-      where {$sqlWhere}
-    	order by ID DESC
-    	limit {$sqlLimit} offset {$sqlOffset}
-    "));
-    $items = array();
-    foreach ($rows as $row) {
-      $items[$row['id']] = (object)$row;
-    }
-    return $items;
-  }
-  public function addItem($itemTodo) {
-    if (is_object($itemTodo)) {
+		$sqlTblName = FileStorage::getTableName();
+		$sqlUserLogin = User::getLogin();
+		$sqlWhere = "1=1";
+		// $sqlWhere .= " and t.`A_RECORD_CREATE_AUTHOR` = '{$sqlUserLogin}' ";// TODO: Acl to read file
+		$sqlWhere .= $sqlWhereAddOgcFilter;
+		if ($pk = V::get('primaryKey', 0, $params, 'int')) $sqlWhere .= " and t.`ID` = {$pk} ";
+		$rows = array_map(function($row) {
+			$wfsItem = array();
+			$wfsItem['id'] = $row['ID'];
+			$wfsItem['name'] = V::get('FILE_LABEL', $row['ID'], $row);
+			$wfsItem['size'] = $row['FILE_SIZE'];
+			$wfsItem['mimeType'] = $row['FILE_MIME_TYPE'];
+			$wfsItem['version'] = $row['FILE_VERSION'];
+			{// fetch file content
+				$objectFile = FileStorage::getFileById($row['ID']);// TODO: avoid sql in FileStorage::convertFromDBRow($row)
+				$wfsItem['content'] = ($objectFile['exists']) ? base64_encode(file_get_contents($objectFile['absolutePath'])) : null;
+			}
+			return $wfsItem;
+		}, DB::getPDO()->fetchAll("
+			select t.ID
+				, t.FILE_HASH
+				, t.FILE_LABEL
+				, t.FILE_TYPE
+				, t.FILE_MIME_TYPE
+				, t.FILE_MTIME
+				, t.FILE_SIZE
+				, t.FILE_VERSION
+				, t.A_STATUS
+				, t.A_RECORD_CREATE_DATE
+				, t.A_RECORD_CREATE_AUTHOR
+				, t.A_RECORD_UPDATE_DATE
+				, t.A_RECORD_UPDATE_AUTHOR
+				, t.A_ADM_COMPANY
+				, t.A_CLASSIFIED
+				, INET_NTOA(t.A_USER_IP) as IP
+			from `{$sqlTblName}` t
+			where {$sqlWhere}
+			order by ID DESC
+			limit {$sqlLimit} offset {$sqlOffset}
+		"));
+		$items = array();
+		foreach ($rows as $row) {
+			$items[$row['id']] = (object)$row;
+		}
+		return $items;
+	}
+	public function addItem($itemTodo) {
+		if (is_object($itemTodo)) {
 			$itemTodo = (array)$itemTodo;
 		}
-    if (!is_array($itemTodo)) throw new HttpException('Item is not array', 400);
+		if (!is_array($itemTodo)) throw new HttpException('Item is not array', 400);
 		if (empty($itemTodo)) {
 			DBG::_('DBG_DS', '>2', "Item patch is empty", null, __CLASS__, __FUNCTION__, __LINE__);
 			return 0;// nothing to insert
 		}
-    if (empty($itemTodo['content'])) throw new Exception("Empty file content");
-    $fileName = V::get('name', '', $itemTodo);
-    $binaryContent = base64_decode($itemTodo['content']);
-    return FileStorage::addFile($binaryContent, $fileName);
-  }
+		if (empty($itemTodo['content'])) throw new Exception("Empty file content");
+		$fileName = V::get('name', '', $itemTodo);
+		$binaryContent = base64_decode($itemTodo['content']);
+		return FileStorage::addFile($binaryContent, $fileName);
+	}
 
-  public function getGeomFieldType($fieldName) { return null; }
-  public function getPrimaryKeyField() { return 'id'; }
-  public function getAttributesFromZasoby() {
+	public function getGeomFieldType($fieldName) { return null; }
+	public function getPrimaryKeyField() { return 'id'; }
+	public function getAttributesFromZasoby() {
 		$attributes = array();// fldName => [ 'id_zasob' => int, 'label' => str, 'description' => str ]
-    // if ($acl->hasFieldPerm($idZasob, 'W')) $elNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_write", "true");
-    // if ($acl->hasFieldPerm($idZasob, 'C')) $elNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_create", "true");
-    // if (!$acl->hasFieldPerm($idZasob, 'R')) $elNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_read", "false");
+		// if ($acl->hasFieldPerm($idZasob, 'W')) $elNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_write", "true");
+		// if ($acl->hasFieldPerm($idZasob, 'C')) $elNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_create", "true");
+		// if (!$acl->hasFieldPerm($idZasob, 'R')) $elNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_read", "false");
 		return $attributes;
 	}
-  public function getXsdFieldType($fieldName) {
-    switch ($fieldName) {
-      case 'id': return 'xsd:integer';
-      case 'name': return 'xsd:string';
-      case 'size': return 'xsd:integer';
-      case 'mimeType': return 'xsd:string';
-      case 'version': return 'xsd:integer';
-      case 'content': return 'xsd:base64Binary';
-      default: throw new HttpException("Error field not exists '{$fieldName}'", 404);
-    }
-  }
+	public function getXsdFieldType($fieldName) {
+		switch ($fieldName) {
+			case 'id': return 'xsd:integer';
+			case 'name': return 'xsd:string';
+			case 'size': return 'xsd:integer';
+			case 'mimeType': return 'xsd:string';
+			case 'version': return 'xsd:integer';
+			case 'content': return 'xsd:base64Binary';
+			default: throw new HttpException("Error field not exists '{$fieldName}'", 404);
+		}
+	}
 
 }

+ 98 - 98
SE/se-lib/Schema/KorespondencjaStorageAcl.php

@@ -6,115 +6,115 @@ Lib::loadClass('FileStorage');
 
 class Schema_KorespondencjaStorageAcl extends Core_AclBase {
 
-  public function __construct() {
-    $this->parentAcl = User::getAcl()->getObjectAcl('default_db', 'IN7_DZIENNIK_KORESP');
-    // DBG::_(true, true, "parentAcl", $this->parentAcl, __CLASS__, __FUNCTION__, __LINE__);
-  }
-  public function getNamespace() { return 'default_objects/' . $this->getName(); }
-  public function getSourceName() { return 'default_objects'; }
-  public function init($force = false) {}
-  public function isInitialized() { return true; }
-  public function getName() { return 'Korespondencja'; }
-  public function getRootTableName() { return 'IN7_DZIENNIK_KORESP'; }
-  public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
-  public function getVisibleFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
-  public function getVirtualFieldListByIdZasob() { return array(); }
-  public function getRealFieldListByIdZasob($force = false) {
-    $cols = $this->parentAcl->getRealFieldListByIdZasob();
-    $cols[100000] = 'File';
-    return $cols;
-  }
-  public function getFieldIdByName($fieldName) {
-    $fields = $this->getRealFieldListByIdZasob();
+	public function __construct() {
+		$this->parentAcl = User::getAcl()->getObjectAcl('default_db', 'IN7_DZIENNIK_KORESP');
+		// DBG::_(true, true, "parentAcl", $this->parentAcl, __CLASS__, __FUNCTION__, __LINE__);
+	}
+	public function getNamespace() { return 'default_objects/' . $this->getName(); }
+	public function getSourceName() { return 'default_objects'; }
+	public function init($force = false) {}
+	public function isInitialized() { return true; }
+	public function getName() { return 'Korespondencja'; }
+	public function getRootTableName() { return 'IN7_DZIENNIK_KORESP'; }
+	public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
+	public function getVisibleFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
+	public function getVirtualFieldListByIdZasob() { return array(); }
+	public function getRealFieldListByIdZasob($force = false) {
+		$cols = $this->parentAcl->getRealFieldListByIdZasob();
+		$cols[100000] = 'File';
+		return $cols;
+	}
+	public function getFieldIdByName($fieldName) {
+		$fields = $this->getRealFieldListByIdZasob();
 		if (empty($fieldName)) return null;
 		foreach ($fields as $idField => $vFieldName) {
 			if ($vFieldName == $fieldName) return $idField;
 		}
 		return null;
 	}
-  public function getFieldType($colName) { return null; }
-  public function isAllowed($idZasob, $taskPerm, $record = null) {
-    if ($this->parentAcl->hasFieldById($idZasob)) return $this->parentAcl->isAllowed($idZasob, $taskPerm, $record);
-    $fields = $this->getRealFieldListByIdZasob();
-    if (array_key_exists($idZasob, $fields)) {
-      if ('File' == $fields[$idZasob]) {
-        foreach ($fields as $idFld => $name) {
-          if ($idFld == $idZasob) continue;
-          if ($this->parentAcl->isAllowed($idFld, $taskPerm, $record)) return true;
-        }
-      }
-    }
-    return false;
-  }
-  public function hasFieldPerm($idZasob, $taskPerm) {
-    if ($this->parentAcl->hasFieldById($idZasob)) return $this->parentAcl->hasFieldPerm($idZasob, $taskPerm);
-    $fields = $this->getRealFieldListByIdZasob();
-    if (array_key_exists($idZasob, $fields)) {
-      if ('File' == $fields[$idZasob]) {
-        foreach ($fields as $idFld => $name) {
-          if ($idFld == $idZasob) continue;
-          if ($this->parentAcl->hasFieldPerm($idFld, $taskPerm)) return true;
-        }
-      }
-    }
-    return false;
-  }
+	public function getFieldType($colName) { return null; }
+	public function isAllowed($idZasob, $taskPerm, $record = null) {
+		if ($this->parentAcl->hasFieldById($idZasob)) return $this->parentAcl->isAllowed($idZasob, $taskPerm, $record);
+		$fields = $this->getRealFieldListByIdZasob();
+		if (array_key_exists($idZasob, $fields)) {
+			if ('File' == $fields[$idZasob]) {
+				foreach ($fields as $idFld => $name) {
+					if ($idFld == $idZasob) continue;
+					if ($this->parentAcl->isAllowed($idFld, $taskPerm, $record)) return true;
+				}
+			}
+		}
+		return false;
+	}
+	public function hasFieldPerm($idZasob, $taskPerm) {
+		if ($this->parentAcl->hasFieldById($idZasob)) return $this->parentAcl->hasFieldPerm($idZasob, $taskPerm);
+		$fields = $this->getRealFieldListByIdZasob();
+		if (array_key_exists($idZasob, $fields)) {
+			if ('File' == $fields[$idZasob]) {
+				foreach ($fields as $idFld => $name) {
+					if ($idFld == $idZasob) continue;
+					if ($this->parentAcl->hasFieldPerm($idFld, $taskPerm)) return true;
+				}
+			}
+		}
+		return false;
+	}
 
-  // TODO: replace legacy functions: isAllowed, hasFieldPerm, getFieldIdByName
-  public function canCreateField($fieldName) {
-    if ('File' == $fieldName) return true;
-    return $this->parentAcl->canCreateField($fieldName);
-  }
-  public function canReadField($fieldName) {
-    if ('File' == $fieldName) return true;
-    return $this->parentAcl->canReadField($fieldName);
-  }
-  public function canReadObjectField($fieldName, $record) {
-    if ('File' == $fieldName) return true;
-    return $this->parentAcl->canReadObjectField($fieldName, $record);
-  }
-  public function canWriteField($fieldName) {
-    if ('File' == $fieldName) return true;
-    return $this->parentAcl->canWriteField($fieldName);
-  }
-  public function canWriteObjectField($fieldName, $record) {
-    if ('File' == $fieldName) return true;
-    return $this->parentAcl->canWriteObjectField($fieldName, $record);
-  }
+	// TODO: replace legacy functions: isAllowed, hasFieldPerm, getFieldIdByName
+	public function canCreateField($fieldName) {
+		if ('File' == $fieldName) return true;
+		return $this->parentAcl->canCreateField($fieldName);
+	}
+	public function canReadField($fieldName) {
+		if ('File' == $fieldName) return true;
+		return $this->parentAcl->canReadField($fieldName);
+	}
+	public function canReadObjectField($fieldName, $record) {
+		if ('File' == $fieldName) return true;
+		return $this->parentAcl->canReadObjectField($fieldName, $record);
+	}
+	public function canWriteField($fieldName) {
+		if ('File' == $fieldName) return true;
+		return $this->parentAcl->canWriteField($fieldName);
+	}
+	public function canWriteObjectField($fieldName, $record) {
+		if ('File' == $fieldName) return true;
+		return $this->parentAcl->canWriteObjectField($fieldName, $record);
+	}
 
-  public function getItems($params = array()) {
-    $DBG = V::get('DBG_DS', 0, $_GET, 'int');
-    if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$params:";print_r($params);echo "\n";}
-    $items = array();
-    $rawItems = $this->parentAcl->getItems($params);
-    foreach ($rawItems as $pk => $item) $items[$pk] = (array)$item;
-    if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$items:";print_r($items);echo "\n";}
-    if (empty($items)) return $items;
-    $this->itemsFetchRefs($items);
-    if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems after itemsFetchRefs \$items:";print_r($items);echo "\n";}
-    return $items;
-  }
-  public function addItem($itemTodo) {
-    return $this->parentAcl->addItem($itemTodo);
-  }
-  public function updateItem($itemPatch) {
-    return $this->parentAcl->updateItem($itemPatch);
-  }
+	public function getItems($params = array()) {
+		$DBG = V::get('DBG_DS', 0, $_GET, 'int');
+		if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$params:";print_r($params);echo "\n";}
+		$items = array();
+		$rawItems = $this->parentAcl->getItems($params);
+		foreach ($rawItems as $pk => $item) $items[$pk] = (array)$item;
+		if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$items:";print_r($items);echo "\n";}
+		if (empty($items)) return $items;
+		$this->itemsFetchRefs($items);
+		if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems after itemsFetchRefs \$items:";print_r($items);echo "\n";}
+		return $items;
+	}
+	public function addItem($itemTodo) {
+		return $this->parentAcl->addItem($itemTodo);
+	}
+	public function updateItem($itemPatch) {
+		return $this->parentAcl->updateItem($itemPatch);
+	}
 
-  public function getGeomFieldType($fieldName) { return null; }
-  public function getPrimaryKeyField() { return 'ID'; }
-  public function getAttributesFromZasoby() {
+	public function getGeomFieldType($fieldName) { return null; }
+	public function getPrimaryKeyField() { return 'ID'; }
+	public function getAttributesFromZasoby() {
 		$attributes = array();// fldName => [ 'id_zasob' => int, 'label' => str, 'description' => str ]
-    // if ($acl->hasFieldPerm($idZasob, 'W')) $elNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_write", "true");
-    // if ($acl->hasFieldPerm($idZasob, 'C')) $elNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_create", "true");
-    // if (!$acl->hasFieldPerm($idZasob, 'R')) $elNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_read", "false");
+		// if ($acl->hasFieldPerm($idZasob, 'W')) $elNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_write", "true");
+		// if ($acl->hasFieldPerm($idZasob, 'C')) $elNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_create", "true");
+		// if (!$acl->hasFieldPerm($idZasob, 'R')) $elNode->setAttributeNS($rootWfsNsUri, "{$rootWfsNs}:allow_read", "false");
 		return $attributes;
 	}
-  public function isEnumerationField($fieldName) { return false; }
-  public function getXsdFieldType($fieldName) {
-    if ('File' == $fieldName) return 'ref:default_objects:File';
-    return $this->parentAcl->getXsdFieldType($fieldName);
-  }
-  public function isGeomField($fldName) { return $this->parentAcl->isGeomField($fldName); }
+	public function isEnumerationField($fieldName) { return false; }
+	public function getXsdFieldType($fieldName) {
+		if ('File' == $fieldName) return 'ref:default_objects:File';
+		return $this->parentAcl->getXsdFieldType($fieldName);
+	}
+	public function isGeomField($fldName) { return $this->parentAcl->isGeomField($fldName); }
 
 }

+ 71 - 71
SE/se-lib/Schema/SystemFunctionStorageAcl.php

@@ -5,85 +5,85 @@ Lib::loadClass('ParseOgcFilter');
 
 class Schema_SystemFunctionStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_objects/SystemFunction',
-      '@primaryKey' => 'name',
-      'name' => [ '@type' => 'xsd:string' ],
-      'description' => [ '@type' => 'xsd:string', '@label' => "Opis" ],
-      'param' => [ '@type' => 'xsd:string', '@label' => "Parametry", '@macOccurs' => 'unbounded' ],
-      // 'autor' => [ '@type' => 'xsd:string' ],
-      // 'utworzono' => [ '@type' => 'xsd:date' ],
-      // 'zaktualizował' => [ '@type' => 'xsd:string' ],
-      // 'zaktualizowano' => [ '@type' => 'xsd:date' ]
-    ]
-  ];
-  public $_rootTableName = 'CRM_LISTA_ZASOBOW';
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_objects/SystemFunction',
+			'@primaryKey' => 'name',
+			'name' => [ '@type' => 'xsd:string' ],
+			'description' => [ '@type' => 'xsd:string', '@label' => "Opis" ],
+			'param' => [ '@type' => 'xsd:string', '@label' => "Parametry", '@macOccurs' => 'unbounded' ],
+			// 'autor' => [ '@type' => 'xsd:string' ],
+			// 'utworzono' => [ '@type' => 'xsd:date' ],
+			// 'zaktualizował' => [ '@type' => 'xsd:string' ],
+			// 'zaktualizowano' => [ '@type' => 'xsd:date' ]
+		]
+	];
+	public $_rootTableName = 'CRM_LISTA_ZASOBOW';
 
-  public function getTotal($params = []) {
-    return count($this->_getAllItems());
-  }
+	public function getTotal($params = []) {
+		return count($this->_getAllItems());
+	}
 
-  public function getItems($params = []) {
-    $items = $this->_getAllItems();
-    $currSortCol = V::get('order_by', 'ID', $params);
-    $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
-    // TODO: validate $currSortCol is in field list
-    // TODO: validate $currSortFlip ('asc' or 'desc')
+	public function getItems($params = []) {
+		$items = $this->_getAllItems();
+		$currSortCol = V::get('order_by', 'ID', $params);
+		$currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
+		// TODO: validate $currSortCol is in field list
+		// TODO: validate $currSortFlip ('asc' or 'desc')
 
-    $aliasMap = array();
-    foreach ($this->_simpleSchema['root'] as $key => $field) {
-      if ('@' === substr($key, 0, 1)) continue;
-      $aliasMap[ $key ] = $key;// (!empty($field['@alias'])) ? $field['@alias'] : $key;
-    }
-    // TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
-    $currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
+		$aliasMap = array();
+		foreach ($this->_simpleSchema['root'] as $key => $field) {
+			if ('@' === substr($key, 0, 1)) continue;
+			$aliasMap[ $key ] = $key;// (!empty($field['@alias'])) ? $field['@alias'] : $key;
+		}
+		// TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
+		$currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
 
-    if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
-      usort($items, function ($itemA, $itemB) use ($currSortCol, $currSortFlip) {
-        $a = strtolower(V::get($currSortCol, '', $itemA));
-        $b = strtolower(V::get($currSortCol, '', $itemB));
+		if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
+			usort($items, function ($itemA, $itemB) use ($currSortCol, $currSortFlip) {
+				$a = strtolower(V::get($currSortCol, '', $itemA));
+				$b = strtolower(V::get($currSortCol, '', $itemB));
 
-        if ($a == $b) return 0;
-        else if ('asc' == $currSortFlip)  return ($a < $b) ? -1 : 1;
-        else if ('desc' == $currSortFlip) return ($a > $b) ? -1 : 1;
-        throw new Exception("BUG - Wrong sort param - order dir");
-      });
-    }
+				if ($a == $b) return 0;
+				else if ('asc' == $currSortFlip)	return ($a < $b) ? -1 : 1;
+				else if ('desc' == $currSortFlip) return ($a > $b) ? -1 : 1;
+				throw new Exception("BUG - Wrong sort param - order dir");
+			});
+		}
 
-    $limit = V::get('limit', 0, $params);
-    $limit = ($limit < 0) ? 0 : $limit;
-    $offset = V::get('limitstart', 0, $params);
-    $offset = ($offset < 0) ? 0 : $offset;
-    return array_slice($items, $offset, ($limit > 0) ? $limit : null, $preserve_keys = true);
-  }
+		$limit = V::get('limit', 0, $params);
+		$limit = ($limit < 0) ? 0 : $limit;
+		$offset = V::get('limitstart', 0, $params);
+		$offset = ($offset < 0) ? 0 : $offset;
+		return array_slice($items, $offset, ($limit > 0) ? $limit : null, $preserve_keys = true);
+	}
 
-  public function _getAllItems($params = []) {
-    static $_cacheAllItems = null;
-    if (null !== $_cacheAllItems) return $_cacheAllItems;
+	public function _getAllItems($params = []) {
+		static $_cacheAllItems = null;
+		if (null !== $_cacheAllItems) return $_cacheAllItems;
 
-    $_cacheAllItems = [];
-    $_cacheAllItems[] = [ 'name' => "Calendar", 'description' => "Calendar" ];
-    $_cacheAllItems[] = [ 'name' => "ProcesEditor", 'description' => "ProcesEditor" ];
-    $_cacheAllItems[] = [ 'name' => "ProcesView", 'description' => "ProcesView" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyKosztorys", 'description' => "ProjektyKosztorys" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyKosztyWstepnychRobot", 'description' => "ProjektyKosztyWstepnychRobot" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyOdbiorKosztorys", 'description' => "ProjektyOdbiorKosztorys" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyOfertaAdminKosztorys", 'description' => "ProjektyOfertaAdminKosztorys" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyOfertaKosztorys", 'description' => "ProjektyOfertaKosztorys" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyProNetMediaApproveZam", 'description' => "ProjektyProNetMediaApproveZam" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyProNetMediaBudget", 'description' => "ProjektyProNetMediaBudget" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyProNetMediaFinalApproveZam", 'description' => "ProjektyProNetMediaFinalApproveZam" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyProNetMediaRequestApproveZam", 'description' => "ProjektyProNetMediaRequestApproveZam" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyProNetMediaZamZlec", 'description' => "ProjektyProNetMediaZamZlec" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyPrzedmiarKosztorys", 'description' => "ProjektyPrzedmiarKosztorys" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyZamowieniaKosztorys", 'description' => "ProjektyZamowieniaKosztorys" ];
-    $_cacheAllItems[] = [ 'name' => "ProjektyZestawienieSwMikRurKosztorys", 'description' => "ProjektyZestawienieSwMikRurKosztorys" ];
-    $_cacheAllItems[] = [ 'name' => "RaportyKasowe", 'description' => "RaportyKasowe" ];
-    $_cacheAllItems[] = [ 'name' => "UserProNetMediaZaliczka", 'description' => "UserProNetMediaZaliczka" ];
-    $_cacheAllItems[] = [ 'name' => "WmsGenerate", 'description' => "WmsGenerate" ];
+		$_cacheAllItems = [];
+		$_cacheAllItems[] = [ 'name' => "Calendar", 'description' => "Calendar" ];
+		$_cacheAllItems[] = [ 'name' => "ProcesEditor", 'description' => "ProcesEditor" ];
+		$_cacheAllItems[] = [ 'name' => "ProcesView", 'description' => "ProcesView" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyKosztorys", 'description' => "ProjektyKosztorys" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyKosztyWstepnychRobot", 'description' => "ProjektyKosztyWstepnychRobot" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyOdbiorKosztorys", 'description' => "ProjektyOdbiorKosztorys" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyOfertaAdminKosztorys", 'description' => "ProjektyOfertaAdminKosztorys" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyOfertaKosztorys", 'description' => "ProjektyOfertaKosztorys" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyProNetMediaApproveZam", 'description' => "ProjektyProNetMediaApproveZam" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyProNetMediaBudget", 'description' => "ProjektyProNetMediaBudget" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyProNetMediaFinalApproveZam", 'description' => "ProjektyProNetMediaFinalApproveZam" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyProNetMediaRequestApproveZam", 'description' => "ProjektyProNetMediaRequestApproveZam" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyProNetMediaZamZlec", 'description' => "ProjektyProNetMediaZamZlec" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyPrzedmiarKosztorys", 'description' => "ProjektyPrzedmiarKosztorys" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyZamowieniaKosztorys", 'description' => "ProjektyZamowieniaKosztorys" ];
+		$_cacheAllItems[] = [ 'name' => "ProjektyZestawienieSwMikRurKosztorys", 'description' => "ProjektyZestawienieSwMikRurKosztorys" ];
+		$_cacheAllItems[] = [ 'name' => "RaportyKasowe", 'description' => "RaportyKasowe" ];
+		$_cacheAllItems[] = [ 'name' => "UserProNetMediaZaliczka", 'description' => "UserProNetMediaZaliczka" ];
+		$_cacheAllItems[] = [ 'name' => "WmsGenerate", 'description' => "WmsGenerate" ];
 
-    return $_cacheAllItems;
-  }
+		return $_cacheAllItems;
+	}
 
 }

+ 4 - 4
SE/se-lib/Schema/SystemObjectStorageAcl.php

@@ -139,10 +139,10 @@ class Schema_SystemObjectStorageAcl extends Core_AclSimpleSchemaBase {
 				DB::getPDO()->execSql("
 					insert into `{$this->_rootTableName}` (namespace, idZasob, idDatabase, description, hasStruct)
 					select concat('{$source['nsPrefix']}/', t.`DESC`)
-						,  t.ID as idZasob
-						,  '{$source['idZasob']}' as idDatabase
-						,  t.`OPIS` as description
-						,  1 as hasStruct
+						, t.ID as idZasob
+						, '{$source['idZasob']}' as idDatabase
+						, t.`OPIS` as description
+						, 1 as hasStruct
 					from CRM_LISTA_ZASOBOW t
 					where t.`TYPE` = 'TABELA'
 						and t.A_STATUS in('NORMAL', 'WAITING')

+ 67 - 67
SE/se-lib/Schema/SystemProcessStorageAcl.php

@@ -5,80 +5,80 @@ Lib::loadClass('ParseOgcFilter');
 
 class Schema_SystemProcessStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_objects/SystemProcess',
-      'ID' => [ '@type' => 'xsd:integer' ],
-      'nazwa' => [ '@type' => 'xsd:string', '@alias' => 'DESC' ],
-      'opis' => [ '@type' => 'xsd:string', '@alias' => 'OPIS' ],
-      'autor' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_CREATE_AUTHOR' ],
-      'utworzono' => [ '@type' => 'xsd:date' , '@alias' => 'A_RECORD_CREATE_DATE' ],
-      'zaktualizował' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_UPDATE_AUTHOR' ],
-      'zaktualizowano' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_UPDATE_DATE' ]
-    ]
-  ];
-  public $_rootTableName = 'CRM_PROCES';
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_objects/SystemProcess',
+			'ID' => [ '@type' => 'xsd:integer' ],
+			'nazwa' => [ '@type' => 'xsd:string', '@alias' => 'DESC' ],
+			'opis' => [ '@type' => 'xsd:string', '@alias' => 'OPIS' ],
+			'autor' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_CREATE_AUTHOR' ],
+			'utworzono' => [ '@type' => 'xsd:date' , '@alias' => 'A_RECORD_CREATE_DATE' ],
+			'zaktualizował' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_UPDATE_AUTHOR' ],
+			'zaktualizowano' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_UPDATE_DATE' ]
+		]
+	];
+	public $_rootTableName = 'CRM_PROCES';
 
-  public function getTotal($params = []) {
-    $sqlWhereAnd = $this->_parseSqlWhere($params);
-    return DB::getPDO()->fetchValue("
-      select count(1) as total
-      from `CRM_PROCES` p
-      where p.`TYPE` = 'PROCES_INIT'
-        and p.`A_STATUS` not in('DELETED', 'OFF_HARD', 'OFF_SOFT')
-        {$sqlWhereAnd}
-    ");
-  }
+	public function getTotal($params = []) {
+		$sqlWhereAnd = $this->_parseSqlWhere($params);
+		return DB::getPDO()->fetchValue("
+			select count(1) as total
+			from `CRM_PROCES` p
+			where p.`TYPE` = 'PROCES_INIT'
+				and p.`A_STATUS` not in('DELETED', 'OFF_HARD', 'OFF_SOFT')
+				{$sqlWhereAnd}
+		");
+	}
 
-  public function _parseSqlWhere($params = []) {
-    $sqlWhereAnd = "";
-    // TODO: parse where/ogc, etc.
-    return $sqlWhereAnd;
-  }
+	public function _parseSqlWhere($params = []) {
+		$sqlWhereAnd = "";
+		// TODO: parse where/ogc, etc.
+		return $sqlWhereAnd;
+	}
 
-  public function getItems($params = []) {
-    $sqlOrderBy = "";
-    $sqlLimitOffset = "";
-    $sqlWhereAnd = $this->_parseSqlWhere($params);
+	public function getItems($params = []) {
+		$sqlOrderBy = "";
+		$sqlLimitOffset = "";
+		$sqlWhereAnd = $this->_parseSqlWhere($params);
 
-    $currSortCol = V::get('order_by', 'ID', $params);
-    $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
-    // TODO: validate $currSortCol is in field list
-    // TODO: validate $currSortFlip ('asc' or 'desc')
+		$currSortCol = V::get('order_by', 'ID', $params);
+		$currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
+		// TODO: validate $currSortCol is in field list
+		// TODO: validate $currSortFlip ('asc' or 'desc')
 
-    $aliasMap = array();
-    foreach ($this->_simpleSchema['root'] as $key => $field) {
-      if ('@' === substr($key, 0, 1)) continue;
-      $aliasMap[ $key ] = (!empty($field['@alias'])) ? $field['@alias'] : $key;
-    }
-    // TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
-    $currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
+		$aliasMap = array();
+		foreach ($this->_simpleSchema['root'] as $key => $field) {
+			if ('@' === substr($key, 0, 1)) continue;
+			$aliasMap[ $key ] = (!empty($field['@alias'])) ? $field['@alias'] : $key;
+		}
+		// TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
+		$currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
 
-    if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
-      $sqlOrderBy = "order by p.`{$currSortCol}` {$currSortFlip}";
-    }
+		if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
+			$sqlOrderBy = "order by p.`{$currSortCol}` {$currSortFlip}";
+		}
 
-    $limit = V::get('limit', 0, $params);
-    $limit = ($limit < 0) ? 0 : $limit;
-    $offset = V::get('limitstart', 0, $params);
-    $offset = ($offset < 0) ? 0 : $offset;
-    if ($limit > 0) $sqlLimitOffset = "limit {$limit} offset {$offset}";
+		$limit = V::get('limit', 0, $params);
+		$limit = ($limit < 0) ? 0 : $limit;
+		$offset = V::get('limitstart', 0, $params);
+		$offset = ($offset < 0) ? 0 : $offset;
+		if ($limit > 0) $sqlLimitOffset = "limit {$limit} offset {$offset}";
 
-    return DB::getPDO()->fetchAllByKey("
-      select p.ID
-        , p.`DESC` as nazwa
-        , p.`OPIS` as opis
-        , p.A_RECORD_CREATE_AUTHOR as `autor`
-        , p.A_RECORD_CREATE_DATE as `utworzono`
-        , p.A_RECORD_UPDATE_AUTHOR as `zaktualizował`
-        , p.A_RECORD_UPDATE_DATE as `zaktualizowano`
-      from `CRM_PROCES` p
-      where p.`TYPE` = 'PROCES_INIT'
-        and p.`A_STATUS` not in('DELETED', 'OFF_HARD', 'OFF_SOFT')
-        {$sqlWhereAnd}
-      {$sqlOrderBy}
-      {$sqlLimitOffset}
-    ", 'ID');
-  }
+		return DB::getPDO()->fetchAllByKey("
+			select p.ID
+				, p.`DESC` as nazwa
+				, p.`OPIS` as opis
+				, p.A_RECORD_CREATE_AUTHOR as `autor`
+				, p.A_RECORD_CREATE_DATE as `utworzono`
+				, p.A_RECORD_UPDATE_AUTHOR as `zaktualizował`
+				, p.A_RECORD_UPDATE_DATE as `zaktualizowano`
+			from `CRM_PROCES` p
+			where p.`TYPE` = 'PROCES_INIT'
+				and p.`A_STATUS` not in('DELETED', 'OFF_HARD', 'OFF_SOFT')
+				{$sqlWhereAnd}
+			{$sqlOrderBy}
+			{$sqlLimitOffset}
+		", 'ID');
+	}
 
 }

+ 184 - 184
SE/se-lib/Schema/SystemSourceStorageAcl.php

@@ -5,205 +5,205 @@ Lib::loadClass('ParseOgcFilter');
 
 class Schema_SystemSourceStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_objects/SystemSource',
-      '@primaryKey' => 'idZasob',
-      'idZasob' => [ '@type' => 'xsd:integer' ],
-      'nsPrefix' => [ '@type' => 'xsd:string' ],
-      'name' => [ '@type' => 'xsd:string' ],
-      'description' => [ '@type' => 'xsd:string' ],
-      'A_RECORD_CREATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'autor' ],
-      'A_RECORD_CREATE_DATE' => [ '@type' => 'xsd:date' , '@label' => 'utworzono' ],
-      'A_RECORD_UPDATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'zaktualizował' ],
-      'A_RECORD_UPDATE_DATE' => [ '@type' => 'xsd:date', '@label' => 'zaktualizowano' ],
-      'SystemObject' => [ '@ref' => 'default_objects/SystemObject', '@maxOccurs' => 'unbounded' ]
-    ]
-  ];
-  public $_rootTableName = 'CRM_#CACHE_ACL_SOURCE';
-  public $_version = '1';
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_objects/SystemSource',
+			'@primaryKey' => 'idZasob',
+			'idZasob' => [ '@type' => 'xsd:integer' ],
+			'nsPrefix' => [ '@type' => 'xsd:string' ],
+			'name' => [ '@type' => 'xsd:string' ],
+			'description' => [ '@type' => 'xsd:string' ],
+			'A_RECORD_CREATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'autor' ],
+			'A_RECORD_CREATE_DATE' => [ '@type' => 'xsd:date' , '@label' => 'utworzono' ],
+			'A_RECORD_UPDATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'zaktualizował' ],
+			'A_RECORD_UPDATE_DATE' => [ '@type' => 'xsd:date', '@label' => 'zaktualizowano' ],
+			'SystemObject' => [ '@ref' => 'default_objects/SystemObject', '@maxOccurs' => 'unbounded' ]
+		]
+	];
+	public $_rootTableName = 'CRM_#CACHE_ACL_SOURCE';
+	public $_version = '1';
 
-  public function updateCache() {
-    DBG::simpleLog('schema', "SystemSource::updateCache...");
-    // DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}` "); // TODO: DBG
-    DB::getPDO()->execSql("
-      create table if not exists `{$this->_rootTableName}` (
+	public function updateCache() {
+		DBG::simpleLog('schema', "SystemSource::updateCache...");
+		// DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}` "); // TODO: DBG
+		DB::getPDO()->execSql("
+			create table if not exists `{$this->_rootTableName}` (
 				`idZasob` int(11) NOT NULL,
 				`nsPrefix` varchar(255) DEFAULT '',
 				`name` varchar(255) DEFAULT '',
 				`description` varchar(255) DEFAULT '',
-        `hasConfig` tinyint(1) DEFAULT 0,
-        `A_RECORD_CREATE_AUTHOR` varchar(20) NOT NULL,
-        `A_RECORD_CREATE_DATE` datetime DEFAULT NULL,
-        `A_RECORD_UPDATE_AUTHOR` varchar(20) NOT NULL DEFAULT '',
-        `A_RECORD_UPDATE_DATE` datetime DEFAULT NULL,
+				`hasConfig` tinyint(1) DEFAULT 0,
+				`A_RECORD_CREATE_AUTHOR` varchar(20) NOT NULL,
+				`A_RECORD_CREATE_DATE` datetime DEFAULT NULL,
+				`A_RECORD_UPDATE_AUTHOR` varchar(20) NOT NULL DEFAULT '',
+				`A_RECORD_UPDATE_DATE` datetime DEFAULT NULL,
 				UNIQUE KEY `idZasob` (idZasob)
-			) ENGINE=MyISAM  DEFAULT CHARSET=latin2
-    ");
+			) ENGINE=MyISAM	DEFAULT CHARSET=latin2
+		");
 
-    // database from config files
-    $host = V::get('SERVER_NAME', '', $_SERVER);
-    if (!$host) die('Missing SERVER_NAME!');
-    function hideConfPass($line) {
-      if (false !== ($pos = strpos($line, "pass' =>"))) {
-        return substr($line, 0, $pos + 9) . "*****";
-      }
-      return $line;
-    }
-    foreach (glob(APP_PATH_CONFIG . "/.cnf--zasob_*-{$host}.ini.php", GLOB_NOSORT) as $file) {
-      $fname = basename($file);
-      // DBG::nicePrint($fname, '$fname');
-      $idZasob = (int)substr($fname, strlen('.cnf--zasob_'), strpos($fname, '-', strlen('.cnf--zasob_') + 1) - strlen('.cnf--zasob_'));// '.cnf--zasob_931-...'
-      // DBG::nicePrint($idZasob, '$idZasob');
-      if (!$idZasob) continue;
-      $conf = parse_ini_file($file, true);
-      if (!$conf) continue;
-      if (in_array(V::get('type', '', $conf), ['mysql', 'pgsql', 'mssql'])) {
-        DB::getPDO()->insertOrUpdate($this->_rootTableName, [
-          'idZasob' => $idZasob,
-          'nsPrefix' => "zasob_{$idZasob}",
-          'name' => V::get('database', $idZasob, $conf),
-          'hasConfig' => 1,
-          '@insert' => [
-            'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
-            'A_RECORD_CREATE_DATE' => 'NOW()',
-          ],
-          '@update' => [
-            'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
-            'A_RECORD_UPDATE_DATE' => 'NOW()',
-          ]
-        ]);
-      }
-      // DBG::nicePrint(implode("\n", array_map( hideConfPass, explode("\n", var_export($conf, true)) ) ), '$conf');
-    }
+		// database from config files
+		$host = V::get('SERVER_NAME', '', $_SERVER);
+		if (!$host) die('Missing SERVER_NAME!');
+		function hideConfPass($line) {
+			if (false !== ($pos = strpos($line, "pass' =>"))) {
+				return substr($line, 0, $pos + 9) . "*****";
+			}
+			return $line;
+		}
+		foreach (glob(APP_PATH_CONFIG . "/.cnf--zasob_*-{$host}.ini.php", GLOB_NOSORT) as $file) {
+			$fname = basename($file);
+			// DBG::nicePrint($fname, '$fname');
+			$idZasob = (int)substr($fname, strlen('.cnf--zasob_'), strpos($fname, '-', strlen('.cnf--zasob_') + 1) - strlen('.cnf--zasob_'));// '.cnf--zasob_931-...'
+			// DBG::nicePrint($idZasob, '$idZasob');
+			if (!$idZasob) continue;
+			$conf = parse_ini_file($file, true);
+			if (!$conf) continue;
+			if (in_array(V::get('type', '', $conf), ['mysql', 'pgsql', 'mssql'])) {
+				DB::getPDO()->insertOrUpdate($this->_rootTableName, [
+					'idZasob' => $idZasob,
+					'nsPrefix' => "zasob_{$idZasob}",
+					'name' => V::get('database', $idZasob, $conf),
+					'hasConfig' => 1,
+					'@insert' => [
+						'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+						'A_RECORD_CREATE_DATE' => 'NOW()',
+					],
+					'@update' => [
+						'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
+						'A_RECORD_UPDATE_DATE' => 'NOW()',
+					]
+				]);
+			}
+			// DBG::nicePrint(implode("\n", array_map( hideConfPass, explode("\n", var_export($conf, true)) ) ), '$conf');
+		}
 
-    // source from CRM_LISTA_ZASOBOW
-    foreach (DB::getPDO()->fetchAll("
-      select z.`ID`, z.`DESC`, z.OPIS
-      from CRM_LISTA_ZASOBOW z
-      where z.`TYPE` in ('BAZA_DANYCH', 'DATABASE_MYSQL', 'DATABASE_POSTGRESQL')
-        and z.A_STATUS not in ('DELETED')
-    ") as $item) {
-      $desc = V::get('DESC', $item['ID'], $item);
-      DB::getPDO()->insertOrUpdate($this->_rootTableName, [
-        'idZasob' => $item['ID'],
-        'nsPrefix' => "zasob_{$item['ID']}",
-        'name' => $desc,
-        'description' => V::get('OPIS', $desc, $item),
-        '@insert' => [
-          'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
-          'A_RECORD_CREATE_DATE' => 'NOW()',
-          'hasConfig' => 0,
-        ],
-        '@update' => [
-          'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
-          'A_RECORD_UPDATE_DATE' => 'NOW()',
-        ]
-      ]);
-    }
-    $idMainDb = DB::getPDO()->getZasobId();
-    DB::getPDO()->update($this->_rootTableName, 'idZasob', $idMainDb, [
-      'nsPrefix' => 'default_db'
-    ]);
+		// source from CRM_LISTA_ZASOBOW
+		foreach (DB::getPDO()->fetchAll("
+			select z.`ID`, z.`DESC`, z.OPIS
+			from CRM_LISTA_ZASOBOW z
+			where z.`TYPE` in ('BAZA_DANYCH', 'DATABASE_MYSQL', 'DATABASE_POSTGRESQL')
+				and z.A_STATUS not in ('DELETED')
+		") as $item) {
+			$desc = V::get('DESC', $item['ID'], $item);
+			DB::getPDO()->insertOrUpdate($this->_rootTableName, [
+				'idZasob' => $item['ID'],
+				'nsPrefix' => "zasob_{$item['ID']}",
+				'name' => $desc,
+				'description' => V::get('OPIS', $desc, $item),
+				'@insert' => [
+					'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+					'A_RECORD_CREATE_DATE' => 'NOW()',
+					'hasConfig' => 0,
+				],
+				'@update' => [
+					'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
+					'A_RECORD_UPDATE_DATE' => 'NOW()',
+				]
+			]);
+		}
+		$idMainDb = DB::getPDO()->getZasobId();
+		DB::getPDO()->update($this->_rootTableName, 'idZasob', $idMainDb, [
+			'nsPrefix' => 'default_db'
+		]);
 
-    // default_objects: StorageAcl, AntAcl, ...
-    $id = DB::getPDO()->fetchValue(" select idZasob from `{$this->_rootTableName}` where name = 'default_objects' ");
-    if (!$id) {
-      $item = DB::getPDO()->fetchFirst("
-        select z.`ID`
-        from CRM_LISTA_ZASOBOW z
-        where z.`TYPE` in ('BAZA_DANYCH')
-          and z.A_STATUS not in ('DELETED')
-          and z.`DESC` = 'default_objects'
-      ");
-      if ($item) {
-        $id = $item['ID'];
-      } else {
-        $idMainDbParent = DB::getPDO()->fetchValue(" select PARENT_ID from CRM_LISTA_ZASOBOW where ID = '" . DB::getPDO()->getZasobId() . "' ");
-        $id = DB::getPDO()->insert('CRM_LISTA_ZASOBOW', [
-          'DESC' => 'default_objects',
-          'TYPE' => 'BAZA_DANYCH',
-          'OPIS' => "Obiekty systemowe",
-          'PARENT_ID' => $idMainDbParent,
-          'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
-          'A_RECORD_CREATE_DATE' => 'NOW()',
-          'A_ADM_COMPANY' => 'system',// edit not allowed
-        ]);
-      }
-    }
-    if (!$id) throw new Exception("Missing default_objects ID");
-    DB::getPDO()->insertOrUpdate($this->_rootTableName, [
-      'idZasob' => $id,
-      'nsPrefix' => 'default_objects',
-      'name' => 'default_objects',
-      'description' => "Obiekty systemowe",
-      'hasConfig' => 1,
-      '@insert' => [
-        'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
-        'A_RECORD_CREATE_DATE' => 'NOW()',
-      ],
-      '@update' => [
-        'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
-        'A_RECORD_UPDATE_DATE' => 'NOW()',
-      ]
-    ]);
-  }
+		// default_objects: StorageAcl, AntAcl, ...
+		$id = DB::getPDO()->fetchValue(" select idZasob from `{$this->_rootTableName}` where name = 'default_objects' ");
+		if (!$id) {
+			$item = DB::getPDO()->fetchFirst("
+				select z.`ID`
+				from CRM_LISTA_ZASOBOW z
+				where z.`TYPE` in ('BAZA_DANYCH')
+					and z.A_STATUS not in ('DELETED')
+					and z.`DESC` = 'default_objects'
+			");
+			if ($item) {
+				$id = $item['ID'];
+			} else {
+				$idMainDbParent = DB::getPDO()->fetchValue(" select PARENT_ID from CRM_LISTA_ZASOBOW where ID = '" . DB::getPDO()->getZasobId() . "' ");
+				$id = DB::getPDO()->insert('CRM_LISTA_ZASOBOW', [
+					'DESC' => 'default_objects',
+					'TYPE' => 'BAZA_DANYCH',
+					'OPIS' => "Obiekty systemowe",
+					'PARENT_ID' => $idMainDbParent,
+					'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+					'A_RECORD_CREATE_DATE' => 'NOW()',
+					'A_ADM_COMPANY' => 'system',// edit not allowed
+				]);
+			}
+		}
+		if (!$id) throw new Exception("Missing default_objects ID");
+		DB::getPDO()->insertOrUpdate($this->_rootTableName, [
+			'idZasob' => $id,
+			'nsPrefix' => 'default_objects',
+			'name' => 'default_objects',
+			'description' => "Obiekty systemowe",
+			'hasConfig' => 1,
+			'@insert' => [
+				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+				'A_RECORD_CREATE_DATE' => 'NOW()',
+			],
+			'@update' => [
+				'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
+				'A_RECORD_UPDATE_DATE' => 'NOW()',
+			]
+		]);
+	}
 
-  public function getTotal($params = []) {
-    return DB::getPDO()->fetchValue(" select count(1) as cnt from `{$this->_rootTableName}` ");
-  }
+	public function getTotal($params = []) {
+		return DB::getPDO()->fetchValue(" select count(1) as cnt from `{$this->_rootTableName}` ");
+	}
 
-  public function getItem($pk, $params = []) {
-    $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_INT);
-    $item = DB::getPDO()->fetchFirst("
-      select t.*
-      from `{$this->_rootTableName}` t
-      where t.idZasob = {$sqlPk}
-    ");
-    return $item;
-  }
+	public function getItem($pk, $params = []) {
+		$sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_INT);
+		$item = DB::getPDO()->fetchFirst("
+			select t.*
+			from `{$this->_rootTableName}` t
+			where t.idZasob = {$sqlPk}
+		");
+		return $item;
+	}
 
-  public function getItems($params = []) {
-    $sqlWhere = [];
-    if (array_key_exists('f_hasConfig', $params)) {
-      $sqlWhere[] = "t.hasConfig = " . DB::getPDO()->convertValueToSqlSafe($params['f_hasConfig']);
-    }
-    $sqlWhere = (!empty($sqlWhere)) ? "where " . implode(" and ", $sqlWhere) : "";
-    $items = DB::getPDO()->fetchAll("
-      select t.*
-      from `{$this->_rootTableName}` t
-      {$sqlWhere}
-    ");
-    $currSortCol = V::get('order_by', 'ID', $params);
-    $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
-    // TODO: validate $currSortCol is in field list
-    // TODO: validate $currSortFlip ('asc' or 'desc')
+	public function getItems($params = []) {
+		$sqlWhere = [];
+		if (array_key_exists('f_hasConfig', $params)) {
+			$sqlWhere[] = "t.hasConfig = " . DB::getPDO()->convertValueToSqlSafe($params['f_hasConfig']);
+		}
+		$sqlWhere = (!empty($sqlWhere)) ? "where " . implode(" and ", $sqlWhere) : "";
+		$items = DB::getPDO()->fetchAll("
+			select t.*
+			from `{$this->_rootTableName}` t
+			{$sqlWhere}
+		");
+		$currSortCol = V::get('order_by', 'ID', $params);
+		$currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
+		// TODO: validate $currSortCol is in field list
+		// TODO: validate $currSortFlip ('asc' or 'desc')
 
-    $aliasMap = array();
-    foreach ($this->_simpleSchema['root'] as $key => $field) {
-      if ('@' === substr($key, 0, 1)) continue;
-      $aliasMap[ $key ] = $key;// (!empty($field['@alias'])) ? $field['@alias'] : $key;
-    }
-    // TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
-    $currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
+		$aliasMap = array();
+		foreach ($this->_simpleSchema['root'] as $key => $field) {
+			if ('@' === substr($key, 0, 1)) continue;
+			$aliasMap[ $key ] = $key;// (!empty($field['@alias'])) ? $field['@alias'] : $key;
+		}
+		// TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
+		$currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
 
-    if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
-      usort($items, function ($itemA, $itemB) use ($currSortCol, $currSortFlip) {
-        $a = strtolower(V::get($currSortCol, '', $itemA));
-        $b = strtolower(V::get($currSortCol, '', $itemB));
+		if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
+			usort($items, function ($itemA, $itemB) use ($currSortCol, $currSortFlip) {
+				$a = strtolower(V::get($currSortCol, '', $itemA));
+				$b = strtolower(V::get($currSortCol, '', $itemB));
 
-        if ($a == $b) return 0;
-        else if ('asc' == $currSortFlip)  return ($a < $b) ? -1 : 1;
-        else if ('desc' == $currSortFlip) return ($a > $b) ? -1 : 1;
-        throw new Exception("BUG - Wrong sort param - order dir");
-      });
-    }
+				if ($a == $b) return 0;
+				else if ('asc' == $currSortFlip)	return ($a < $b) ? -1 : 1;
+				else if ('desc' == $currSortFlip) return ($a > $b) ? -1 : 1;
+				throw new Exception("BUG - Wrong sort param - order dir");
+			});
+		}
 
-    $limit = V::get('limit', 0, $params);
-    $limit = ($limit < 0) ? 0 : $limit;
-    $offset = V::get('limitstart', 0, $params);
-    $offset = ($offset < 0) ? 0 : $offset;
-    return array_slice($items, $offset, ($limit > 0) ? $limit : null, $preserve_keys = true);
-  }
+		$limit = V::get('limit', 0, $params);
+		$limit = ($limit < 0) ? 0 : $limit;
+		$offset = V::get('limitstart', 0, $params);
+		$offset = ($offset < 0) ? 0 : $offset;
+		return array_slice($items, $offset, ($limit > 0) ? $limit : null, $preserve_keys = true);
+	}
 
 }

+ 1 - 1
SE/se-lib/Schema/TableBase.php

@@ -175,7 +175,7 @@ class Schema_TableBase {
 						$field['p5_type'] = 'hexBinary';
 					} break;
 				default:
-					DBG::_(true, true, "TODO: storageType({$storageType})  field({$field['name']})", $field, __CLASS__, __FUNCTION__, __LINE__);
+					DBG::_(true, true, "TODO: storageType({$storageType}) field({$field['name']})", $field, __CLASS__, __FUNCTION__, __LINE__);
 			}
 		} else if ('pgsql' == $storageType) {
 		} else {

+ 169 - 169
SE/se-lib/Schema/TestPermsStorageAcl.php

@@ -6,180 +6,180 @@ Lib::loadClass('FileStorage');
 
 class Schema_TestPermsStorageAcl extends Core_AclBase {
 
-  public function __construct() {
-    $this->parentAcl = User::getAcl()->getObjectAcl('default_db', 'TEST_PERMS');
-    // DBG::_(true, true, "parentAcl", $this->parentAcl, __CLASS__, __FUNCTION__, __LINE__);
-  }
-  public function getNamespace() { return 'default_objects/' . $this->getName(); }
-  public function getSourceName() { return 'default_objects'; }
-  public function init($force = false) {}
-  public function isInitialized() { return true; }
-  public function getName() { return 'TestPerms'; }
-  public function getRootTableName() { return 'TEST_PREMS'; }
-  public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
-  public function getVisibleFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
-  public function getVirtualFieldListByIdZasob() { return array(); }
-  public function getRealFieldListByIdZasob($force = false) {
-    $cols = $this->parentAcl->getRealFieldListByIdZasob();
-    $cols[100000] = 'File';
-    // $cols[100010] = 'File1';
-    // $cols[100011] = 'File2';
-    // $cols[100001] = 'NestedObjectTest';
-    $cols[100002] = 'AccessGroupRead';
-    $cols[100003] = 'AccessGroupWrite';
-    $cols[100004] = 'AccessOwner';
-    return $cols;
-  }
-  public function getFields() {// @returns array - $this->_fields
-    $fields = $this->parentAcl->getFields();
-    $fields[100000] = ['name'=>'File', 'perms'=>'RWXC', 'opis'=>'Plik', 'sort_prio'=>999, 'label'=>'Plik'];
-    // $fields[100001] = 'NestedObjectTest';
-    $fields[100002] = ['name'=>'AccessGroupRead', 'perms'=>'RWXC', 'opis'=>'Odczyt dla', 'sort_prio'=>999, 'label'=>'Odczyt dla'];
-    $fields[100003] = ['name'=>'AccessGroupWrite', 'perms'=>'RWXC', 'opis'=>'Zapis dla', 'sort_prio'=>999, 'label'=>'Zapis dla'];
-    $fields[100004] = ['name'=>'AccessOwner', 'perms'=>'RWXC', 'opis'=>'Osoba odpowiedzialna', 'sort_prio'=>999, 'label'=>'Osoba odp.'];
-    return $fields;
-  }
-  public function getFieldType($fieldName) {
-    foreach ($this->getFields() as $field) {
-      if ($fieldName == $field['name']) return $field;
-    }
-    return null;
+	public function __construct() {
+		$this->parentAcl = User::getAcl()->getObjectAcl('default_db', 'TEST_PERMS');
+		// DBG::_(true, true, "parentAcl", $this->parentAcl, __CLASS__, __FUNCTION__, __LINE__);
+	}
+	public function getNamespace() { return 'default_objects/' . $this->getName(); }
+	public function getSourceName() { return 'default_objects'; }
+	public function init($force = false) {}
+	public function isInitialized() { return true; }
+	public function getName() { return 'TestPerms'; }
+	public function getRootTableName() { return 'TEST_PREMS'; }
+	public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
+	public function getVisibleFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
+	public function getVirtualFieldListByIdZasob() { return array(); }
+	public function getRealFieldListByIdZasob($force = false) {
+		$cols = $this->parentAcl->getRealFieldListByIdZasob();
+		$cols[100000] = 'File';
+		// $cols[100010] = 'File1';
+		// $cols[100011] = 'File2';
+		// $cols[100001] = 'NestedObjectTest';
+		$cols[100002] = 'AccessGroupRead';
+		$cols[100003] = 'AccessGroupWrite';
+		$cols[100004] = 'AccessOwner';
+		return $cols;
+	}
+	public function getFields() {// @returns array - $this->_fields
+		$fields = $this->parentAcl->getFields();
+		$fields[100000] = ['name'=>'File', 'perms'=>'RWXC', 'opis'=>'Plik', 'sort_prio'=>999, 'label'=>'Plik'];
+		// $fields[100001] = 'NestedObjectTest';
+		$fields[100002] = ['name'=>'AccessGroupRead', 'perms'=>'RWXC', 'opis'=>'Odczyt dla', 'sort_prio'=>999, 'label'=>'Odczyt dla'];
+		$fields[100003] = ['name'=>'AccessGroupWrite', 'perms'=>'RWXC', 'opis'=>'Zapis dla', 'sort_prio'=>999, 'label'=>'Zapis dla'];
+		$fields[100004] = ['name'=>'AccessOwner', 'perms'=>'RWXC', 'opis'=>'Osoba odpowiedzialna', 'sort_prio'=>999, 'label'=>'Osoba odp.'];
+		return $fields;
+	}
+	public function getFieldType($fieldName) {
+		foreach ($this->getFields() as $field) {
+			if ($fieldName == $field['name']) return $field;
+		}
+		return null;
 	}
 
-  // TODO: replace legacy functions: isAllowed, hasFieldPerm, getFieldIdByName
-  public function canCreateField($fieldName) {
-    if ('File' == $fieldName) return true;
-    if ('AccessGroupRead' == $fieldName) return true;
-    if ('AccessGroupWrite' == $fieldName) return true;
-    if ('AccessOwner' == $fieldName) return true;
-    return $this->parentAcl->canCreateField($fieldName);
-  }
-  public function canReadField($fieldName) {
-    if ('File' == $fieldName) return true;
-    if ('AccessGroupRead' == $fieldName) return true;
-    if ('AccessGroupWrite' == $fieldName) return true;
-    if ('AccessOwner' == $fieldName) return true;
-    return $this->parentAcl->canReadField($fieldName);
-  }
-  public function canReadObjectField($fieldName, $record) {
-    if ('File' == $fieldName) return true;
-    if ('AccessGroupRead' == $fieldName) return true;
-    if ('AccessGroupWrite' == $fieldName) return true;
-    if ('AccessOwner' == $fieldName) return true;
-    return $this->parentAcl->canReadObjectField($fieldName, $record);
-  }
-  public function canWriteField($fieldName) {
-    if ('File' == $fieldName) return true;
-    if ('AccessGroupRead' == $fieldName) return true;
-    if ('AccessGroupWrite' == $fieldName) return true;
-    if ('AccessOwner' == $fieldName) return true;
-    return $this->parentAcl->canWriteField($fieldName);
-  }
-  public function canWriteObjectField($fieldName, $record) {
-    if ('File' == $fieldName) return true;
-    if ('AccessGroupRead' == $fieldName) return true;
-    if ('AccessGroupWrite' == $fieldName) return true;
-    if ('AccessOwner' == $fieldName) return true;
-    return $this->parentAcl->canWriteObjectField($fieldName, $record);
-  }
+	// TODO: replace legacy functions: isAllowed, hasFieldPerm, getFieldIdByName
+	public function canCreateField($fieldName) {
+		if ('File' == $fieldName) return true;
+		if ('AccessGroupRead' == $fieldName) return true;
+		if ('AccessGroupWrite' == $fieldName) return true;
+		if ('AccessOwner' == $fieldName) return true;
+		return $this->parentAcl->canCreateField($fieldName);
+	}
+	public function canReadField($fieldName) {
+		if ('File' == $fieldName) return true;
+		if ('AccessGroupRead' == $fieldName) return true;
+		if ('AccessGroupWrite' == $fieldName) return true;
+		if ('AccessOwner' == $fieldName) return true;
+		return $this->parentAcl->canReadField($fieldName);
+	}
+	public function canReadObjectField($fieldName, $record) {
+		if ('File' == $fieldName) return true;
+		if ('AccessGroupRead' == $fieldName) return true;
+		if ('AccessGroupWrite' == $fieldName) return true;
+		if ('AccessOwner' == $fieldName) return true;
+		return $this->parentAcl->canReadObjectField($fieldName, $record);
+	}
+	public function canWriteField($fieldName) {
+		if ('File' == $fieldName) return true;
+		if ('AccessGroupRead' == $fieldName) return true;
+		if ('AccessGroupWrite' == $fieldName) return true;
+		if ('AccessOwner' == $fieldName) return true;
+		return $this->parentAcl->canWriteField($fieldName);
+	}
+	public function canWriteObjectField($fieldName, $record) {
+		if ('File' == $fieldName) return true;
+		if ('AccessGroupRead' == $fieldName) return true;
+		if ('AccessGroupWrite' == $fieldName) return true;
+		if ('AccessOwner' == $fieldName) return true;
+		return $this->parentAcl->canWriteObjectField($fieldName, $record);
+	}
 
-  public function getTotal($params = array()) {// TODO: use ParseOgcQuery
-    $DBG = V::get('DBG_DS', 0, $_GET, 'int');
-    if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getTotal \$params:";print_r($params);echo "\n";}
-    return $this->parentAcl->getTotal($params);
-  }
-  public function getItem($primaryKey, $params = []) {
-    $items = $this->getItems(['primaryKey'=>$primaryKey]);
-    return (!empty($items[$primaryKey])) ? $items[$primaryKey] : null;
-  }
-  public function getItems($params = array()) {// TODO: use ParseOgcQuery
-    $DBG = V::get('DBG_DS', 0, $_GET, 'int');
-    if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$params:";print_r($params);echo "\n";}
-    $items = array();
-    $rawItems = $this->parentAcl->getItems($params);
-    foreach ($rawItems as $pk => $item) $items[$pk] = (array)$item;
-    if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$items:";print_r($items);echo "\n";}
-    if (empty($items)) return $items;
-    $this->itemsFetchRefs($items);// TODO: only fields from request
-    if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems after itemsFetchRefs \$items:";print_r($items);echo "\n";}
-    return $items;
-  }
-  public function addItem($itemTodo) {
-    return $this->parentAcl->addItem($itemTodo);
-  }
-  public function updateItem($itemPatch) {
-    return $this->parentAcl->updateItem($itemPatch);
-  }
+	public function getTotal($params = array()) {// TODO: use ParseOgcQuery
+		$DBG = V::get('DBG_DS', 0, $_GET, 'int');
+		if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getTotal \$params:";print_r($params);echo "\n";}
+		return $this->parentAcl->getTotal($params);
+	}
+	public function getItem($primaryKey, $params = []) {
+		$items = $this->getItems(['primaryKey'=>$primaryKey]);
+		return (!empty($items[$primaryKey])) ? $items[$primaryKey] : null;
+	}
+	public function getItems($params = array()) {// TODO: use ParseOgcQuery
+		$DBG = V::get('DBG_DS', 0, $_GET, 'int');
+		if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$params:";print_r($params);echo "\n";}
+		$items = array();
+		$rawItems = $this->parentAcl->getItems($params);
+		foreach ($rawItems as $pk => $item) $items[$pk] = (array)$item;
+		if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems \$items:";print_r($items);echo "\n";}
+		if (empty($items)) return $items;
+		$this->itemsFetchRefs($items);// TODO: only fields from request
+		if($DBG>2){echo 'C.'.get_class($this).' L.' . __LINE__ . " getItems after itemsFetchRefs \$items:";print_r($items);echo "\n";}
+		return $items;
+	}
+	public function addItem($itemTodo) {
+		return $this->parentAcl->addItem($itemTodo);
+	}
+	public function updateItem($itemPatch) {
+		return $this->parentAcl->updateItem($itemPatch);
+	}
 
-  public function getGeomFieldType($fieldName) { return ('the_geom' == $fieldName) ? 'polygon' : null; }
-  public function getPrimaryKeyField() { return 'ID'; }
-  public function getAttributesFromZasoby() { return array(); }
-  public function isEnumerationField($fieldName) {
-    if ('A_STATUS' == $fieldName) return true;
-    return false;
-  }
-  public function getEnumerations($fieldName) {
-    if ('A_STATUS' == $fieldName) return $this->parentAcl->getEnumerations($fieldName);
-    return null;
-  }
-  public function getXsdFieldType($fieldName) {
-    if ('File' == $fieldName) return 'ref:default_objects:File';
-    // if ('File1' == $fieldName) return 'alias_ref:p5_objects:File';
-    // if ('File2' == $fieldName) return 'alias_ref:p5_objects:File';
-    // if ('NestedObjectTest' == $fieldName) return 'local_ref:p5_objects:NestedObjectTest';
-    if ('AccessGroupRead' == $fieldName) return 'ref:default_objects:AccessGroupRead';
-    if ('AccessGroupWrite' == $fieldName) return 'ref:default_objects:AccessGroupWrite';
-    if ('AccessOwner' == $fieldName) return 'ref:default_objects:AccessOwner';
-    return $this->parentAcl->getXsdFieldType($fieldName);
-  }
-  public function isGeomField($fldName) {
-    if ('File' == $fieldName) return false;
-    if ('AccessGroupRead' == $fieldName) return false;
-    if ('AccessGroupWrite' == $fieldName) return false;
-    if ('AccessOwner' == $fieldName) return false;
-    // if ('NestedObjectTest' == $fieldName) return false;
-    return $this->parentAcl->isGeomField($fldName);
-  }
+	public function getGeomFieldType($fieldName) { return ('the_geom' == $fieldName) ? 'polygon' : null; }
+	public function getPrimaryKeyField() { return 'ID'; }
+	public function getAttributesFromZasoby() { return array(); }
+	public function isEnumerationField($fieldName) {
+		if ('A_STATUS' == $fieldName) return true;
+		return false;
+	}
+	public function getEnumerations($fieldName) {
+		if ('A_STATUS' == $fieldName) return $this->parentAcl->getEnumerations($fieldName);
+		return null;
+	}
+	public function getXsdFieldType($fieldName) {
+		if ('File' == $fieldName) return 'ref:default_objects:File';
+		// if ('File1' == $fieldName) return 'alias_ref:p5_objects:File';
+		// if ('File2' == $fieldName) return 'alias_ref:p5_objects:File';
+		// if ('NestedObjectTest' == $fieldName) return 'local_ref:p5_objects:NestedObjectTest';
+		if ('AccessGroupRead' == $fieldName) return 'ref:default_objects:AccessGroupRead';
+		if ('AccessGroupWrite' == $fieldName) return 'ref:default_objects:AccessGroupWrite';
+		if ('AccessOwner' == $fieldName) return 'ref:default_objects:AccessOwner';
+		return $this->parentAcl->getXsdFieldType($fieldName);
+	}
+	public function isGeomField($fldName) {
+		if ('File' == $fieldName) return false;
+		if ('AccessGroupRead' == $fieldName) return false;
+		if ('AccessGroupWrite' == $fieldName) return false;
+		if ('AccessOwner' == $fieldName) return false;
+		// if ('NestedObjectTest' == $fieldName) return false;
+		return $this->parentAcl->isGeomField($fldName);
+	}
 
-  public function getInstanceList() {
-    return [
-      'TestPerms',
-      'TestPermsDoUzgodnienia',
-      'TestPermsUzgodniony',
-      'TestPermsOdrzucony',
-      'TestPermsAktywny', // test `matching`
-    ];
-  }
+	public function getInstanceList() {
+		return [
+			'TestPerms',
+			'TestPermsDoUzgodnienia',
+			'TestPermsUzgodniony',
+			'TestPermsOdrzucony',
+			'TestPermsAktywny', // test `matching`
+		];
+	}
 
-  public function getInstanceSchema($instance) {
-    switch ($instance) {
-      case 'TestPermsDoUzgodnienia': return [
-        '@extension' => [
-          '@base' => 'TEST_PERMS',
-          'KorespDoUzg' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/KorespDoUzg', '@minOccurs' => 1 ],
-        ]
-      ];
-      case 'TestPermsUzgodniony': return [
-        '@extension' => [
-          '@base' => 'TestPermsDoUzgodnienia',
-          'KorespDoUzg' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/KorespDoUzg', '@minOccurs' => 0 ],
-          'KorespUzg' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/KorespUzg', '@minOccurs' => 1 ],
-        ]
-      ];
-      case 'TestPermsOdrzucony': return [
-        '@extension' => [
-          '@base' => 'TestPermsDoUzgodnienia',
-          'KorespDoUzg' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/KorespDoUzg', '@minOccurs' => 0 ],
-          'KorespOdrzucony' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/KorespOdrzucony', '@minOccurs' => 1 ],
-        ]
-      ];
-      case 'TestPermsAktywny': return [
-        '@restriction' => [
-          '@base' => 'TEST_PERMS',
-          'A_STATUS' => [ '@fixed' => "NORMAL" ],
-        ]
-      ];
-    }
-  }
+	public function getInstanceSchema($instance) {
+		switch ($instance) {
+			case 'TestPermsDoUzgodnienia': return [
+				'@extension' => [
+					'@base' => 'TEST_PERMS',
+					'KorespDoUzg' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/KorespDoUzg', '@minOccurs' => 1 ],
+				]
+			];
+			case 'TestPermsUzgodniony': return [
+				'@extension' => [
+					'@base' => 'TestPermsDoUzgodnienia',
+					'KorespDoUzg' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/KorespDoUzg', '@minOccurs' => 0 ],
+					'KorespUzg' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/KorespUzg', '@minOccurs' => 1 ],
+				]
+			];
+			case 'TestPermsOdrzucony': return [
+				'@extension' => [
+					'@base' => 'TestPermsDoUzgodnienia',
+					'KorespDoUzg' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/KorespDoUzg', '@minOccurs' => 0 ],
+					'KorespOdrzucony' => [ '@ref' => 'default_db/IN7_DZIENNIK_KORESP/KorespOdrzucony', '@minOccurs' => 1 ],
+				]
+			];
+			case 'TestPermsAktywny': return [
+				'@restriction' => [
+					'@base' => 'TEST_PERMS',
+					'A_STATUS' => [ '@fixed' => "NORMAL" ],
+				]
+			];
+		}
+	}
 
 }

+ 131 - 131
SE/se-lib/Schema/UserConfigStorageAcl.php

@@ -9,137 +9,137 @@ Lib::loadClass('UsersHelper');
  */
 class Schema_UserConfigStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_objects/UserConfig',
-      '@primaryKey' => 'ID_USER',
-      'ID_USER' => [ '@type' => 'xsd:integer' ],
-      'ID_PROCES' => [ '@type' => 'xsd:integer' ],
-      'lastLogin' => [ '@type' => 'xsd:dateTime', '@confKey' => 'auth_user_{ID_USER}' ],// TODO: store last login time
-      'lastAuthCacheUpdate' => [ '@type' => 'xsd:dateTime', '@confKey' => 'acl_user_{ID_USER}_{ID_PROCES}_cache_update' ],
-      // 'appFilterProces' => [ '@type' => 'xsd:integer' ],// TODO: filter proces id set by app (web app stores in session - create UserSession Storage)
-    ]
-  ];
-  public $_rootTableName = 'CRM_CONFIG__#USER_CONF_VIEW';// 'CRM_CONFIG';
-  public $idUser = null;
-  public $idProcesFilter = null;
-
-  public function __construct($simpleSchema = null) {
-    parent::__construct($simpleSchema);
-    $this->idUser = User::getID();// default - current user
-    $this->idProcesFilter = 0;
-  }
-
-  public function setIdUser($idUser) {
-    $this->idUser = intval($idUser);
-    if ($this->idUser <= 0) throw new Exception("Missing id user");
-  }
-  public function getIdUser() { return $this->idUser; }
-  public function setIdProcesFilter($idProcesFilter) { $this->idProcesFilter = intval($idProcesFilter); }
-  public function getIdProcesFilter() { return $this->idProcesFilter; }
-
-  public function getTotal($params = []) { return 1; }
-
-  public function _parseSqlWhere($params = []) { return ''; }
-
-  public function sqlFieldConfKey($fieldName) {
-    if ('@' == substr($fieldName, 0, 1)) return null;
-    if (!array_key_exists($fieldName, $this->_simpleSchema['root'])) return null;
-    $field = $this->_simpleSchema['root'][$fieldName];
-    if ('ID_USER' == $fieldName) return null;
-    if ('ID_PROCES' == $fieldName) return null;
-    if (empty($field['@confKey'])) return null;
-    $confKey = $field['@confKey'];
-    $confKey = str_replace('{ID_USER}', $this->idUser, $confKey);
-    $confKey = str_replace('{ID_PROCES}', $this->idProcesFilter, $confKey);
-    return $confKey;
-  }
-
-  public function updateItem($itemPatch) {
-    DBG::log($itemPatch, 'array', '$itemPatch');
-
-    $affected = 0;
-    foreach ($itemPatch as $fieldName => $value) {
-      if (!array_key_exists($fieldName, $this->_simpleSchema['root'])) throw new Exception("Field '{$fieldName}' not exists in '" . $this->getNamespace() . "'");
-      $field = $this->_simpleSchema['root'][$fieldName];
-      $confKey = $this->sqlFieldConfKey($fieldName);
-      if ($confKey) {
-        $sqlConfKey = DB::getPDO()->quote($confKey, PDO::PARAM_STR);
-        $sqlValue = '';
-        if ('NOW()' == $value) {
-          $sqlValue = 'NOW()';
-        } else if ('NULL' == $value) {
-          $sqlValue = 'NULL';
-        } else {
-          $sqlValue = DB::getPDO()->quote($value, PDO::PARAM_STR);
-        }
-        $fieldAffected = DB::getPDO()->execSql("
-    			insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
-    			values ({$sqlConfKey}, {$sqlValue})
-    			on duplicate key update CONF_VAL = {$sqlValue}
-    		");
-        if ($fieldAffected > 0) $affected = 1;
-      }
-    }
-    return $affected;
-  }
-
-  public function sqlSelect($params = []) {
-    $select = [];
-    $select[] = ['ID_USER', $this->idUser];
-    $select[] = ['ID_PROCES', $this->idProcesFilter];
-    foreach ($this->_simpleSchema['root'] as $fieldName => $conf) {
-      if ('@' == substr($fieldName, 0, 1)) continue;
-      $confKey = $this->sqlFieldConfKey($fieldName);
-      if ($confKey) {
-        $sqlLastLoginKey = DB::getPDO()->quote($confKey, PDO::PARAM_STR);
-        $select[] = [$fieldName, "(select CONF_VAL from CRM_CONFIG where CONF_KEY = {$sqlLastLoginKey})"];
-      }
-    }
-    return implode("\n\t, ", array_map(function ($s) { return "{$s[1]} as {$s[0]}"; }, $select));
-  }
-  public function getItem($primaryKey, $params = []) {
-    $sqlSelect = $this->sqlSelect();
-    return DB::getPDO()->fetchFirst("
-      select {$sqlSelect}
-    ");
-  }
-  public function getItems($params = []) {
-    $sqlOrderBy = "";
-    $sqlLimitOffset = "";
-    $sqlWhereAnd = $this->_parseSqlWhere($params);
-
-    $currSortCol = V::get('order_by', 'ID', $params);
-    $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
-    // TODO: validate $currSortCol is in field list
-    // TODO: validate $currSortFlip ('asc' or 'desc')
-
-    $aliasMap = array();
-    foreach ($this->_simpleSchema['root'] as $key => $field) {
-      if ('@' === substr($key, 0, 1)) continue;
-      $aliasMap[ $key ] = (!empty($field['@alias'])) ? $field['@alias'] : $key;
-    }
-    // TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
-    $currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
-
-    if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
-      $sqlOrderBy = "order by t.`{$currSortCol}` {$currSortFlip}";
-    }
-
-    $limit = V::get('limit', 0, $params);
-    $limit = ($limit < 0) ? 0 : $limit;
-    $offset = V::get('limitstart', 0, $params);
-    $offset = ($offset < 0) ? 0 : $offset;
-    if ($limit > 0) $sqlLimitOffset = "limit {$limit} offset {$offset}";
-
-    $sqlIdProces = ($this->idProcesFilter > 0) ? $this->idProcesFilter : 'NULL';
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_objects/UserConfig',
+			'@primaryKey' => 'ID_USER',
+			'ID_USER' => [ '@type' => 'xsd:integer' ],
+			'ID_PROCES' => [ '@type' => 'xsd:integer' ],
+			'lastLogin' => [ '@type' => 'xsd:dateTime', '@confKey' => 'auth_user_{ID_USER}' ],// TODO: store last login time
+			'lastAuthCacheUpdate' => [ '@type' => 'xsd:dateTime', '@confKey' => 'acl_user_{ID_USER}_{ID_PROCES}_cache_update' ],
+			// 'appFilterProces' => [ '@type' => 'xsd:integer' ],// TODO: filter proces id set by app (web app stores in session - create UserSession Storage)
+		]
+	];
+	public $_rootTableName = 'CRM_CONFIG__#USER_CONF_VIEW';// 'CRM_CONFIG';
+	public $idUser = null;
+	public $idProcesFilter = null;
+
+	public function __construct($simpleSchema = null) {
+		parent::__construct($simpleSchema);
+		$this->idUser = User::getID();// default - current user
+		$this->idProcesFilter = 0;
+	}
+
+	public function setIdUser($idUser) {
+		$this->idUser = intval($idUser);
+		if ($this->idUser <= 0) throw new Exception("Missing id user");
+	}
+	public function getIdUser() { return $this->idUser; }
+	public function setIdProcesFilter($idProcesFilter) { $this->idProcesFilter = intval($idProcesFilter); }
+	public function getIdProcesFilter() { return $this->idProcesFilter; }
+
+	public function getTotal($params = []) { return 1; }
+
+	public function _parseSqlWhere($params = []) { return ''; }
+
+	public function sqlFieldConfKey($fieldName) {
+		if ('@' == substr($fieldName, 0, 1)) return null;
+		if (!array_key_exists($fieldName, $this->_simpleSchema['root'])) return null;
+		$field = $this->_simpleSchema['root'][$fieldName];
+		if ('ID_USER' == $fieldName) return null;
+		if ('ID_PROCES' == $fieldName) return null;
+		if (empty($field['@confKey'])) return null;
+		$confKey = $field['@confKey'];
+		$confKey = str_replace('{ID_USER}', $this->idUser, $confKey);
+		$confKey = str_replace('{ID_PROCES}', $this->idProcesFilter, $confKey);
+		return $confKey;
+	}
+
+	public function updateItem($itemPatch) {
+		DBG::log($itemPatch, 'array', '$itemPatch');
+
+		$affected = 0;
+		foreach ($itemPatch as $fieldName => $value) {
+			if (!array_key_exists($fieldName, $this->_simpleSchema['root'])) throw new Exception("Field '{$fieldName}' not exists in '" . $this->getNamespace() . "'");
+			$field = $this->_simpleSchema['root'][$fieldName];
+			$confKey = $this->sqlFieldConfKey($fieldName);
+			if ($confKey) {
+				$sqlConfKey = DB::getPDO()->quote($confKey, PDO::PARAM_STR);
+				$sqlValue = '';
+				if ('NOW()' == $value) {
+					$sqlValue = 'NOW()';
+				} else if ('NULL' == $value) {
+					$sqlValue = 'NULL';
+				} else {
+					$sqlValue = DB::getPDO()->quote($value, PDO::PARAM_STR);
+				}
+				$fieldAffected = DB::getPDO()->execSql("
+					insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
+					values ({$sqlConfKey}, {$sqlValue})
+					on duplicate key update CONF_VAL = {$sqlValue}
+				");
+				if ($fieldAffected > 0) $affected = 1;
+			}
+		}
+		return $affected;
+	}
+
+	public function sqlSelect($params = []) {
+		$select = [];
+		$select[] = ['ID_USER', $this->idUser];
+		$select[] = ['ID_PROCES', $this->idProcesFilter];
+		foreach ($this->_simpleSchema['root'] as $fieldName => $conf) {
+			if ('@' == substr($fieldName, 0, 1)) continue;
+			$confKey = $this->sqlFieldConfKey($fieldName);
+			if ($confKey) {
+				$sqlLastLoginKey = DB::getPDO()->quote($confKey, PDO::PARAM_STR);
+				$select[] = [$fieldName, "(select CONF_VAL from CRM_CONFIG where CONF_KEY = {$sqlLastLoginKey})"];
+			}
+		}
+		return implode("\n\t, ", array_map(function ($s) { return "{$s[1]} as {$s[0]}"; }, $select));
+	}
+	public function getItem($primaryKey, $params = []) {
+		$sqlSelect = $this->sqlSelect();
+		return DB::getPDO()->fetchFirst("
+			select {$sqlSelect}
+		");
+	}
+	public function getItems($params = []) {
+		$sqlOrderBy = "";
+		$sqlLimitOffset = "";
+		$sqlWhereAnd = $this->_parseSqlWhere($params);
+
+		$currSortCol = V::get('order_by', 'ID', $params);
+		$currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
+		// TODO: validate $currSortCol is in field list
+		// TODO: validate $currSortFlip ('asc' or 'desc')
+
+		$aliasMap = array();
+		foreach ($this->_simpleSchema['root'] as $key => $field) {
+			if ('@' === substr($key, 0, 1)) continue;
+			$aliasMap[ $key ] = (!empty($field['@alias'])) ? $field['@alias'] : $key;
+		}
+		// TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
+		$currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
+
+		if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
+			$sqlOrderBy = "order by t.`{$currSortCol}` {$currSortFlip}";
+		}
+
+		$limit = V::get('limit', 0, $params);
+		$limit = ($limit < 0) ? 0 : $limit;
+		$offset = V::get('limitstart', 0, $params);
+		$offset = ($offset < 0) ? 0 : $offset;
+		if ($limit > 0) $sqlLimitOffset = "limit {$limit} offset {$offset}";
+
+		$sqlIdProces = ($this->idProcesFilter > 0) ? $this->idProcesFilter : 'NULL';
 		$sqlWhereAndIdProces = ($this->idProcesFilter > 0) ? "and c.ID_PROCES = {$this->idProcesFilter}" : "and c.ID_PROCES is NULL";
-    $items = [];
-    $items[$this->idUser] = $this->getItem(1);
-    // array_walk($items, function (&$item, $key) {
-    //   $item['link_uruchom_filtr_procesu'] = Request::getPathUri() . "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$item['ID']}";
-    // });
-    return $items;
-  }
+		$items = [];
+		$items[$this->idUser] = $this->getItem(1);
+		// array_walk($items, function (&$item, $key) {
+		//	 $item['link_uruchom_filtr_procesu'] = Request::getPathUri() . "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$item['ID']}";
+		// });
+		return $items;
+	}
 
 }

+ 107 - 107
SE/se-lib/Schema/UserObjectStorageAcl.php

@@ -10,47 +10,47 @@ Lib::loadClass('UsersHelper');
  */
 class Schema_UserObjectStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_objects/UserObject',
-      '@primaryKey' => 'ID_TABLE',
-      // 'ID' => [ '@type' => 'xsd:string', '@aliasSqlConcat' => ['{table}.ID_TABLE', '-', '{table}.ID_USER', '-', '{table}.ID_PROCES'] ],
-      'ID_TABLE' => [ '@type' => 'xsd:integer' ], // `ID_TABLE` int(11) NOT NULL,
-      'ID_USER' => [ '@type' => 'xsd:integer' ], // `ID_USER` int(11) NOT NULL,
-      'ID_PROCES' => [ '@type' => 'xsd:integer' ], // `ID_PROCES` int(11) DEFAULT NULL,
-      'db' => [ '@type' => 'xsd:integer' ], // `db` int(11) NOT NULL,
-      'name' => [ '@type' => 'xsd:string' ], // `name` varchar(255) DEFAULT '',
-      'label' => [ '@type' => 'xsd:string' ], // `label` varchar(255) DEFAULT '',
-      'opis' => [ '@type' => 'xsd:string' ], // `opis` text,
-      '_rootTableName' => [ '@type' => 'xsd:string' ], // `ROOT_TABLE_NAME` varchar(255) DEFAULT '',
-      'A_LAST_SYNC' => [ '@type' => 'xsd:dateTime' ], // `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
-      // TODO: UNIQUE KEY `uniq` (ID_USER, ID_URL, ID_PROCES)
-    ]
-  ];
-  public $_rootTableName = 'CRM_AUTH_#CACHE_ACL_OBJECT';
-  public $idUser = null;
-  public $idProcesFilter = null;
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_objects/UserObject',
+			'@primaryKey' => 'ID_TABLE',
+			// 'ID' => [ '@type' => 'xsd:string', '@aliasSqlConcat' => ['{table}.ID_TABLE', '-', '{table}.ID_USER', '-', '{table}.ID_PROCES'] ],
+			'ID_TABLE' => [ '@type' => 'xsd:integer' ], // `ID_TABLE` int(11) NOT NULL,
+			'ID_USER' => [ '@type' => 'xsd:integer' ], // `ID_USER` int(11) NOT NULL,
+			'ID_PROCES' => [ '@type' => 'xsd:integer' ], // `ID_PROCES` int(11) DEFAULT NULL,
+			'db' => [ '@type' => 'xsd:integer' ], // `db` int(11) NOT NULL,
+			'name' => [ '@type' => 'xsd:string' ], // `name` varchar(255) DEFAULT '',
+			'label' => [ '@type' => 'xsd:string' ], // `label` varchar(255) DEFAULT '',
+			'opis' => [ '@type' => 'xsd:string' ], // `opis` text,
+			'_rootTableName' => [ '@type' => 'xsd:string' ], // `ROOT_TABLE_NAME` varchar(255) DEFAULT '',
+			'A_LAST_SYNC' => [ '@type' => 'xsd:dateTime' ], // `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+			// TODO: UNIQUE KEY `uniq` (ID_USER, ID_URL, ID_PROCES)
+		]
+	];
+	public $_rootTableName = 'CRM_AUTH_#CACHE_ACL_OBJECT';
+	public $idUser = null;
+	public $idProcesFilter = null;
 
-  public function __construct($simpleSchema = null) {
-    parent::__construct($simpleSchema);
-    $this->idUser = User::getID();// default - current user
-  }
+	public function __construct($simpleSchema = null) {
+		parent::__construct($simpleSchema);
+		$this->idUser = User::getID();// default - current user
+	}
 
-  public function setIdUser($idUser) {
-    $this->idUser = intval($idUser);
-    if ($this->idUser <= 0) throw new Exception("Missing id user");
-  }
-  public function getIdUser() { return $this->idUser; }
-  public function setIdProcesFilter($idProcesFilter) { $this->idProcesFilter = intval($idProcesFilter); }
-  public function getIdProcesFilter() { return $this->idProcesFilter; }
+	public function setIdUser($idUser) {
+		$this->idUser = intval($idUser);
+		if ($this->idUser <= 0) throw new Exception("Missing id user");
+	}
+	public function getIdUser() { return $this->idUser; }
+	public function setIdProcesFilter($idProcesFilter) { $this->idProcesFilter = intval($idProcesFilter); }
+	public function getIdProcesFilter() { return $this->idProcesFilter; }
 	public function updateCacheFeatures() {
-	    $dbName = DB::getPDO()->getDatabaseName();
+			$dbName = DB::getPDO()->getDatabaseName();
 		$idDatabase = DB::getPDO()->getZasobId();
-	    $sqlIdProces = ($this->idProcesFilter > 0) ? $this->idProcesFilter : 'NULL';
+			$sqlIdProces = ($this->idProcesFilter > 0) ? $this->idProcesFilter : 'NULL';
 		$sqlWhereAndIdProces = ($this->idProcesFilter > 0) ? "and c.ID_PROCES = {$this->idProcesFilter}" : "and c.ID_PROCES is NULL";
 		$sqlNoPrefixWhereAndIdProces = ($this->idProcesFilter > 0) ? "and ID_PROCES = {$this->idProcesFilter}" : "and ID_PROCES is NULL";
-	    $sqlIdProcesListSql = $this->getUsedUserProcesIdsSql();
-	    DB::getPDO()->execSql("
+			$sqlIdProcesListSql = $this->getUsedUserProcesIdsSql();
+			DB::getPDO()->execSql("
 			create table if not exists `{$this->_rootTableName}` (
 				`ID_USER` int(11) NOT NULL,
 				`ID_TABLE` int(11) NOT NULL,
@@ -62,7 +62,7 @@ class Schema_UserObjectStorageAcl extends Core_AclSimpleSchemaBase {
 				`ROOT_TABLE_NAME` varchar(255) DEFAULT '',
 				`A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
 				UNIQUE KEY `uniq` (ID_USER, ID_TABLE, ID_PROCES)
-			) ENGINE=MyISAM  DEFAULT CHARSET=latin2
+			) ENGINE=MyISAM	DEFAULT CHARSET=latin2
 		");
 		DB::getPDO()->execSql(" delete from `{$this->_rootTableName}` where ID_USER = {$this->idUser} {$sqlNoPrefixWhereAndIdProces} ");
 		if ($sqlIdProcesListSql) {
@@ -90,7 +90,7 @@ class Schema_UserObjectStorageAcl extends Core_AclSimpleSchemaBase {
 				{$sqlWhereAndIdProces}
 		");
 	}
-  public function getUsedUserProcesIdsSql() {
+	public function getUsedUserProcesIdsSql() {
 		if ($this->idProcesFilter > 0) {
 			return "
 				select i.`ID_PROCES`
@@ -107,58 +107,58 @@ class Schema_UserObjectStorageAcl extends Core_AclSimpleSchemaBase {
 				where gi.`ID_GROUP` in({$sqlIdUserGroupList})
 		";
 	}
-  public function getUsedUserGroupIds() {
+	public function getUsedUserGroupIds() {
 		// $idUserGroupList = User::getGroupsIds();
 		// TODO: acl filtr by group ids
-    return array_keys(UsersHelper::getGroupByUser($this->idUser));
+		return array_keys(UsersHelper::getGroupByUser($this->idUser));
 	}
 
-  public function getTotal($params = []) {
-    // TODO: $sqlWhereAnd = $this->_parseSqlWhere($params);
+	public function getTotal($params = []) {
+		// TODO: $sqlWhereAnd = $this->_parseSqlWhere($params);
 		$sqlWhereAndIdProces = ($this->idProcesFilter > 0) ? "and t.ID_PROCES = {$this->idProcesFilter}" : "and t.ID_PROCES is NULL";
-    return DB::getPDO()->fetchValue("
-      select count(1) as total
-      from `{$this->_rootTableName}` t
-      where t.ID_USER = {$this->idUser}
-        {$sqlWhereAndIdProces}
-    ");
-  }
+		return DB::getPDO()->fetchValue("
+			select count(1) as total
+			from `{$this->_rootTableName}` t
+			where t.ID_USER = {$this->idUser}
+				{$sqlWhereAndIdProces}
+		");
+	}
 
-  public function _parseSqlWhere($params = []) {
-    $sqlWhereAnd = "";
-    // TODO: parse where/ogc, etc.
-    return $sqlWhereAnd;
-  }
+	public function _parseSqlWhere($params = []) {
+		$sqlWhereAnd = "";
+		// TODO: parse where/ogc, etc.
+		return $sqlWhereAnd;
+	}
 
-  public function getItems($params = []) {
-    $sqlOrderBy = "";
-    $sqlLimitOffset = "";
-    $sqlWhereAnd = $this->_parseSqlWhere($params);
+	public function getItems($params = []) {
+		$sqlOrderBy = "";
+		$sqlLimitOffset = "";
+		$sqlWhereAnd = $this->_parseSqlWhere($params);
 
-    $currSortCol = V::get('order_by', 'ID', $params);
-    $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
-    // TODO: validate $currSortCol is in field list
-    // TODO: validate $currSortFlip ('asc' or 'desc')
+		$currSortCol = V::get('order_by', 'ID', $params);
+		$currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
+		// TODO: validate $currSortCol is in field list
+		// TODO: validate $currSortFlip ('asc' or 'desc')
 
-    $aliasMap = array();
-    foreach ($this->_simpleSchema['root'] as $key => $field) {
-      if ('@' === substr($key, 0, 1)) continue;
-      $aliasMap[ $key ] = (!empty($field['@alias'])) ? $field['@alias'] : $key;
-    }
-    // TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
-    $currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
+		$aliasMap = array();
+		foreach ($this->_simpleSchema['root'] as $key => $field) {
+			if ('@' === substr($key, 0, 1)) continue;
+			$aliasMap[ $key ] = (!empty($field['@alias'])) ? $field['@alias'] : $key;
+		}
+		// TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
+		$currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
 
-    if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
-      $sqlOrderBy = "order by t.`{$currSortCol}` {$currSortFlip}";
-    }
+		if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
+			$sqlOrderBy = "order by t.`{$currSortCol}` {$currSortFlip}";
+		}
 
-    $limit = V::get('limit', 0, $params);
-    $limit = ($limit < 0) ? 0 : $limit;
-    $offset = V::get('limitstart', 0, $params);
-    $offset = ($offset < 0) ? 0 : $offset;
-    if ($limit > 0) $sqlLimitOffset = "limit {$limit} offset {$offset}";
+		$limit = V::get('limit', 0, $params);
+		$limit = ($limit < 0) ? 0 : $limit;
+		$offset = V::get('limitstart', 0, $params);
+		$offset = ($offset < 0) ? 0 : $offset;
+		if ($limit > 0) $sqlLimitOffset = "limit {$limit} offset {$offset}";
 
-    // $sql = "
+		// $sql = "
 		// 	select tpvg.`ID_TABLE`
 		// 		, tpvg.`ID_DATABASE` as `db`
 		// 		, tpvg.`TABLE_NAME` as `name`
@@ -181,37 +181,37 @@ class Schema_UserObjectStorageAcl extends Core_AclSimpleSchemaBase {
 		// 		{$sqlWhereAndIdProces}
 		// ";
 		// $userAccessForTables = DB::getPDO()->fetchAllByKey($sql, 'ID_TABLE');
-    $sqlIdProces = ($this->idProcesFilter > 0) ? $this->idProcesFilter : 'NULL';
+		$sqlIdProces = ($this->idProcesFilter > 0) ? $this->idProcesFilter : 'NULL';
 		$sqlWhereAndIdProces = ($this->idProcesFilter > 0) ? "and c.ID_PROCES = {$this->idProcesFilter}" : "and c.ID_PROCES is NULL";
-    $items = DB::getPDO()->fetchAllByKey("
-      select t.ID_TABLE
-          , {$this->idUser} as ID_USER
-          , {$sqlIdProces} as ID_PROCES
-          , t.db
-          , t.name
-          , t.label
-          , t.opis
-          , t._rootTableName
+		$items = DB::getPDO()->fetchAllByKey("
+			select t.ID_TABLE
+					, {$this->idUser} as ID_USER
+					, {$sqlIdProces} as ID_PROCES
+					, t.db
+					, t.name
+					, t.label
+					, t.opis
+					, t._rootTableName
 			from (
-        select c.ID_TABLE
-            , c.db
-            , c.name
-            , c.label
-            , c.opis
-            , c.ROOT_TABLE_NAME as _rootTableName
-        from `{$this->_rootTableName}` as c
-        where c.ID_USER = {$this->idUser}
-          {$sqlWhereAndIdProces}
-      ) as t
-      where 1=1
-        {$sqlWhereAnd}
-      {$sqlOrderBy}
-      {$sqlLimitOffset}
-    ", 'ID_TABLE');
-    // array_walk($items, function (&$item, $key) {
-    //   $item['link_uruchom_filtr_procesu'] = Request::getPathUri() . "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$item['ID']}";
-    // });
-    return $items;
-  }
+				select c.ID_TABLE
+						, c.db
+						, c.name
+						, c.label
+						, c.opis
+						, c.ROOT_TABLE_NAME as _rootTableName
+				from `{$this->_rootTableName}` as c
+				where c.ID_USER = {$this->idUser}
+					{$sqlWhereAndIdProces}
+			) as t
+			where 1=1
+				{$sqlWhereAnd}
+			{$sqlOrderBy}
+			{$sqlLimitOffset}
+		", 'ID_TABLE');
+		// array_walk($items, function (&$item, $key) {
+		//	 $item['link_uruchom_filtr_procesu'] = Request::getPathUri() . "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$item['ID']}";
+		// });
+		return $items;
+	}
 
 }

+ 130 - 130
SE/se-lib/Schema/UserProcessStorageAcl.php

@@ -5,135 +5,135 @@ Lib::loadClass('ParseOgcFilter');
 
 class Schema_UserProcessStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_objects/UserProcess',
-      'ID' => [ '@type' => 'xsd:integer' ],
-      'PARENT_ID' => [ '@type' => 'xsd:integer' ],
-      'nazwa' => [ '@type' => 'xsd:string', '@alias' => 'DESC' ],
-      'opis' => [ '@type' => 'xsd:string', '@alias' => 'OPIS' ],
-      'link_uruchom_filtr_procesu' => [ '@type' => 'p5:www_link' ],
-      'autor' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_CREATE_AUTHOR' ],
-      'utworzono' => [ '@type' => 'xsd:date' , '@alias' => 'A_RECORD_CREATE_DATE' ],
-      'zaktualizował' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_UPDATE_AUTHOR' ],
-      'zaktualizowano' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_UPDATE_DATE' ]
-    ]
-  ];
-  public $_rootTableName = 'CRM_PROCES';
-  public $idUser = null;
-
-  public function __construct($simpleSchema = null) {
-    parent::__construct($simpleSchema);
-    $this->idUser = User::getID();// default - current user
-  }
-
-  public function setIdUser($idUser) { $this->idUser = intval($idUser); }
-  public function getIdUser() { return $this->idUser; }
-
-  public function getTotal($params = []) {
-    $sqlWhereAnd = $this->_parseSqlWhere($params);
-
-    $idGroupList = $this->_getUserIdGroupList();
-    if (empty($idGroupList)) throw new Exception("Brak przyipsanych grup do użytwkonika");
-    $sqlIdGroupCsv = implode(",", $idGroupList);
-
-    return DB::getPDO()->fetchValue("
-      select count(1) as total
-      from `CRM_PROCES` p
-      where p.`TYPE` = 'PROCES_INIT'
-        and p.`A_STATUS` not in('DELETED', 'OFF_HARD', 'OFF_SOFT')
-        and p.ID in (
-          select gi.ID_PROCES_INIT
-          from `CRM_PROCES_idx_GROUP_to_INIT_VIEW` as gi
-          where gi.ID_GROUP in({$sqlIdGroupCsv})
-        )
-        {$sqlWhereAnd}
-    ");
-  }
-
-  public function _parseSqlWhere($params = []) {
-    $sqlWhereAnd = "";
-    // TODO: parse where/ogc, etc.
-    return $sqlWhereAnd;
-  }
-
-  public function getItems($params = []) {
-    $sqlOrderBy = "";
-    $sqlLimitOffset = "";
-    $sqlWhereAnd = $this->_parseSqlWhere($params);
-
-    $currSortCol = V::get('order_by', 'ID', $params);
-    $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
-    // TODO: validate $currSortCol is in field list
-    // TODO: validate $currSortFlip ('asc' or 'desc')
-
-    $aliasMap = array();
-    foreach ($this->_simpleSchema['root'] as $key => $field) {
-      if ('@' === substr($key, 0, 1)) continue;
-      $aliasMap[ $key ] = (!empty($field['@alias'])) ? $field['@alias'] : $key;
-    }
-    // TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
-    $currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
-
-    if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
-      $sqlOrderBy = "order by p.`{$currSortCol}` {$currSortFlip}";
-    }
-
-    $limit = V::get('limit', 0, $params);
-    $limit = ($limit < 0) ? 0 : $limit;
-    $offset = V::get('limitstart', 0, $params);
-    $offset = ($offset < 0) ? 0 : $offset;
-    if ($limit > 0) $sqlLimitOffset = "limit {$limit} offset {$offset}";
-
-    $idGroupList = $this->_getUserIdGroupList();
-    if (empty($idGroupList)) throw new Exception("Brak przyipsanych grup do użytwkonika");
-    $sqlIdGroupCsv = implode(",", $idGroupList);
-
-    $items = DB::getPDO()->fetchAllByKey("
-      select p.ID
-        , p.PARENT_ID
-        , p.`DESC` as nazwa
-        , p.`OPIS` as opis
-        , p.A_RECORD_CREATE_AUTHOR as `autor`
-        , p.A_RECORD_CREATE_DATE as `utworzono`
-        , p.A_RECORD_UPDATE_AUTHOR as `zaktualizował`
-        , p.A_RECORD_UPDATE_DATE as `zaktualizowano`
-      from `CRM_PROCES` p
-      where p.`TYPE` = 'PROCES_INIT'
-        and p.`A_STATUS` not in('DELETED', 'OFF_HARD', 'OFF_SOFT')
-        and p.ID in (
-          select gi.ID_PROCES_INIT
-          from `CRM_PROCES_idx_GROUP_to_INIT_VIEW` as gi
-          where gi.ID_GROUP in({$sqlIdGroupCsv})
-        )
-        {$sqlWhereAnd}
-      group by p.ID
-      {$sqlOrderBy}
-      {$sqlLimitOffset}
-    ", 'ID');
-    array_walk($items, function (&$item, $key) {
-      $item['link_uruchom_filtr_procesu'] = Request::getPathUri() . "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$item['ID']}";
-    });
-    return $items;
-  }
-
-  public function _getUserIdGroupList() {
-    return array_map(
-      function ($row) {
-        return $row['ID'];
-      }
-      , DB::getPDO()->fetchAll("
-        select z.ID
-        from `CRM_AUTH_PROFILE` as up
-          left join `CRM_LISTA_ZASOBOW` as z on(z.`ID`=up.`ID_ZASOB`)
-        where
-          up.`REMOTE_ID`='{$this->idUser}'
-          and up.`A_STATUS` in('WAITING', 'NORMAL')
-          and up.`REMOTE_TABLE`='ADMIN_USERS'
-          and z.`ID` is not null
-          and z.`TYPE` in('STANOWISKO','PODMIOT','DZIAL')
-      ")
-    );
-  }
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_objects/UserProcess',
+			'ID' => [ '@type' => 'xsd:integer' ],
+			'PARENT_ID' => [ '@type' => 'xsd:integer' ],
+			'nazwa' => [ '@type' => 'xsd:string', '@alias' => 'DESC' ],
+			'opis' => [ '@type' => 'xsd:string', '@alias' => 'OPIS' ],
+			'link_uruchom_filtr_procesu' => [ '@type' => 'p5:www_link' ],
+			'autor' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_CREATE_AUTHOR' ],
+			'utworzono' => [ '@type' => 'xsd:date' , '@alias' => 'A_RECORD_CREATE_DATE' ],
+			'zaktualizował' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_UPDATE_AUTHOR' ],
+			'zaktualizowano' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_UPDATE_DATE' ]
+		]
+	];
+	public $_rootTableName = 'CRM_PROCES';
+	public $idUser = null;
+
+	public function __construct($simpleSchema = null) {
+		parent::__construct($simpleSchema);
+		$this->idUser = User::getID();// default - current user
+	}
+
+	public function setIdUser($idUser) { $this->idUser = intval($idUser); }
+	public function getIdUser() { return $this->idUser; }
+
+	public function getTotal($params = []) {
+		$sqlWhereAnd = $this->_parseSqlWhere($params);
+
+		$idGroupList = $this->_getUserIdGroupList();
+		if (empty($idGroupList)) throw new Exception("Brak przyipsanych grup do użytwkonika");
+		$sqlIdGroupCsv = implode(",", $idGroupList);
+
+		return DB::getPDO()->fetchValue("
+			select count(1) as total
+			from `CRM_PROCES` p
+			where p.`TYPE` = 'PROCES_INIT'
+				and p.`A_STATUS` not in('DELETED', 'OFF_HARD', 'OFF_SOFT')
+				and p.ID in (
+					select gi.ID_PROCES_INIT
+					from `CRM_PROCES_idx_GROUP_to_INIT_VIEW` as gi
+					where gi.ID_GROUP in({$sqlIdGroupCsv})
+				)
+				{$sqlWhereAnd}
+		");
+	}
+
+	public function _parseSqlWhere($params = []) {
+		$sqlWhereAnd = "";
+		// TODO: parse where/ogc, etc.
+		return $sqlWhereAnd;
+	}
+
+	public function getItems($params = []) {
+		$sqlOrderBy = "";
+		$sqlLimitOffset = "";
+		$sqlWhereAnd = $this->_parseSqlWhere($params);
+
+		$currSortCol = V::get('order_by', 'ID', $params);
+		$currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
+		// TODO: validate $currSortCol is in field list
+		// TODO: validate $currSortFlip ('asc' or 'desc')
+
+		$aliasMap = array();
+		foreach ($this->_simpleSchema['root'] as $key => $field) {
+			if ('@' === substr($key, 0, 1)) continue;
+			$aliasMap[ $key ] = (!empty($field['@alias'])) ? $field['@alias'] : $key;
+		}
+		// TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
+		$currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
+
+		if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
+			$sqlOrderBy = "order by p.`{$currSortCol}` {$currSortFlip}";
+		}
+
+		$limit = V::get('limit', 0, $params);
+		$limit = ($limit < 0) ? 0 : $limit;
+		$offset = V::get('limitstart', 0, $params);
+		$offset = ($offset < 0) ? 0 : $offset;
+		if ($limit > 0) $sqlLimitOffset = "limit {$limit} offset {$offset}";
+
+		$idGroupList = $this->_getUserIdGroupList();
+		if (empty($idGroupList)) throw new Exception("Brak przyipsanych grup do użytwkonika");
+		$sqlIdGroupCsv = implode(",", $idGroupList);
+
+		$items = DB::getPDO()->fetchAllByKey("
+			select p.ID
+				, p.PARENT_ID
+				, p.`DESC` as nazwa
+				, p.`OPIS` as opis
+				, p.A_RECORD_CREATE_AUTHOR as `autor`
+				, p.A_RECORD_CREATE_DATE as `utworzono`
+				, p.A_RECORD_UPDATE_AUTHOR as `zaktualizował`
+				, p.A_RECORD_UPDATE_DATE as `zaktualizowano`
+			from `CRM_PROCES` p
+			where p.`TYPE` = 'PROCES_INIT'
+				and p.`A_STATUS` not in('DELETED', 'OFF_HARD', 'OFF_SOFT')
+				and p.ID in (
+					select gi.ID_PROCES_INIT
+					from `CRM_PROCES_idx_GROUP_to_INIT_VIEW` as gi
+					where gi.ID_GROUP in({$sqlIdGroupCsv})
+				)
+				{$sqlWhereAnd}
+			group by p.ID
+			{$sqlOrderBy}
+			{$sqlLimitOffset}
+		", 'ID');
+		array_walk($items, function (&$item, $key) {
+			$item['link_uruchom_filtr_procesu'] = Request::getPathUri() . "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$item['ID']}";
+		});
+		return $items;
+	}
+
+	public function _getUserIdGroupList() {
+		return array_map(
+			function ($row) {
+				return $row['ID'];
+			}
+			, DB::getPDO()->fetchAll("
+				select z.ID
+				from `CRM_AUTH_PROFILE` as up
+					left join `CRM_LISTA_ZASOBOW` as z on(z.`ID`=up.`ID_ZASOB`)
+				where
+					up.`REMOTE_ID`='{$this->idUser}'
+					and up.`A_STATUS` in('WAITING', 'NORMAL')
+					and up.`REMOTE_TABLE`='ADMIN_USERS'
+					and z.`ID` is not null
+					and z.`TYPE` in('STANOWISKO','PODMIOT','DZIAL')
+			")
+		);
+	}
 
 }

+ 147 - 147
SE/se-lib/Schema/UserTestStatsStorageAcl.php

@@ -7,152 +7,152 @@ Lib::loadClass('ProcesTestyHelper');
 
 class Schema_UserTestStatsStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_objects/UserTestStats',
-      'ID' => [ '@type' => 'xsd:integer' ],
-      'PARENT_ID' => [ '@type' => 'xsd:integer' ],
-      'nazwa' => [ '@type' => 'xsd:string', '@alias' => 'DESC' ],
-      'opis' => [ '@type' => 'xsd:string', '@alias' => 'OPIS' ],
-      'link_uruchom_filtr_procesu' => [ '@type' => 'p5:www_link' ],
-      'link_uruchom_test_teoretyczny' => [ '@type' => 'p5:www_link', '@label' => "Wykonaj test teoretyczny"],
-      'wynik_teoretyczny' => [ '@type' => 'xsd:string', '@label' => "Wynik teoretyczny" ],
-      'wynik_teoretyczny_value' => [ '@type' => 'xsd:string', '@label' => "Wynik teoretyczny" ],
-      'wynik_praktyczny' => [ '@type' => 'xsd:string', '@label' => "Wynik praktyczny" ],
-      'wynik_unactual' => [ '@type' => 'xsd:string', '@label' => "Test nieaktualny?" ],
-      'wynik_unactual_id' => [ '@type' => 'xsd:integer', '@label' => "Nr nieaktualnego testu" ],
-      'link_popraw_test' => [ '@type' => 'xsd:integer', '@label' => "Popraw test" ],
-      'last_update_date' => [ '@type' => 'xsd:date' , '@label' => 'Ostatnia zmiana w procesie' ],
-      // 'autor' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_CREATE_AUTHOR' ],
-      // 'utworzono' => [ '@type' => 'xsd:date' , '@alias' => 'A_RECORD_CREATE_DATE' ],
-      // 'zaktualizował' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_UPDATE_AUTHOR' ],
-      // 'zaktualizowano' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_UPDATE_DATE' ]
-    ]
-  ];
-  public $_rootTableName = 'CRM_PROCES';
-  public $idUser = null;
-  public $_userProcessAcl = null;// Schema_UserProcessStorageAcl
-
-  public function __construct($simpleSchema = null) {
-    parent::__construct($simpleSchema);
-    $this->idUser = User::getID();// default - current user
-    $this->_userProcessAcl = new Schema_UserProcessStorageAcl();// Core_AclHelper::getAclByNamespace('default_objects/UserProcess')
-    $this->_userProcessAcl->setIdUser($this->idUser);
-  }
-
-  public function setIdUser($idUser) { $this->idUser = intval($idUser); $this->_userProcessAcl->setIdUser($this->idUser); }
-  public function getIdUser() { return $this->idUser; }
-
-  public function getTotal($params = []) { return $this->_userProcessAcl->getTotal(); }
-
-  public function _parseSqlWhere($params = []) { return $this->_userProcessAcl->_parseSqlWhere($params); }
-
-  public function getItems($params = []) {
-    $bupLimit = V::get('limit', 0, $params);
-    $params['limit'] = 0;
-    $items = $this->_userProcessAcl->getItems($params);
-    if (empty($items)) return $items;
-
-    $params['limit'] = $bupLimit;
-
-    $sqlWhereAnd[] = "t.ID_PROCES_INIT in (" . implode(",", array_keys($items)) . ")";
-    // if ($max_age > 0) {
-    //   $sqlWhereAnd[] = "COALESCE(UNIX_TIMESTAMP(t.`TEST_END`), 0) > (UNIX_TIMESTAMP(NOW()) - {$max_age})";
-    // }
-    $sqlWhereAnd = (!empty($sqlWhereAnd)) ? "and " . implode("\n and ", $sqlWhereAnd) : '';
-    $idUser = $this->idUser;
-    $wynikiTeoret = DB::getPDO()->fetchAllByKey("
-      select test.ID
-        ,  test.ID_PROCES_INIT
-        ,  test.OCENA
-        ,  test.A_STATUS
-        ,  test.TEST_TYPE
-        ,  test.TEST_END
-      from CRM_TESTY test
-      where test.ID in(
-        select MAX(t.ID) as ID
-        from CRM_TESTY t
-        where t.`ID_TESTER`='{$idUser}'
-          and t.TEST_TYPE = 'TEORETYCZNY'
-          {$sqlWhereAnd}
-        group by t.ID_PROCES_INIT
-      )
-    ", 'ID_PROCES_INIT');
-    DBG::log($wynikiTeoret, 'array', "\$wynikiTeoret");
-    $wynikiPraktyczne = DB::getPDO()->fetchAllByKey("
-      select test.ID
-        ,  test.ID_PROCES_INIT
-        ,  test.OCENA
-        ,  test.A_STATUS
-        ,  test.TEST_TYPE
-        ,  test.TEST_END
-      from CRM_TESTY test
-      where test.ID in(
-        select MAX(t.ID) as ID
-        from CRM_TESTY t
-        where t.`ID_TESTER`='{$idUser}'
-          and t.TEST_TYPE = 'PRAKTYCZNY'
-          {$sqlWhereAnd}
-        group by t.ID_PROCES_INIT
-      )
-    ", 'ID_PROCES_INIT');
-    DBG::log($wynikiPraktyczne, 'array', "\$wynikiPraktyczne");
-
-    $limit = V::get('limit', 0, $params);
-    $limit = ($limit < 0) ? 0 : $limit;
-    $offset = V::get('limitstart', 0, $params);
-    $offset = ($offset < 0) ? 0 : $offset;
-    $items = array_slice($items, $offset, ($limit > 0) ? $limit : null, $preserve_keys = true);
-    if (empty($items)) return $items;
-
-    $testyLastUpdate = DB::getPDO()->fetchAllByKey("
-      select i.idx_PROCES_INIT_ID as ID, max(p.`A_RECORD_UPDATE_DATE`) as max_update_date
-      from CRM_PROCES p
-        join CRM_PROCES_idx i on(i.ID_PROCES = p.ID)
-      where i.idx_PROCES_INIT_ID in (" . implode(",", array_keys($items)) . ")
-      group by i.idx_PROCES_INIT_ID
-    ", 'ID');
-    DBG::log($testyLastUpdate, 'array', "\$testyLastUpdate");
-    DBG::log($items, 'array', "\$items...");
-
-    array_walk($items, function(&$item, $key) use ($wynikiTeoret, $wynikiPraktyczne, $testyLastUpdate) {
-      $item['link_uruchom_test_teoretyczny'] = Request::getPathUri() . "procesy5.php?task=CRM_TESTY__ADD_TEST&test_type=TEORETYCZNY&proces_id={$item['ID']}";
-
-      $item['wynik_teoretyczny_value'] = (array_key_exists($item['ID'], $wynikiTeoret)) ? $wynikiTeoret[ $item['ID'] ][ 'OCENA' ] : 0;
-      $item['wynik_teoretyczny'] = ProcesTestyHelper::getOcenaLabel($item['wynik_teoretyczny_value']);
-      $wynik_praktyczny_value = (array_key_exists($item['ID'], $wynikiPraktyczne)) ? $wynikiPraktyczne[ $item['ID'] ][ 'OCENA' ] : 0;
-      $item['wynik_praktyczny'] = ProcesTestyHelper::getOcenaLabel($wynik_praktyczny_value);
-      $item['wynik_unactual'] = '';
-      $item['wynik_unactual_id'] = '';
-      $item['link_popraw_test'] = '';
-      $item['last_test_end'] = '';
-      $item['last_update_date'] = (array_key_exists($item['ID'], $testyLastUpdate)) ? $testyLastUpdate[ $item['ID'] ][ 'max_update_date' ] : null;
-      if (array_key_exists($item['ID'], $wynikiTeoret)) {
-        $test = $wynikiTeoret[ $item['ID'] ];
-        $item['last_test_end'] = $test['TEST_END'];
-
-        $max_update_date = DB::getPDO()->fetchValue("
-          select max(p.`A_RECORD_UPDATE_DATE`) as max_update_date
-    			from `CRM_PROCES` as p
-    			where p.`ID` in(
-    				select i.`ID_PROCES`
-    					from `CRM_PROCES_idx` i
-    					where i.`idx_PROCES_INIT_ID`='{$item['ID']}'
-    			)
-        ");
-        if ($item['last_update_date']) {
-          $max_update_date = substr($item['last_update_date'], 0, 10);
-          $test_end = substr($item['last_test_end'], 0, 10);
-          if ($max_update_date > $test_end) {
-            $item['wynik_unactual'] = $max_update_date;
-            $item['wynik_unactual_id'] = $test['ID'];
-            $item['link_popraw_test'] = "procesy5.php?task=CRM_TESTY__ADD_TEST&function_init=fun_CRM_TESTY__ADD_FIX&test_id={$test['ID']}";
-          }
-        }
-      }
-    });
-
-    return $items;
-  }
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_objects/UserTestStats',
+			'ID' => [ '@type' => 'xsd:integer' ],
+			'PARENT_ID' => [ '@type' => 'xsd:integer' ],
+			'nazwa' => [ '@type' => 'xsd:string', '@alias' => 'DESC' ],
+			'opis' => [ '@type' => 'xsd:string', '@alias' => 'OPIS' ],
+			'link_uruchom_filtr_procesu' => [ '@type' => 'p5:www_link' ],
+			'link_uruchom_test_teoretyczny' => [ '@type' => 'p5:www_link', '@label' => "Wykonaj test teoretyczny"],
+			'wynik_teoretyczny' => [ '@type' => 'xsd:string', '@label' => "Wynik teoretyczny" ],
+			'wynik_teoretyczny_value' => [ '@type' => 'xsd:string', '@label' => "Wynik teoretyczny" ],
+			'wynik_praktyczny' => [ '@type' => 'xsd:string', '@label' => "Wynik praktyczny" ],
+			'wynik_unactual' => [ '@type' => 'xsd:string', '@label' => "Test nieaktualny?" ],
+			'wynik_unactual_id' => [ '@type' => 'xsd:integer', '@label' => "Nr nieaktualnego testu" ],
+			'link_popraw_test' => [ '@type' => 'xsd:integer', '@label' => "Popraw test" ],
+			'last_update_date' => [ '@type' => 'xsd:date' , '@label' => 'Ostatnia zmiana w procesie' ],
+			// 'autor' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_CREATE_AUTHOR' ],
+			// 'utworzono' => [ '@type' => 'xsd:date' , '@alias' => 'A_RECORD_CREATE_DATE' ],
+			// 'zaktualizował' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_UPDATE_AUTHOR' ],
+			// 'zaktualizowano' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_UPDATE_DATE' ]
+		]
+	];
+	public $_rootTableName = 'CRM_PROCES';
+	public $idUser = null;
+	public $_userProcessAcl = null;// Schema_UserProcessStorageAcl
+
+	public function __construct($simpleSchema = null) {
+		parent::__construct($simpleSchema);
+		$this->idUser = User::getID();// default - current user
+		$this->_userProcessAcl = new Schema_UserProcessStorageAcl();// Core_AclHelper::getAclByNamespace('default_objects/UserProcess')
+		$this->_userProcessAcl->setIdUser($this->idUser);
+	}
+
+	public function setIdUser($idUser) { $this->idUser = intval($idUser); $this->_userProcessAcl->setIdUser($this->idUser); }
+	public function getIdUser() { return $this->idUser; }
+
+	public function getTotal($params = []) { return $this->_userProcessAcl->getTotal(); }
+
+	public function _parseSqlWhere($params = []) { return $this->_userProcessAcl->_parseSqlWhere($params); }
+
+	public function getItems($params = []) {
+		$bupLimit = V::get('limit', 0, $params);
+		$params['limit'] = 0;
+		$items = $this->_userProcessAcl->getItems($params);
+		if (empty($items)) return $items;
+
+		$params['limit'] = $bupLimit;
+
+		$sqlWhereAnd[] = "t.ID_PROCES_INIT in (" . implode(",", array_keys($items)) . ")";
+		// if ($max_age > 0) {
+		//	 $sqlWhereAnd[] = "COALESCE(UNIX_TIMESTAMP(t.`TEST_END`), 0) > (UNIX_TIMESTAMP(NOW()) - {$max_age})";
+		// }
+		$sqlWhereAnd = (!empty($sqlWhereAnd)) ? "and " . implode("\n and ", $sqlWhereAnd) : '';
+		$idUser = $this->idUser;
+		$wynikiTeoret = DB::getPDO()->fetchAllByKey("
+			select test.ID
+				,	test.ID_PROCES_INIT
+				,	test.OCENA
+				,	test.A_STATUS
+				,	test.TEST_TYPE
+				,	test.TEST_END
+			from CRM_TESTY test
+			where test.ID in(
+				select MAX(t.ID) as ID
+				from CRM_TESTY t
+				where t.`ID_TESTER`='{$idUser}'
+					and t.TEST_TYPE = 'TEORETYCZNY'
+					{$sqlWhereAnd}
+				group by t.ID_PROCES_INIT
+			)
+		", 'ID_PROCES_INIT');
+		DBG::log($wynikiTeoret, 'array', "\$wynikiTeoret");
+		$wynikiPraktyczne = DB::getPDO()->fetchAllByKey("
+			select test.ID
+				,	test.ID_PROCES_INIT
+				,	test.OCENA
+				,	test.A_STATUS
+				,	test.TEST_TYPE
+				,	test.TEST_END
+			from CRM_TESTY test
+			where test.ID in(
+				select MAX(t.ID) as ID
+				from CRM_TESTY t
+				where t.`ID_TESTER`='{$idUser}'
+					and t.TEST_TYPE = 'PRAKTYCZNY'
+					{$sqlWhereAnd}
+				group by t.ID_PROCES_INIT
+			)
+		", 'ID_PROCES_INIT');
+		DBG::log($wynikiPraktyczne, 'array', "\$wynikiPraktyczne");
+
+		$limit = V::get('limit', 0, $params);
+		$limit = ($limit < 0) ? 0 : $limit;
+		$offset = V::get('limitstart', 0, $params);
+		$offset = ($offset < 0) ? 0 : $offset;
+		$items = array_slice($items, $offset, ($limit > 0) ? $limit : null, $preserve_keys = true);
+		if (empty($items)) return $items;
+
+		$testyLastUpdate = DB::getPDO()->fetchAllByKey("
+			select i.idx_PROCES_INIT_ID as ID, max(p.`A_RECORD_UPDATE_DATE`) as max_update_date
+			from CRM_PROCES p
+				join CRM_PROCES_idx i on(i.ID_PROCES = p.ID)
+			where i.idx_PROCES_INIT_ID in (" . implode(",", array_keys($items)) . ")
+			group by i.idx_PROCES_INIT_ID
+		", 'ID');
+		DBG::log($testyLastUpdate, 'array', "\$testyLastUpdate");
+		DBG::log($items, 'array', "\$items...");
+
+		array_walk($items, function(&$item, $key) use ($wynikiTeoret, $wynikiPraktyczne, $testyLastUpdate) {
+			$item['link_uruchom_test_teoretyczny'] = Request::getPathUri() . "procesy5.php?task=CRM_TESTY__ADD_TEST&test_type=TEORETYCZNY&proces_id={$item['ID']}";
+
+			$item['wynik_teoretyczny_value'] = (array_key_exists($item['ID'], $wynikiTeoret)) ? $wynikiTeoret[ $item['ID'] ][ 'OCENA' ] : 0;
+			$item['wynik_teoretyczny'] = ProcesTestyHelper::getOcenaLabel($item['wynik_teoretyczny_value']);
+			$wynik_praktyczny_value = (array_key_exists($item['ID'], $wynikiPraktyczne)) ? $wynikiPraktyczne[ $item['ID'] ][ 'OCENA' ] : 0;
+			$item['wynik_praktyczny'] = ProcesTestyHelper::getOcenaLabel($wynik_praktyczny_value);
+			$item['wynik_unactual'] = '';
+			$item['wynik_unactual_id'] = '';
+			$item['link_popraw_test'] = '';
+			$item['last_test_end'] = '';
+			$item['last_update_date'] = (array_key_exists($item['ID'], $testyLastUpdate)) ? $testyLastUpdate[ $item['ID'] ][ 'max_update_date' ] : null;
+			if (array_key_exists($item['ID'], $wynikiTeoret)) {
+				$test = $wynikiTeoret[ $item['ID'] ];
+				$item['last_test_end'] = $test['TEST_END'];
+
+				$max_update_date = DB::getPDO()->fetchValue("
+					select max(p.`A_RECORD_UPDATE_DATE`) as max_update_date
+					from `CRM_PROCES` as p
+					where p.`ID` in(
+						select i.`ID_PROCES`
+							from `CRM_PROCES_idx` i
+							where i.`idx_PROCES_INIT_ID`='{$item['ID']}'
+					)
+				");
+				if ($item['last_update_date']) {
+					$max_update_date = substr($item['last_update_date'], 0, 10);
+					$test_end = substr($item['last_test_end'], 0, 10);
+					if ($max_update_date > $test_end) {
+						$item['wynik_unactual'] = $max_update_date;
+						$item['wynik_unactual_id'] = $test['ID'];
+						$item['link_popraw_test'] = "procesy5.php?task=CRM_TESTY__ADD_TEST&function_init=fun_CRM_TESTY__ADD_FIX&test_id={$test['ID']}";
+					}
+				}
+			}
+		});
+
+		return $items;
+	}
 
 }

+ 120 - 120
SE/se-lib/Schema/UserUrlActionStorageAcl.php

@@ -11,38 +11,38 @@ Lib::loadClass('UsersHelper');
  */
 class Schema_UserUrlActionStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_objects/UserUrlAction',
-      '@primaryKey' => 'ID_URL',
-      'ID_URL' => [ '@type' => 'xsd:integer' ], // `ID_URL` int(11) NOT NULL,
-      'ID_USER' => [ '@type' => 'xsd:integer' ], // `ID_USER` int(11) NOT NULL,
-      'ID_PROCES' => [ '@type' => 'xsd:integer' ], // `ID_PROCES` int(11) DEFAULT NULL,
-      'link' => [ '@type' => 'p5:www_link' ], // `link` varchar(255) DEFAULT '',
-      'label' => [ '@type' => 'xsd:string' ], // `label` varchar(255) DEFAULT '',
-      'opis' => [ '@type' => 'xsd:string' ], // `opis` text,
-      'A_LAST_SYNC' => [ '@type' => 'xsd:dateTime' ], // `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
-      // TODO: UNIQUE KEY `uniq` (ID_USER, ID_URL, ID_PROCES)
-    ]
-  ];
-  public $_rootTableName = 'CRM_AUTH_#CACHE_ACL_URL_ACTION';
-  public $idUser = null;
-  public $idProcesFilter = null;
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_objects/UserUrlAction',
+			'@primaryKey' => 'ID_URL',
+			'ID_URL' => [ '@type' => 'xsd:integer' ], // `ID_URL` int(11) NOT NULL,
+			'ID_USER' => [ '@type' => 'xsd:integer' ], // `ID_USER` int(11) NOT NULL,
+			'ID_PROCES' => [ '@type' => 'xsd:integer' ], // `ID_PROCES` int(11) DEFAULT NULL,
+			'link' => [ '@type' => 'p5:www_link' ], // `link` varchar(255) DEFAULT '',
+			'label' => [ '@type' => 'xsd:string' ], // `label` varchar(255) DEFAULT '',
+			'opis' => [ '@type' => 'xsd:string' ], // `opis` text,
+			'A_LAST_SYNC' => [ '@type' => 'xsd:dateTime' ], // `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+			// TODO: UNIQUE KEY `uniq` (ID_USER, ID_URL, ID_PROCES)
+		]
+	];
+	public $_rootTableName = 'CRM_AUTH_#CACHE_ACL_URL_ACTION';
+	public $idUser = null;
+	public $idProcesFilter = null;
 
-  public function __construct($simpleSchema = null) {
-    parent::__construct($simpleSchema);
-    $this->idUser = User::getID();// default - current user
-  }
+	public function __construct($simpleSchema = null) {
+		parent::__construct($simpleSchema);
+		$this->idUser = User::getID();// default - current user
+	}
 
-  public function setIdUser($idUser) {
-    $this->idUser = intval($idUser);
-    if ($this->idUser <= 0) throw new Exception("Missing id user");
-  }
-  public function getIdUser() { return $this->idUser; }
-  public function setIdProcesFilter($idProcesFilter) { $this->idProcesFilter = intval($idProcesFilter); }
-  public function getIdProcesFilter() { return $this->idProcesFilter; }
-  public function updateCacheFeatures() {
-    $sqlIdProces = ($this->idProcesFilter > 0) ? $this->idProcesFilter : 'NULL';
+	public function setIdUser($idUser) {
+		$this->idUser = intval($idUser);
+		if ($this->idUser <= 0) throw new Exception("Missing id user");
+	}
+	public function getIdUser() { return $this->idUser; }
+	public function setIdProcesFilter($idProcesFilter) { $this->idProcesFilter = intval($idProcesFilter); }
+	public function getIdProcesFilter() { return $this->idProcesFilter; }
+	public function updateCacheFeatures() {
+		$sqlIdProces = ($this->idProcesFilter > 0) ? $this->idProcesFilter : 'NULL';
 		$sqlWhereAndIdProces = ($this->idProcesFilter > 0) ? "and c.ID_PROCES = {$this->idProcesFilter}" : "and c.ID_PROCES is NULL";
 		$sqlNoPrefixWhereAndIdProces = ($this->idProcesFilter > 0) ? "and ID_PROCES = {$this->idProcesFilter}" : "and ID_PROCES is NULL";
 		DB::getPDO()->execSql("
@@ -55,27 +55,27 @@ class Schema_UserUrlActionStorageAcl extends Core_AclSimpleSchemaBase {
 				`opis` text,
 				`A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
 				UNIQUE KEY `uniq` (ID_USER, ID_URL, ID_PROCES)
-			) ENGINE=MyISAM  DEFAULT CHARSET=latin2
+			) ENGINE=MyISAM	DEFAULT CHARSET=latin2
 		");
 		DB::getPDO()->execSql(" delete from `{$this->_rootTableName}` where ID_USER = {$this->idUser} {$sqlNoPrefixWhereAndIdProces} ");
-	    $sqlIdProcesListSql = $this->getUsedUserProcesIdsSql();
+			$sqlIdProcesListSql = $this->getUsedUserProcesIdsSql();
 		if ($sqlIdProcesListSql) {
 			DB::getPDO()->execSql("
-		  		insert into `{$this->_rootTableName}` (ID_USER, A_LAST_SYNC, ID_PROCES, ID_URL, link, label, opis)
-		  		select {$this->idUser}
-		      		, NOW()
-		      		, {$sqlIdProces}
-		      		, upvg.`ID_URL`
-		      		, upvg.`URL_LINK` as `link`
-		      		, upvg.`URL_LABEL` as `label`
-		      		, upvg.`URL_DESC` as `opis`
-		  		from `CRM_PROCES_idx_URL_TO_PROCES_VIEW` as upvg
-		  		where upvg.`ID_PROCES` in({$sqlIdProcesListSql})
-		  		group by upvg.`ID_URL`
+					insert into `{$this->_rootTableName}` (ID_USER, A_LAST_SYNC, ID_PROCES, ID_URL, link, label, opis)
+					select {$this->idUser}
+						, NOW()
+						, {$sqlIdProces}
+						, upvg.`ID_URL`
+						, upvg.`URL_LINK` as `link`
+						, upvg.`URL_LABEL` as `label`
+						, upvg.`URL_DESC` as `opis`
+					from `CRM_PROCES_idx_URL_TO_PROCES_VIEW` as upvg
+					where upvg.`ID_PROCES` in({$sqlIdProcesListSql})
+					group by upvg.`ID_URL`
 			");
 		}
 	}
-  public function getUsedUserProcesIdsSql() {
+	public function getUsedUserProcesIdsSql() {
 		if ($this->idProcesFilter > 0) {
 			return "
 				select i.`ID_PROCES`
@@ -92,69 +92,69 @@ class Schema_UserUrlActionStorageAcl extends Core_AclSimpleSchemaBase {
 				where gi.`ID_GROUP` in({$sqlIdUserGroupList})
 		";
 	}
-  public function getUsedUserGroupIds() {
+	public function getUsedUserGroupIds() {
 		// $idUserGroupList = User::getGroupsIds();
 		// TODO: acl filtr by group ids
-    return array_keys(UsersHelper::getGroupByUser($this->idUser));
+		return array_keys(UsersHelper::getGroupByUser($this->idUser));
 	}
 
-  public function getTotal($params = []) {
-    // TODO: $sqlWhereAnd = $this->_parseSqlWhere($params);
+	public function getTotal($params = []) {
+		// TODO: $sqlWhereAnd = $this->_parseSqlWhere($params);
 		$sqlWhereAndIdProces = ($this->idProcesFilter > 0) ? "and t.ID_PROCES = {$this->idProcesFilter}" : "and t.ID_PROCES is NULL";
-    return DB::getPDO()->fetchValue("
-      select count(1) as total
-      from `{$this->_rootTableName}` t
-      where t.ID_USER = {$this->idUser}
-        {$sqlWhereAndIdProces}
-    ");
-  }
+		return DB::getPDO()->fetchValue("
+			select count(1) as total
+			from `{$this->_rootTableName}` t
+			where t.ID_USER = {$this->idUser}
+				{$sqlWhereAndIdProces}
+		");
+	}
 
-  public function _parseSqlWhere($params = []) {
-    $sqlWhereAnd = [];
-    // TODO: parse where/ogc, etc.
-    if (!empty($params)) DBG::log($params, 'array', "\$params");
-    if (!empty($params['f_link'])) {
-      if (is_string($params['f_link'])) {
-        if ('=' === substr($params['f_link'], 0, 1)) {
-          $sqlWhereAnd[] = "t.link = " . DB::getPDO()->quote(substr($params['f_link'], 1));
-        } else {
-          $sqlWhereAnd[] = "t.link like " . DB::getPDO()->quote("%{$params['f_link']}%");
-        }
-      }
-    }
-    if (!empty($params)) DBG::log($sqlWhereAnd, 'array', "\$sqlWhereAnd");
-    return (!empty($sqlWhereAnd)) ? "where " . implode(" and ", $sqlWhereAnd) : "";
-  }
+	public function _parseSqlWhere($params = []) {
+		$sqlWhereAnd = [];
+		// TODO: parse where/ogc, etc.
+		if (!empty($params)) DBG::log($params, 'array', "\$params");
+		if (!empty($params['f_link'])) {
+			if (is_string($params['f_link'])) {
+				if ('=' === substr($params['f_link'], 0, 1)) {
+					$sqlWhereAnd[] = "t.link = " . DB::getPDO()->quote(substr($params['f_link'], 1));
+				} else {
+					$sqlWhereAnd[] = "t.link like " . DB::getPDO()->quote("%{$params['f_link']}%");
+				}
+			}
+		}
+		if (!empty($params)) DBG::log($sqlWhereAnd, 'array', "\$sqlWhereAnd");
+		return (!empty($sqlWhereAnd)) ? "where " . implode(" and ", $sqlWhereAnd) : "";
+	}
 
-  public function getItems($params = []) {
-    $sqlOrderBy = "";
-    $sqlLimitOffset = "";
-    $sqlWhereAnd = $this->_parseSqlWhere($params);
+	public function getItems($params = []) {
+		$sqlOrderBy = "";
+		$sqlLimitOffset = "";
+		$sqlWhereAnd = $this->_parseSqlWhere($params);
 
-    $currSortCol = V::get('order_by', 'ID', $params);
-    $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
-    // TODO: validate $currSortCol is in field list
-    // TODO: validate $currSortFlip ('asc' or 'desc')
+		$currSortCol = V::get('order_by', 'ID', $params);
+		$currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
+		// TODO: validate $currSortCol is in field list
+		// TODO: validate $currSortFlip ('asc' or 'desc')
 
-    $aliasMap = array();
-    foreach ($this->_simpleSchema['root'] as $key => $field) {
-      if ('@' === substr($key, 0, 1)) continue;
-      $aliasMap[ $key ] = (!empty($field['@alias'])) ? $field['@alias'] : $key;
-    }
-    // TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
-    $currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
+		$aliasMap = array();
+		foreach ($this->_simpleSchema['root'] as $key => $field) {
+			if ('@' === substr($key, 0, 1)) continue;
+			$aliasMap[ $key ] = (!empty($field['@alias'])) ? $field['@alias'] : $key;
+		}
+		// TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
+		$currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
 
-    if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
-      $sqlOrderBy = "order by t.`{$currSortCol}` {$currSortFlip}";
-    }
+		if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
+			$sqlOrderBy = "order by t.`{$currSortCol}` {$currSortFlip}";
+		}
 
-    $limit = V::get('limit', 0, $params);
-    $limit = ($limit < 0) ? 0 : $limit;
-    $offset = V::get('limitstart', 0, $params);
-    $offset = ($offset < 0) ? 0 : $offset;
-    if ($limit > 0) $sqlLimitOffset = "limit {$limit} offset {$offset}";
+		$limit = V::get('limit', 0, $params);
+		$limit = ($limit < 0) ? 0 : $limit;
+		$offset = V::get('limitstart', 0, $params);
+		$offset = ($offset < 0) ? 0 : $offset;
+		if ($limit > 0) $sqlLimitOffset = "limit {$limit} offset {$offset}";
 
-    // $sql = "
+		// $sql = "
 		// 	select upvg.`ID_URL`
 		// 		, upvg.`URL_LINK` as `link`
 		// 		, upvg.`URL_LABEL` as `label`
@@ -172,34 +172,34 @@ class Schema_UserUrlActionStorageAcl extends Core_AclSimpleSchemaBase {
 		// 	from `{$this->_rootTableName}` as c
 		// 	where c.ID_USER = {$idUser}
 		// ", 'ID_URL');
-    $sqlIdProces = ($this->idProcesFilter > 0) ? $this->idProcesFilter : 'NULL';
+		$sqlIdProces = ($this->idProcesFilter > 0) ? $this->idProcesFilter : 'NULL';
 		$sqlWhereAndIdProces = ($this->idProcesFilter > 0) ? "and c.ID_PROCES = {$this->idProcesFilter}" : "and c.ID_PROCES is NULL";
-    $items = DB::getPDO()->fetchAllByKey("
-      select t.ID_URL
-          , t.ID_USER
-          , t.ID_PROCES
-          , t.link
+		$items = DB::getPDO()->fetchAllByKey("
+			select t.ID_URL
+					, t.ID_USER
+					, t.ID_PROCES
+					, t.link
 					, t.label
 					, t.opis
 			from (
-        select c.ID_URL
-            , c.ID_USER
-            , c.ID_PROCES
-            , c.link
-  					, c.label
-  					, c.opis
-        from `{$this->_rootTableName}` as c
-        where c.ID_USER = {$this->idUser}
-          {$sqlWhereAndIdProces}
-      ) as t
-      {$sqlWhereAnd}
-      {$sqlOrderBy}
-      {$sqlLimitOffset}
-    ", 'ID_URL');
-    // array_walk($items, function (&$item, $key) {
-    //   $item['link_uruchom_filtr_procesu'] = Request::getPathUri() . "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$item['ID']}";
-    // });
-    return $items;
-  }
+				select c.ID_URL
+						, c.ID_USER
+						, c.ID_PROCES
+						, c.link
+						, c.label
+						, c.opis
+				from `{$this->_rootTableName}` as c
+				where c.ID_USER = {$this->idUser}
+					{$sqlWhereAndIdProces}
+			) as t
+			{$sqlWhereAnd}
+			{$sqlOrderBy}
+			{$sqlLimitOffset}
+		", 'ID_URL');
+		// array_walk($items, function (&$item, $key) {
+		//	 $item['link_uruchom_filtr_procesu'] = Request::getPathUri() . "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$item['ID']}";
+		// });
+		return $items;
+	}
 
 }

+ 7 - 7
SE/se-lib/TableAjax.php

@@ -3699,11 +3699,11 @@ jQuery(document).ready(function(){
 					jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
 
 					window.fetch('<?= $this->syncUrl; ?>&_hash=<?= $this->_htmlID; ?>&_task=editFormJson&_primaryKey=' + recordID, {
-				    method: 'GET',
-				    credentials: 'same-origin',
-				  }).then(function(response) {
-				    return response.json()
-				  }).then(function __route_edit_payload(payload) {
+						method: 'GET',
+						credentials: 'same-origin',
+					}).then(function(response) {
+						return response.json()
+					}).then(function __route_edit_payload(payload) {
 						taskCnt.removeClass('AjaxTable-loading');
 						// console.log('editFormJson :: payload', payload)
 						if ('success' == payload.type) {
@@ -3715,14 +3715,14 @@ jQuery(document).ready(function(){
 						} else {
 							console.log('editFormJson :: ERROR payload', payload)
 						}
-				  }).catch(function __route_edit_catch(e) {
+					}).catch(function __route_edit_catch(e) {
 						taskCnt.removeClass('AjaxTable-loading');
 						console.log('editFormJson :: ERROR', e)
 						p5UI__notifyAjaxCallback({
 							type: 'error',
 							msg: 'Request error ' + e
 						});
-				  })
+					})
 				},
 				HIST: TableAjax__HIST_Route,
 				FILES: function tableAjaxFiles(args) {

+ 511 - 511
SE/static/p5UI/buildDom.js

@@ -1,33 +1,33 @@
 (function (global, p5VendorJs) {
-  if (!p5VendorJs.React) throw "Missing React"
-  if (!p5VendorJs.ReactDOM) throw "Missing ReactDOM"
-  if (!p5VendorJs.createReactClass) throw "Missing createReactClass"
-  var React = p5VendorJs.React
-  var ReactDOM = p5VendorJs.ReactDOM
-  var createReactClass = p5VendorJs.createReactClass
-  var h = React.createElement
-  var DBG = 0
+	if (!p5VendorJs.React) throw "Missing React"
+	if (!p5VendorJs.ReactDOM) throw "Missing ReactDOM"
+	if (!p5VendorJs.createReactClass) throw "Missing createReactClass"
+	var React = p5VendorJs.React
+	var ReactDOM = p5VendorJs.ReactDOM
+	var createReactClass = p5VendorJs.createReactClass
+	var h = React.createElement
+	var DBG = 0
 
-  var P5UI__RawHtml = createReactClass({
-    componentDidMount: function () {
-      if (this.props.rawHtml) {
-        this.rootNode.innerHTML = this.props.rawHtml
-      }
-    },
-    render: function () {
-      return h('div', {
-        ref: function (node) { this.rootNode = node; }.bind(this),
-      })
-    }
-  })
-  global.p5VendorJs['P5UI__RawHtml'] = P5UI__RawHtml
+	var P5UI__RawHtml = createReactClass({
+		componentDidMount: function () {
+			if (this.props.rawHtml) {
+				this.rootNode.innerHTML = this.props.rawHtml
+			}
+		},
+		render: function () {
+			return h('div', {
+				ref: function (node) { this.rootNode = node; }.bind(this),
+			})
+		}
+	})
+	global.p5VendorJs['P5UI__RawHtml'] = P5UI__RawHtml
 
-  var P5UI__FeatureEditForm = createReactClass({
-    componentDidMount: function () {
-      if(DBG)console.warn('P5UI__FeatureEditForm::componentDidMount this.rootNode', this.rootNode)
-      jQuery(this.rootNode).find('textarea').autosize();
+	var P5UI__FeatureEditForm = createReactClass({
+		componentDidMount: function () {
+			if(DBG)console.warn('P5UI__FeatureEditForm::componentDidMount this.rootNode', this.rootNode)
+			jQuery(this.rootNode).find('textarea').autosize();
 			jQuery(this.rootNode).find('.frm-help').popover({trigger:'hover'});
-      jQuery(this.rootNode).find('.show-last-value input').on('input', function(e) {
+			jQuery(this.rootNode).find('.show-last-value input').on('input', function(e) {
 				var input, btn, btnIco;
 				input = jQuery(e.target);
 				btn = input.next('.button-appendBack');
@@ -50,506 +50,506 @@
 					}
 				}
 			});
-    },
-    submit: function (e) {
-      if(DBG)console.warn('P5UI__FeatureEditForm::submit this.rootNode', this.rootNode)
-      e.preventDefault()
+		},
+		submit: function (e) {
+			if(DBG)console.warn('P5UI__FeatureEditForm::submit this.rootNode', this.rootNode)
+			e.preventDefault()
 
-      var formData = {};
-      jQuery(this.rootNode).serializeArray().map(function(i) { formData[i.name] = i.value; });// TODO: edit Widget - send only updated fields
-      // TODO: change Edit btn to return to edit record with fields -> show form
+			var formData = {};
+			jQuery(this.rootNode).serializeArray().map(function(i) { formData[i.name] = i.value; });// TODO: edit Widget - send only updated fields
+			// TODO: change Edit btn to return to edit record with fields -> show form
 
-      var taskCont = jQuery(this.rootNode).parents('.AjaxTableTaskCnt').parent(); // jQuery('#{$this->_htmlID}_task').parent();
-      //taskCont.empty();
-      taskCont.children().fadeOut('slow');
-      var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
-        , alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
-      jQuery('<div class="alert alert-info"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> zapisywanie ... </div></div>').appendTo(alertCnt);
+			var taskCont = jQuery(this.rootNode).parents('.AjaxTableTaskCnt').parent(); // jQuery('#{$this->_htmlID}_task').parent();
+			//taskCont.empty();
+			taskCont.children().fadeOut('slow');
+			var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
+				, alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
+			jQuery('<div class="alert alert-info"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> zapisywanie ... </div></div>').appendTo(alertCnt);
 
-      function notifyAjaxCallback(data) {
-        var notify = {}, outMsg = '';
-        notify.type = (data && data.type)? data.type : '';
-        notify.msg = (data && data.msg)? data.msg : '';
-        switch (notify.type) {
-          case 'success':
-            if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
-            break;
-          case 'info':
-            if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
-            break;
-          case 'error':
-            if (!notify.msg) notify.msg = 'Wystąpiły błędy';
-            break;
-          case 'warning':
-            notify.type = 'warn';
-            if (!notify.msg) notify.msg = 'Wystąpiły błędy';
-            break;
-          default:
-            notify.msg = 'Nieznany błąd';
-            if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
-            notify.type = '';
-        }
-        jQuery.notify(notify.msg, notify.type);
-        var alertType = ('error' == data.type) ? 'danger' : data.type;
-        outMsg = '<div class="alert alert-' + alertType + '">' + notify.msg + '</div>';
-        return outMsg;
-      }
+			function notifyAjaxCallback(data) {
+				var notify = {}, outMsg = '';
+				notify.type = (data && data.type)? data.type : '';
+				notify.msg = (data && data.msg)? data.msg : '';
+				switch (notify.type) {
+					case 'success':
+						if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
+						break;
+					case 'info':
+						if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
+						break;
+					case 'error':
+						if (!notify.msg) notify.msg = 'Wystąpiły błędy';
+						break;
+					case 'warning':
+						notify.type = 'warn';
+						if (!notify.msg) notify.msg = 'Wystąpiły błędy';
+						break;
+					default:
+						notify.msg = 'Nieznany błąd';
+						if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
+						notify.type = '';
+				}
+				jQuery.notify(notify.msg, notify.type);
+				var alertType = ('error' == data.type) ? 'danger' : data.type;
+				outMsg = '<div class="alert alert-' + alertType + '">' + notify.msg + '</div>';
+				return outMsg;
+			}
 
-      var idRecord = this.props.idRecord
-      var tableLabelHtml = this.props.tableLabelHtml
-      superagent
-        .post(this.props.ajaxSaveUrl)
-        .type('json') // header ĺapplication/x-www-form-urlencoded' requires type('form');
-        .send({
-          namespace: this.props.namespace,
-          primaryKey: this.props.idRecord,
-          form: formData
-        })
-        .set('Accept', 'application/json')
-        .end(function(err, res) {
-          var payload;
-          if (err || !res.ok || 'application/json' !== res.type) {
-            payload = {type: 'warning', msg: res.body.msg || 'Wystąpiły błędy', body: res.body};
-          } else {
-            payload = {type: 'success', msg: res.body.msg || '', body: res.body};
-          }
-          var data = res.body;
+			var idRecord = this.props.idRecord
+			var tableLabelHtml = this.props.tableLabelHtml
+			superagent
+				.post(this.props.ajaxSaveUrl)
+				.type('json') // header ĺapplication/x-www-form-urlencoded' requires type('form');
+				.send({
+					namespace: this.props.namespace,
+					primaryKey: this.props.idRecord,
+					form: formData
+				})
+				.set('Accept', 'application/json')
+				.end(function(err, res) {
+					var payload;
+					if (err || !res.ok || 'application/json' !== res.type) {
+						payload = {type: 'warning', msg: res.body.msg || 'Wystąpiły błędy', body: res.body};
+					} else {
+						payload = {type: 'success', msg: res.body.msg || '', body: res.body};
+					}
+					var data = res.body;
 
-          alertCntWrap.removeClass('AjaxTable-loading');
-          alertCnt.empty();
-          if (false === ['success', 'info'].indexOf(payload.type)) {
-            jQuery(errorTxt).appendTo(alertCnt);
-            var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
-            jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli '+tableLabelHtml+'</a>').appendTo(errLinks);
-            var backToEditBtn = jQuery('<a href="#EDIT/'+idRecord+'/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-pencil"></i> Popraw dane '+idRecord+'</a>').appendTo(errLinks);
-            backToEditBtn.on('click', function(){
-              alertCnt.remove();
-              taskCont.children().fadeIn('slow');
-              return false;
-            });
-          } else {
-            var outMsg = notifyAjaxCallback(payload);
-            var out = '';
-            out += outMsg;
-            out += '<div class="breadcrumb">' +
-                ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli '+tableLabelHtml+'</a>' +
-                ' <a href="#EDIT/'+idRecord+'/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord '+idRecord+'</a>' +
-              '</div>';
-            jQuery(out).appendTo(alertCnt);
+					alertCntWrap.removeClass('AjaxTable-loading');
+					alertCnt.empty();
+					if (false === ['success', 'info'].indexOf(payload.type)) {
+						jQuery(errorTxt).appendTo(alertCnt);
+						var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
+						jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli '+tableLabelHtml+'</a>').appendTo(errLinks);
+						var backToEditBtn = jQuery('<a href="#EDIT/'+idRecord+'/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-pencil"></i> Popraw dane '+idRecord+'</a>').appendTo(errLinks);
+						backToEditBtn.on('click', function(){
+							alertCnt.remove();
+							taskCont.children().fadeIn('slow');
+							return false;
+						});
+					} else {
+						var outMsg = notifyAjaxCallback(payload);
+						var out = '';
+						out += outMsg;
+						out += '<div class="breadcrumb">' +
+								' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli '+tableLabelHtml+'</a>' +
+								' <a href="#EDIT/'+idRecord+'/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord '+idRecord+'</a>' +
+							'</div>';
+						jQuery(out).appendTo(alertCnt);
 
-            // add rowFunctions from response
-            if (data && data.rowFunctions && data.primaryKey) {
-              var rowFunWrapNode = $('<div class="container"></div>').insertAfter(alertCnt);
-              var rowFunListNode = $('<ul></ul>').appendTo(rowFunWrapNode);
-              var keys = Object.keys(data.rowFunctions),
-                  total = keys.length,
-                  moreFuncBtnNode,
-                  moreFunctions = [],
-                  idx
-              ;
-              moreFunctions = keys.splice(3);
-              keys.forEach(function(key) {
-                var cellNode = $('<li></li>');
-                var funObj = data.rowFunctions[key],
-                    funcNode = p5UI_TableAjax_generateFunctionNode(funObj, data.primaryKey, {ico: true, label: true})
-                ;
-                funcNode.appendTo(cellNode);
-                cellNode.appendTo(rowFunListNode);
-              });
-            }
-          }
-        })
-    },
-    render: function () {
-      if(DBG)console.warn('P5UI__FeatureEditForm::render this.props', this.props)
-      var formProps = Object.assign({}, this.props)
-      delete formProps.children
-      return h('form', Object.assign(formProps, {
-        ref: function (node) { this.rootNode = node; }.bind(this),
-        onSubmit: this.submit.bind(this)
-      }), this.props.children)
-    }
-  })
-  global.p5VendorJs['P5UI__FeatureEditForm'] = P5UI__FeatureEditForm
+						// add rowFunctions from response
+						if (data && data.rowFunctions && data.primaryKey) {
+							var rowFunWrapNode = $('<div class="container"></div>').insertAfter(alertCnt);
+							var rowFunListNode = $('<ul></ul>').appendTo(rowFunWrapNode);
+							var keys = Object.keys(data.rowFunctions),
+									total = keys.length,
+									moreFuncBtnNode,
+									moreFunctions = [],
+									idx
+							;
+							moreFunctions = keys.splice(3);
+							keys.forEach(function(key) {
+								var cellNode = $('<li></li>');
+								var funObj = data.rowFunctions[key],
+										funcNode = p5UI_TableAjax_generateFunctionNode(funObj, data.primaryKey, {ico: true, label: true})
+								;
+								funcNode.appendTo(cellNode);
+								cellNode.appendTo(rowFunListNode);
+							});
+						}
+					}
+				})
+		},
+		render: function () {
+			if(DBG)console.warn('P5UI__FeatureEditForm::render this.props', this.props)
+			var formProps = Object.assign({}, this.props)
+			delete formProps.children
+			return h('form', Object.assign(formProps, {
+				ref: function (node) { this.rootNode = node; }.bind(this),
+				onSubmit: this.submit.bind(this)
+			}), this.props.children)
+		}
+	})
+	global.p5VendorJs['P5UI__FeatureEditForm'] = P5UI__FeatureEditForm
 
-  var P5UI__Typespecial = createReactClass({
-    componentDidMount: function () {
-      if(DBG)console.log('TS::componentDidMount (['+this.props.idField+'] '+this.props.fieldNamespace+') ...')
-      // console.log('TS::componentDidMount (['+this.props.idField+'] '+this.props.fieldNamespace+') this.rootNode', this.rootNode) // OK
-    	var fldNode = jQuery(document.getElementById(this.props.fieldName)) // jQuery('#{$fName}')
-      var tsNode = jQuery(this.rootNode) // jQuery('#ts-{$fName}')
-      var ajaxDataUrlBase = this.props.ajaxDataUrlBase
-    	if (!fldNode && !tsNode) {
-        console.log("BUG Missing fldNode or tsNode in P5UI__Typespecial")
-    		return;
-    	}
-    	if (!ajaxDataUrlBase) {
-        console.log("BUG Missing ajaxDataUrlBase in P5UI__Typespecial")
-    		return;
-    	}
+	var P5UI__Typespecial = createReactClass({
+		componentDidMount: function () {
+			if(DBG)console.log('TS::componentDidMount (['+this.props.idField+'] '+this.props.fieldNamespace+') ...')
+			// console.log('TS::componentDidMount (['+this.props.idField+'] '+this.props.fieldNamespace+') this.rootNode', this.rootNode) // OK
+			var fldNode = jQuery(document.getElementById(this.props.fieldName)) // jQuery('#{$fName}')
+			var tsNode = jQuery(this.rootNode) // jQuery('#ts-{$fName}')
+			var ajaxDataUrlBase = this.props.ajaxDataUrlBase
+			if (!fldNode && !tsNode) {
+				console.log("BUG Missing fldNode or tsNode in P5UI__Typespecial")
+				return;
+			}
+			if (!ajaxDataUrlBase) {
+				console.log("BUG Missing ajaxDataUrlBase in P5UI__Typespecial")
+				return;
+			}
 
-    	fldNode.attr('name', '');
-    	fldNode.hide();
-    	if (fldNode.parent().hasClass('show-last-value')) {
-    		fldNode.parent().hide();
-    	}
-    	tsNode.attr('name', this.props.frmFldName)
-    	tsNode.attr('tabindex', fldNode.attr('tabindex'))
+			fldNode.attr('name', '');
+			fldNode.hide();
+			if (fldNode.parent().hasClass('show-last-value')) {
+				fldNode.parent().hide();
+			}
+			tsNode.attr('name', this.props.frmFldName)
+			tsNode.attr('tabindex', fldNode.attr('tabindex'))
 
-      var getFetchCallback = ('TypespecialVariable' === this.props.type)
-        ? function (query, callback) {
-            return function(res) {
-    					for (var i in res) {
-    						if (!res[i].name || res[i].id != res[i].name) {
-    							res[i].name = res[i].id + ': ' + res[i].name;
-    						}
-    					}
-    					callback(res);
-    				}
-          }
-        : function (query, callback) {
-            return function(res) {
-              var i, prefix, prefixLen;
-              for (i in res) {
-                prefix = '' + res[i].id;
-                prefixLen = prefix.length;
-                if (prefixLen > 0 && prefix !== res[i].name.substr(0, prefixLen)) {
-                  res[i].name = res[i].id + ': ' + res[i].name;
-                }
-                res[i]['\$order'] = 1 + (parseInt(i) || 0); // set order from request
-              }
-              callback(res);
-            }
-          }
-      ;
-      var scoreCallback = ('TypespecialVariable' === this.props.type)
-        ? function(search) {
-      			var score = this.getScoreFunction(search);
-      			return function(item) {
-      				// console.log('score:item:', item, ', score:', score(item));
-      				if (search && search == item.id) {
-      					return 1;
-      				} else {
-      					return score(item);// score(item) * (1 + Math.min(item.watchers / 100, 1));
-      				}
-      			};
-      		}
-        : function(query) {
-      			// console.log('Typespecial({$fName})::score: q(', query, ')');
-      			var score = this.getScoreFunction(query);
-      			return function(item) {
-      				var retScore = 0, lName = ('' + item.name).toLowerCase(), lQuery = query.toLowerCase();
-      				if (query.search(' ') > -1) {
-      					retScore = score(item);
-      				}
-      				else {
-      					if (lQuery + ':' == lName.substr(0, lQuery.length + 1)) {
-      						retScore = 100;
-      					} else if (lName.search(lQuery) > -1) {
-      						retScore = 90 - lName.search(lQuery);
-      					} else {
-      						retScore = 0;
-      					}
-      				}
-      				// console.log('Typespecial({$fName})::score: q(', lQuery, ') , retScore(', retScore, '), score(', score(item), '), item.name(', item.name, ') item.id:', item.id);
-      				return retScore;
-      			};
-      		}
-      ;
+			var getFetchCallback = ('TypespecialVariable' === this.props.type)
+				? function (query, callback) {
+						return function(res) {
+							for (var i in res) {
+								if (!res[i].name || res[i].id != res[i].name) {
+									res[i].name = res[i].id + ': ' + res[i].name;
+								}
+							}
+							callback(res);
+						}
+					}
+				: function (query, callback) {
+						return function(res) {
+							var i, prefix, prefixLen;
+							for (i in res) {
+								prefix = '' + res[i].id;
+								prefixLen = prefix.length;
+								if (prefixLen > 0 && prefix !== res[i].name.substr(0, prefixLen)) {
+									res[i].name = res[i].id + ': ' + res[i].name;
+								}
+								res[i]['\$order'] = 1 + (parseInt(i) || 0); // set order from request
+							}
+							callback(res);
+						}
+					}
+			;
+			var scoreCallback = ('TypespecialVariable' === this.props.type)
+				? function(search) {
+						var score = this.getScoreFunction(search);
+						return function(item) {
+							// console.log('score:item:', item, ', score:', score(item));
+							if (search && search == item.id) {
+								return 1;
+							} else {
+								return score(item);// score(item) * (1 + Math.min(item.watchers / 100, 1));
+							}
+						};
+					}
+				: function(query) {
+						// console.log('Typespecial({$fName})::score: q(', query, ')');
+						var score = this.getScoreFunction(query);
+						return function(item) {
+							var retScore = 0, lName = ('' + item.name).toLowerCase(), lQuery = query.toLowerCase();
+							if (query.search(' ') > -1) {
+								retScore = score(item);
+							}
+							else {
+								if (lQuery + ':' == lName.substr(0, lQuery.length + 1)) {
+									retScore = 100;
+								} else if (lName.search(lQuery) > -1) {
+									retScore = 90 - lName.search(lQuery);
+								} else {
+									retScore = 0;
+								}
+							}
+							// console.log('Typespecial({$fName})::score: q(', lQuery, ') , retScore(', retScore, '), score(', score(item), '), item.name(', item.name, ') item.id:', item.id);
+							return retScore;
+						};
+					}
+			;
 
-    	tsNode.selectize({
-    		theme: 'typespecial',
-    		valueField: 'id',
-    		labelField: 'id',
-    		searchField: 'name',
-    		sortField: ('TypespecialVariable' === this.props.type) ? 'name' : '$order', // TODO: skip in Typespecial - default sort field is '$order'
-    		create: this.props.create,
-    		delimiter: ';',
-    		dataAttr: 'typespecial',
-    		preload: this.props.preload || false,
-    		options: this.props.options,
-    		render: {
-    			item: function(item, escape) {
-    				return '<div>' +
-    					'<span class=\"name\">' + escape(item.name || item.id) + '</span>' +
-    				'</div>';
-    			},
-    			option: function(item, escape) {
-    				return '<div>' +
-    					'<span class=\"title\">' +
-    						escape(item.name || item.id) +
-    					'</span>' +
-    				'</div>';
-    			}
-    		},
-    		onItemAdd: function(value, item) {// Invoked when an item is selected.
-    			var curSel = this.options[value] || null, fieldExport;
-    			if (curSel && curSel.exports) {
-    				for (var i in curSel.exports) {
-    					fieldExport = jQuery('#ts-f' + i);
-    					if (fieldExport.length) {
-                //console.log('--- onItemAdd fieldExport.selectize(',fieldExport.selectize,')', fieldExport);
-    						if (fieldExport.get(0).selectize) {
-    							fieldExport.get(0).selectize.addOption({id:curSel.exports[i], name:curSel.exports[i]});
-    							fieldExport.get(0).selectize.setValue(curSel.exports[i]);
-    						} else {
-    							//jQuery('#f' + i).val(curSel.exports[i]);
-    						}
-    					} else {
-    						fieldExport = jQuery('#f' + i);
-    						if (fieldExport.is('input')) {
-    							jQuery('#f' + i).val(curSel.exports[i]);
-    						} else if (fieldExport.is('select')) {
-    							//TODO: add option and select //jQuery('#f' + i).val(curSel.exports[i]);
-    						}
-    					}
-    				}
-    			}
-    		},
-    		score: scoreCallback,
-    		load: function(query, callback) {
-    			// if (!query.length) return callback(); // empty query at preload action
-    			$.ajax({
-    				url: ajaxDataUrlBase,
-    				data: 'q=' + encodeURIComponent(query),
-    				type: 'POST',
-    				error: function() {
-    					callback();
-    				},
-    				success: getFetchCallback(query, callback),
-    			});
-    		}
-    	});
-    },
-    render: function () {
-      if(DBG)console.log('TS::render (['+this.props.idField+'] '+this.props.fieldNamespace+') props', this.props)
-      return h('div', {
-        'className': "typespecial",
-        'style': { 'max-width': '366px' }
-      }, [
-        h('select', {
-          'ref': function (node) { this.rootNode = node; }.bind(this),
-        }, this.props.children)
-      ])
-    }
-  })
-  global.p5VendorJs['P5UI__Typespecial'] = P5UI__Typespecial
+			tsNode.selectize({
+				theme: 'typespecial',
+				valueField: 'id',
+				labelField: 'id',
+				searchField: 'name',
+				sortField: ('TypespecialVariable' === this.props.type) ? 'name' : '$order', // TODO: skip in Typespecial - default sort field is '$order'
+				create: this.props.create,
+				delimiter: ';',
+				dataAttr: 'typespecial',
+				preload: this.props.preload || false,
+				options: this.props.options,
+				render: {
+					item: function(item, escape) {
+						return '<div>' +
+							'<span class=\"name\">' + escape(item.name || item.id) + '</span>' +
+						'</div>';
+					},
+					option: function(item, escape) {
+						return '<div>' +
+							'<span class=\"title\">' +
+								escape(item.name || item.id) +
+							'</span>' +
+						'</div>';
+					}
+				},
+				onItemAdd: function(value, item) {// Invoked when an item is selected.
+					var curSel = this.options[value] || null, fieldExport;
+					if (curSel && curSel.exports) {
+						for (var i in curSel.exports) {
+							fieldExport = jQuery('#ts-f' + i);
+							if (fieldExport.length) {
+								//console.log('--- onItemAdd fieldExport.selectize(',fieldExport.selectize,')', fieldExport);
+								if (fieldExport.get(0).selectize) {
+									fieldExport.get(0).selectize.addOption({id:curSel.exports[i], name:curSel.exports[i]});
+									fieldExport.get(0).selectize.setValue(curSel.exports[i]);
+								} else {
+									//jQuery('#f' + i).val(curSel.exports[i]);
+								}
+							} else {
+								fieldExport = jQuery('#f' + i);
+								if (fieldExport.is('input')) {
+									jQuery('#f' + i).val(curSel.exports[i]);
+								} else if (fieldExport.is('select')) {
+									//TODO: add option and select //jQuery('#f' + i).val(curSel.exports[i]);
+								}
+							}
+						}
+					}
+				},
+				score: scoreCallback,
+				load: function(query, callback) {
+					// if (!query.length) return callback(); // empty query at preload action
+					$.ajax({
+						url: ajaxDataUrlBase,
+						data: 'q=' + encodeURIComponent(query),
+						type: 'POST',
+						error: function() {
+							callback();
+						},
+						success: getFetchCallback(query, callback),
+					});
+				}
+			});
+		},
+		render: function () {
+			if(DBG)console.log('TS::render (['+this.props.idField+'] '+this.props.fieldNamespace+') props', this.props)
+			return h('div', {
+				'className': "typespecial",
+				'style': { 'max-width': '366px' }
+			}, [
+				h('select', {
+					'ref': function (node) { this.rootNode = node; }.bind(this),
+				}, this.props.children)
+			])
+		}
+	})
+	global.p5VendorJs['P5UI__Typespecial'] = P5UI__Typespecial
 
-  var P5UI__FeatureRowFunctions = createReactClass({
-    componentDidMount: function () {
-      if(DBG)console.warn('P5UI__FeatureRowFunctions::componentDidMount this.rootNode', this.rootNode)
-      if (this.props.rawHtml) {
-        if(DBG)console.warn('P5UI__FeatureRowFunctions::componentDidMount this.props.rawHtml', this.props.rawHtml)
-        this.rootNode.innerHTML = this.props.rawHtml
-      }
-    },
-    render: function () {
-      var showLabels = this.props.showLabels || false
-      var functions = this.props.functions || {}
-      if (!this.props.id) return h('div', { 'className': 'alert alert-danger' }, "Missing ID")
-      if(DBG)console.warn('P5UI__FeatureRowFunctions::render this.props', this.props)
-      return h('div', {
-        ref: function (node) { this.rootNode = node; }.bind(this),
-      }, [
-        ('hist' in functions)
-          ? h('a', { className: "btn btn-xs btn-link", href: functions.hist.href.replace("{0}", this.props.id), title: functions.hist.title }, [ h('span', { className: functions.hist.ico }), h('span', { style: {'padding': '0 6px'} }, functions.hist.title) ])
-          : null
-        ,
-        ('files' in functions)
-          ? h('a', { className: "btn btn-xs btn-link", href: functions.files.href.replace("{0}", this.props.id), title: functions.files.title }, [ h('span', { className: functions.files.ico }), h('span', { style: {'padding': '0 6px'} }, functions.files.title) ])
-          : null
-        ,
-        ('msgs' in functions)
-          ? h('a', { className: "btn btn-xs btn-link", href: functions.msgs.href.replace("{0}", this.props.id), title: functions.msgs.title }, [ h('span', { className: functions.msgs.ico }), h('span', { style: {'padding': '0 6px'} }, functions.msgs.title) ])
-          : null
-        ,
-        (this.props.viewMoreDropdown)
-          ? h(P5UI__MoreFunctionsDropdownAjax, this.props.viewMoreDropdown)
-          : null
-        ,
-      ])
-    }
-  })
-  global.p5VendorJs['P5UI__FeatureRowFunctions'] = P5UI__FeatureRowFunctions
+	var P5UI__FeatureRowFunctions = createReactClass({
+		componentDidMount: function () {
+			if(DBG)console.warn('P5UI__FeatureRowFunctions::componentDidMount this.rootNode', this.rootNode)
+			if (this.props.rawHtml) {
+				if(DBG)console.warn('P5UI__FeatureRowFunctions::componentDidMount this.props.rawHtml', this.props.rawHtml)
+				this.rootNode.innerHTML = this.props.rawHtml
+			}
+		},
+		render: function () {
+			var showLabels = this.props.showLabels || false
+			var functions = this.props.functions || {}
+			if (!this.props.id) return h('div', { 'className': 'alert alert-danger' }, "Missing ID")
+			if(DBG)console.warn('P5UI__FeatureRowFunctions::render this.props', this.props)
+			return h('div', {
+				ref: function (node) { this.rootNode = node; }.bind(this),
+			}, [
+				('hist' in functions)
+					? h('a', { className: "btn btn-xs btn-link", href: functions.hist.href.replace("{0}", this.props.id), title: functions.hist.title }, [ h('span', { className: functions.hist.ico }), h('span', { style: {'padding': '0 6px'} }, functions.hist.title) ])
+					: null
+				,
+				('files' in functions)
+					? h('a', { className: "btn btn-xs btn-link", href: functions.files.href.replace("{0}", this.props.id), title: functions.files.title }, [ h('span', { className: functions.files.ico }), h('span', { style: {'padding': '0 6px'} }, functions.files.title) ])
+					: null
+				,
+				('msgs' in functions)
+					? h('a', { className: "btn btn-xs btn-link", href: functions.msgs.href.replace("{0}", this.props.id), title: functions.msgs.title }, [ h('span', { className: functions.msgs.ico }), h('span', { style: {'padding': '0 6px'} }, functions.msgs.title) ])
+					: null
+				,
+				(this.props.viewMoreDropdown)
+					? h(P5UI__MoreFunctionsDropdownAjax, this.props.viewMoreDropdown)
+					: null
+				,
+			])
+		}
+	})
+	global.p5VendorJs['P5UI__FeatureRowFunctions'] = P5UI__FeatureRowFunctions
 
-  var P5UI__MoreFunctionsDropdownAjax = createReactClass({
-    componentDidMount: function () {
-      jQuery(this.rootNode).popover({
-        container: 'body',
-        placement: 'bottom',
-        trigger: 'click',
-        // title: e.data.col + '<a href="#" class="glyphicon glyphicon-remove pull-right" onclick="return hidePopover();"></a>',
-        title: 'Więcej funkcji dla rekordu nr ' + this.props.primaryKey, // '<div style="display:block;position:relative;padding:0 20px 0 0;">' + (this.props.friendly || colName) + ' <button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:0;top:0;">&times;</button>' + '</div>',
-        html: true,
-        content: 'TODO: list...', // this.renderListToString.bind(this),
-        template: '' +
-          '<div class="popover" role="tooltip" style="max-width:600px;width:400px;">' +
-            '<div class="arrow"></div>' +
-            '<div style="display:block;position:relative;">' +
-              '<div class="popover-title">' +
-              '</div>' +
-            '</div>' +
-            '<div class="popover-content"></div>' +
-          '</div>'
-      })
-      this.setState({ 'isOpen': false })
-    },
-    componentWillUnmount: function () {
-      if(DBG)console.warn("P5UI__MoreFunctionsDropdownAjax::componentWillUnmount")
-      jQuery(this.rootNode).popover('destroy')
-    },
-    componentWillMount: function() {
-      this._closeDropdownIfClickedOutside = function (event) {
-    		if (!this.state.isOpen) return;
+	var P5UI__MoreFunctionsDropdownAjax = createReactClass({
+		componentDidMount: function () {
+			jQuery(this.rootNode).popover({
+				container: 'body',
+				placement: 'bottom',
+				trigger: 'click',
+				// title: e.data.col + '<a href="#" class="glyphicon glyphicon-remove pull-right" onclick="return hidePopover();"></a>',
+				title: 'Więcej funkcji dla rekordu nr ' + this.props.primaryKey, // '<div style="display:block;position:relative;padding:0 20px 0 0;">' + (this.props.friendly || colName) + ' <button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:0;top:0;">&times;</button>' + '</div>',
+				html: true,
+				content: 'TODO: list...', // this.renderListToString.bind(this),
+				template: '' +
+					'<div class="popover" role="tooltip" style="max-width:600px;width:400px;">' +
+						'<div class="arrow"></div>' +
+						'<div style="display:block;position:relative;">' +
+							'<div class="popover-title">' +
+							'</div>' +
+						'</div>' +
+						'<div class="popover-content"></div>' +
+					'</div>'
+			})
+			this.setState({ 'isOpen': false })
+		},
+		componentWillUnmount: function () {
+			if(DBG)console.warn("P5UI__MoreFunctionsDropdownAjax::componentWillUnmount")
+			jQuery(this.rootNode).popover('destroy')
+		},
+		componentWillMount: function() {
+			this._closeDropdownIfClickedOutside = function (event) {
+				if (!this.state.isOpen) return;
 
-        var idHtmlPopover = jQuery(this.rootNode).attr('aria-describedby')
-        if(DBG)console.warn("P5UI__MoreFunctionsDropdownAjax::_closeDropdownIfClickedOutside idHtmlPopover:", idHtmlPopover)
-        if (!idHtmlPopover) return;
+				var idHtmlPopover = jQuery(this.rootNode).attr('aria-describedby')
+				if(DBG)console.warn("P5UI__MoreFunctionsDropdownAjax::_closeDropdownIfClickedOutside idHtmlPopover:", idHtmlPopover)
+				if (!idHtmlPopover) return;
 
-    		var popoverNode = document.getElementById(idHtmlPopover)
-        var isClickedOutside = p5UI__clickedOutsideElement(popoverNode, event)
-        if(DBG)console.warn("P5UI__MoreFunctionsDropdownAjax::_closeDropdownIfClickedOutside isClickedOutside:", isClickedOutside, 'this.rootNode', this.rootNode)
-    		if (isClickedOutside) {
-          if (jQuery(this.rootNode).data("bs.popover")) {
-            jQuery(this.rootNode).popover('hide')
-          } else {
-            popoverNode.parentNode.removeChild(popoverNode) // DOM removed before 'hide'
-          }
-    			this.setState({
-    				isOpen: false
-    			}, this._unbindCloseDropdownIfClickedOutside.bind(this));
-    		}
-    	}.bind(this);
-      this._bindCloseDropdownIfClickedOutside = function () {
-        if(DBG)console.warn("P5UI__MoreFunctionsDropdownAjax::_bindCloseDropdownIfClickedOutside", this._closeDropdownIfClickedOutside)
-    		if (!document.addEventListener && document.attachEvent) {
-    			document.attachEvent('onclick', this._closeDropdownIfClickedOutside);
-    		} else {
-    			document.addEventListener('click', this._closeDropdownIfClickedOutside);
-    		}
-    	}.bind(this);
-      this._unbindCloseDropdownIfClickedOutside = function () {
-        if(DBG)console.warn("P5UI__MoreFunctionsDropdownAjax::_unbindCloseDropdownIfClickedOutside", this._closeDropdownIfClickedOutside)
-    		if (!document.removeEventListener && document.detachEvent) {
-    			document.detachEvent('onclick', this._closeDropdownIfClickedOutside);
-    		} else {
-    			document.removeEventListener('click', this._closeDropdownIfClickedOutside);
-    		}
-    	}.bind(this);
-    },
-    shouldComponentUpdate: function (nextProps, nextState) {
-      if (!nextState) return false
-      if (!this.state) return false
-      if (this.state.rowFunctions !== nextState.rowFunctions) {
-        var idHtmlPopover = jQuery(this.rootNode).attr('aria-describedby')
-        if(DBG)console.warn("P5UI__MoreFunctionsDropdownAjax::shouldComponentUpdate idHtmlPopover:", idHtmlPopover, 'nextState.rowFunctions', nextState.rowFunctions)
-        if (idHtmlPopover && nextState.rowFunctions && nextState.rowFunctions.length) {
-          jQuery(document.getElementById(idHtmlPopover)).find('.popover-content').html(this.renderListToString(nextState.rowFunctions))
-        } else {
-          jQuery(document.getElementById(idHtmlPopover)).find('.popover-content').html('<p class="text-muted">Brak dodatkowych funkcji</p>')
-        }
-      }
-      return false
-    },
-    renderListToString: function (list) {
-      if(DBG)console.warn('P5UI__MoreFunctionsDropdownAjax::renderListToString - this.state:', this.state)
-      var primaryKey = this.props.id
-      var out = '<ul class="list-unstyled">' + list.map(function (fun) {
-        return '<li><a href="'+fun.href.replace('{0}', primaryKey)+'" style="margin:0 2px;" title="'+fun.title+'">' +
-          (fun.ico ? '<span class="'+fun.ico+'"></span> ' : '') +
-          (fun.label || fun.title) +
-        '</a></li>'
-      }).join('') + '</ul>'
-      if(DBG)console.warn('P5UI__MoreFunctionsDropdownAjax::renderListToString - out:', out)
-      return out
-    },
-    onAjaxFetch: function (data) {
-      this.setState({ rowFunctions: data.rowFunctions })
-    },
-    handleClick: function (e) {
-      e.preventDefault()
-      if (!this.props.uri) throw "Missing uri in P5UI__MoreFunctionsDropdownAjax"
-      if (this.state.isOpen) {
-        jQuery(this.rootNode).popover('hide')
-      } else {
-        jQuery(this.rootNode).popover('show')
-        var idHtmlPopover = jQuery(this.rootNode).attr('aria-describedby')
-        if (idHtmlPopover) {
-          jQuery(document.getElementById(idHtmlPopover)).find('.popover-content').html('<p>Loading...</p>')
-        }
-        // global.fetch()
-        // setTimeout(this.onAjaxFetch.bind(this, { msg: "Funkcje", type: "success", rowFunctions: [
-        //   { id: "msgs", ico: "glyphicon glyphicon-envelope", href: "index.php?_route=TableMsgs&_task=tableRow&idTable=13051&idRow=83", label: 'Wiadomości <span class="badge">0</badge>', title: "Wiadomości (0)" },
-        //   { ico: "glyphicon glyphicon-file", href: "https://biuro.biall-net.pl/dev-pl/se-master/index.php?_route=UrlAction_Ant&typeName=default_db:TEST_PERMS&primaryKey=83", label: 'Druki', title: "Druki" },
-        // ] }), 1000)
-        _popoverCellAjaxXhr = jQuery.ajax({
-  				type: 'GET',
-  				url: this.props.uri,
-  				dataType: 'json',
-  				contentType: "application/json; charset=utf-8",
-  			})
-  			.done(function(data, textStatus, jqXHR){
-  				if (data && 'success' === data.type) {
-            var rowFunctions = (data.rowFunctions && data.rowFunctions.length > 0)
-              ? data.rowFunctions
-              : [];
-            this.setState({ rowFunctions: data.rowFunctions })
-    			}
-        }.bind(this))
-        if (this.state.isOpen) this.setState({ 'isOpen': false })
-        else this.setState({ 'isOpen': true }, this._bindCloseDropdownIfClickedOutside)
-      }
-    },
-    render: function () {
-      if(DBG)console.warn('P5UI__MoreFunctionsDropdownAjax::render this.props', this.props)
-      return h('button', {
-        className: 'btn btn-xs btn-link',
-        ref: function (node) { this.rootNode = node; }.bind(this),
-        onClick: this.handleClick.bind(this)
-      }, [
-        h('span', {'className':"glyphicon glyphicon-menu-hamburger"}),
-        " Więcej "
-      ]);
-    }
-  })
-  global.p5VendorJs['P5UI__MoreFunctionsDropdownAjax'] = P5UI__MoreFunctionsDropdownAjax
+				var popoverNode = document.getElementById(idHtmlPopover)
+				var isClickedOutside = p5UI__clickedOutsideElement(popoverNode, event)
+				if(DBG)console.warn("P5UI__MoreFunctionsDropdownAjax::_closeDropdownIfClickedOutside isClickedOutside:", isClickedOutside, 'this.rootNode', this.rootNode)
+				if (isClickedOutside) {
+					if (jQuery(this.rootNode).data("bs.popover")) {
+						jQuery(this.rootNode).popover('hide')
+					} else {
+						popoverNode.parentNode.removeChild(popoverNode) // DOM removed before 'hide'
+					}
+					this.setState({
+						isOpen: false
+					}, this._unbindCloseDropdownIfClickedOutside.bind(this));
+				}
+			}.bind(this);
+			this._bindCloseDropdownIfClickedOutside = function () {
+				if(DBG)console.warn("P5UI__MoreFunctionsDropdownAjax::_bindCloseDropdownIfClickedOutside", this._closeDropdownIfClickedOutside)
+				if (!document.addEventListener && document.attachEvent) {
+					document.attachEvent('onclick', this._closeDropdownIfClickedOutside);
+				} else {
+					document.addEventListener('click', this._closeDropdownIfClickedOutside);
+				}
+			}.bind(this);
+			this._unbindCloseDropdownIfClickedOutside = function () {
+				if(DBG)console.warn("P5UI__MoreFunctionsDropdownAjax::_unbindCloseDropdownIfClickedOutside", this._closeDropdownIfClickedOutside)
+				if (!document.removeEventListener && document.detachEvent) {
+					document.detachEvent('onclick', this._closeDropdownIfClickedOutside);
+				} else {
+					document.removeEventListener('click', this._closeDropdownIfClickedOutside);
+				}
+			}.bind(this);
+		},
+		shouldComponentUpdate: function (nextProps, nextState) {
+			if (!nextState) return false
+			if (!this.state) return false
+			if (this.state.rowFunctions !== nextState.rowFunctions) {
+				var idHtmlPopover = jQuery(this.rootNode).attr('aria-describedby')
+				if(DBG)console.warn("P5UI__MoreFunctionsDropdownAjax::shouldComponentUpdate idHtmlPopover:", idHtmlPopover, 'nextState.rowFunctions', nextState.rowFunctions)
+				if (idHtmlPopover && nextState.rowFunctions && nextState.rowFunctions.length) {
+					jQuery(document.getElementById(idHtmlPopover)).find('.popover-content').html(this.renderListToString(nextState.rowFunctions))
+				} else {
+					jQuery(document.getElementById(idHtmlPopover)).find('.popover-content').html('<p class="text-muted">Brak dodatkowych funkcji</p>')
+				}
+			}
+			return false
+		},
+		renderListToString: function (list) {
+			if(DBG)console.warn('P5UI__MoreFunctionsDropdownAjax::renderListToString - this.state:', this.state)
+			var primaryKey = this.props.id
+			var out = '<ul class="list-unstyled">' + list.map(function (fun) {
+				return '<li><a href="'+fun.href.replace('{0}', primaryKey)+'" style="margin:0 2px;" title="'+fun.title+'">' +
+					(fun.ico ? '<span class="'+fun.ico+'"></span> ' : '') +
+					(fun.label || fun.title) +
+				'</a></li>'
+			}).join('') + '</ul>'
+			if(DBG)console.warn('P5UI__MoreFunctionsDropdownAjax::renderListToString - out:', out)
+			return out
+		},
+		onAjaxFetch: function (data) {
+			this.setState({ rowFunctions: data.rowFunctions })
+		},
+		handleClick: function (e) {
+			e.preventDefault()
+			if (!this.props.uri) throw "Missing uri in P5UI__MoreFunctionsDropdownAjax"
+			if (this.state.isOpen) {
+				jQuery(this.rootNode).popover('hide')
+			} else {
+				jQuery(this.rootNode).popover('show')
+				var idHtmlPopover = jQuery(this.rootNode).attr('aria-describedby')
+				if (idHtmlPopover) {
+					jQuery(document.getElementById(idHtmlPopover)).find('.popover-content').html('<p>Loading...</p>')
+				}
+				// global.fetch()
+				// setTimeout(this.onAjaxFetch.bind(this, { msg: "Funkcje", type: "success", rowFunctions: [
+				//	 { id: "msgs", ico: "glyphicon glyphicon-envelope", href: "index.php?_route=TableMsgs&_task=tableRow&idTable=13051&idRow=83", label: 'Wiadomości <span class="badge">0</badge>', title: "Wiadomości (0)" },
+				//	 { ico: "glyphicon glyphicon-file", href: "https://biuro.biall-net.pl/dev-pl/se-master/index.php?_route=UrlAction_Ant&typeName=default_db:TEST_PERMS&primaryKey=83", label: 'Druki', title: "Druki" },
+				// ] }), 1000)
+				_popoverCellAjaxXhr = jQuery.ajax({
+					type: 'GET',
+					url: this.props.uri,
+					dataType: 'json',
+					contentType: "application/json; charset=utf-8",
+				})
+				.done(function(data, textStatus, jqXHR){
+					if (data && 'success' === data.type) {
+						var rowFunctions = (data.rowFunctions && data.rowFunctions.length > 0)
+							? data.rowFunctions
+							: [];
+						this.setState({ rowFunctions: data.rowFunctions })
+					}
+				}.bind(this))
+				if (this.state.isOpen) this.setState({ 'isOpen': false })
+				else this.setState({ 'isOpen': true }, this._bindCloseDropdownIfClickedOutside)
+			}
+		},
+		render: function () {
+			if(DBG)console.warn('P5UI__MoreFunctionsDropdownAjax::render this.props', this.props)
+			return h('button', {
+				className: 'btn btn-xs btn-link',
+				ref: function (node) { this.rootNode = node; }.bind(this),
+				onClick: this.handleClick.bind(this)
+			}, [
+				h('span', {'className':"glyphicon glyphicon-menu-hamburger"}),
+				" Więcej "
+			]);
+		}
+	})
+	global.p5VendorJs['P5UI__MoreFunctionsDropdownAjax'] = P5UI__MoreFunctionsDropdownAjax
 
 
-  function buildDom(dom, target) {
-    ReactDOM.render(buildReactNodeRec(dom), target)
-  }
-  function buildReactNodeRec(dom) {
-    if (null === dom) return null
-    if ('string' === typeof dom) return dom
-    var nodeReactType = dom[0]
-    if ('P5UI__' === nodeReactType.substr(0, 'P5UI__'.length)) {
-      if (nodeReactType in global.p5VendorJs) nodeReactType = global.p5VendorJs[nodeReactType]
-    }
-    return h(nodeReactType,
-      convertAttrsToReact(dom[0], dom[1]),
-      (dom[2] && 'function' === typeof dom[2].map)
-        ? dom[2].map(buildReactNodeRec)
-        : dom[2]
-    )
-  }
-  function convertAttrsToReact(tagName, attrs) {
-    if (!attrs) return null
-    if(DBG)console.log('todo convertAttrsToReact typeof attrs ('+ typeof attrs +') toString('+ attrs.toString() +')');
-    if (!attrs.toString()) return null
-    if ('class' in attrs) {
-      attrs['className'] = attrs['class']
-      delete attrs['class']
-    }
-    if ('input' === tagName && 'value' in attrs) { // fix input to uncontrolled
-      attrs['defaultValue'] = attrs['value']
-      delete attrs['value']
-    }
-    if ('input' === tagName && 'maxlength' in attrs) { // fix input to uncontrolled
-      attrs['maxLength'] = attrs['maxlength']
-      delete attrs['maxlength']
-    }
-    return attrs
-  }
+	function buildDom(dom, target) {
+		ReactDOM.render(buildReactNodeRec(dom), target)
+	}
+	function buildReactNodeRec(dom) {
+		if (null === dom) return null
+		if ('string' === typeof dom) return dom
+		var nodeReactType = dom[0]
+		if ('P5UI__' === nodeReactType.substr(0, 'P5UI__'.length)) {
+			if (nodeReactType in global.p5VendorJs) nodeReactType = global.p5VendorJs[nodeReactType]
+		}
+		return h(nodeReactType,
+			convertAttrsToReact(dom[0], dom[1]),
+			(dom[2] && 'function' === typeof dom[2].map)
+				? dom[2].map(buildReactNodeRec)
+				: dom[2]
+		)
+	}
+	function convertAttrsToReact(tagName, attrs) {
+		if (!attrs) return null
+		if(DBG)console.log('todo convertAttrsToReact typeof attrs ('+ typeof attrs +') toString('+ attrs.toString() +')');
+		if (!attrs.toString()) return null
+		if ('class' in attrs) {
+			attrs['className'] = attrs['class']
+			delete attrs['class']
+		}
+		if ('input' === tagName && 'value' in attrs) { // fix input to uncontrolled
+			attrs['defaultValue'] = attrs['value']
+			delete attrs['value']
+		}
+		if ('input' === tagName && 'maxlength' in attrs) { // fix input to uncontrolled
+			attrs['maxLength'] = attrs['maxlength']
+			delete attrs['maxlength']
+		}
+		return attrs
+	}
 
-  global.p5UI__buildDom = buildDom
+	global.p5UI__buildDom = buildDom
 })(window, window.p5VendorJs);

+ 7 - 7
SE/static/p5UI/legacy.js

@@ -23,14 +23,14 @@ function ClearAllFind() {
 
 	for (var myprop in ElementsArr){
 
-	     if(ElementsArr[myprop]) {
-		if((ElementsArr[myprop].type=="text")||(ElementsArr[myprop].type=="select-one")){
-			var MyEval="var My"+ElementsArr[myprop].name+"=document.getElementById('"+ElementsArr[myprop].name+"\');";
-			eval(MyEval);
-			var MyEval="My"+ElementsArr[myprop].name+".value=\"%\"";
-			eval(MyEval);
+		if(ElementsArr[myprop]) {
+			if((ElementsArr[myprop].type=="text")||(ElementsArr[myprop].type=="select-one")){
+				var MyEval="var My"+ElementsArr[myprop].name+"=document.getElementById('"+ElementsArr[myprop].name+"\');";
+				eval(MyEval);
+				var MyEval="My"+ElementsArr[myprop].name+".value=\"%\"";
+				eval(MyEval);
+			}
 		}
-	     }
 	}
 }
 

+ 97 - 97
SE/static/p5UI/menuStore.js

@@ -1,115 +1,115 @@
 function p5UI__MenuStore() {
 
-  var _url = ''
-  var _subscribers = []
+	var _url = ''
+	var _subscribers = []
 
-  function _subscribe( fn ) { // fn( { bookmarks, idsBookmarks, objects, urls } )
-    _subscribers.push( fn )
-  }
+	function _subscribe( fn ) { // fn( { bookmarks, idsBookmarks, objects, urls } )
+		_subscribers.push( fn )
+	}
 
-  function _update( data ) { // data: { bookmarks, idsBookmarks, objects, urls }
+	function _update( data ) { // data: { bookmarks, idsBookmarks, objects, urls }
 
-    data.objects.sort(function (a, b) {
-      if (a.raw_label > b.raw_label) return 1
-      if (a.raw_label < b.raw_label) return -1
-      return 0
-    })
-    data.urls.sort(function (a, b) {
-      if (a.raw_label > b.raw_label) return 1
-      if (a.raw_label < b.raw_label) return -1
-      return 0
-    })
+		data.objects.sort(function (a, b) {
+			if (a.raw_label > b.raw_label) return 1
+			if (a.raw_label < b.raw_label) return -1
+			return 0
+		})
+		data.urls.sort(function (a, b) {
+			if (a.raw_label > b.raw_label) return 1
+			if (a.raw_label < b.raw_label) return -1
+			return 0
+		})
 
-    _set('bookmarks', data.bookmarks)
-    _set('idsBookmarks', data.idsBookmarks)
-    _set('objects', data.objects)
-    _set('urls', data.urls)
+		_set('bookmarks', data.bookmarks)
+		_set('idsBookmarks', data.idsBookmarks)
+		_set('objects', data.objects)
+		_set('urls', data.urls)
 
-    var data = _getData()
-    _subscribers.forEach(function (fn) {
-      fn(data)
-    })
-  }
+		var data = _getData()
+		_subscribers.forEach(function (fn) {
+			fn(data)
+		})
+	}
 
-  function _forceUpdate() {
-    var data = _getData()
-    _subscribers.forEach(function (fn) {
-      fn(data)
-    })
-  }
+	function _forceUpdate() {
+		var data = _getData()
+		_subscribers.forEach(function (fn) {
+			fn(data)
+		})
+	}
 
-  function _getData() {
-    return {
-      bookmarks: _get('bookmarks'),
-      idsBookmarks: _get('idsBookmarks'),
-      objects: _get('objects'),
-      urls: _get('urls')
-    }
-  }
+	function _getData() {
+		return {
+			bookmarks: _get('bookmarks'),
+			idsBookmarks: _get('idsBookmarks'),
+			objects: _get('objects'),
+			urls: _get('urls')
+		}
+	}
 
-  function _hasData() {
-    var data = _getData()
-    return (
-      null !== data.bookmarks
-      || null !== data.idsBookmarks
-      || null !== data.objects
-      || null !== data.urls
-    )
-  }
+	function _hasData() {
+		var data = _getData()
+		return (
+			null !== data.bookmarks
+			|| null !== data.idsBookmarks
+			|| null !== data.objects
+			|| null !== data.urls
+		)
+	}
 
-  function _set(type, value) {
-    global.localStorage.setItem('p5Menu.' + type, JSON.stringify(value))
-  }
+	function _set(type, value) {
+		global.localStorage.setItem('p5Menu.' + type, JSON.stringify(value))
+	}
 
-  function _get(type, value) {
-    var val = global.localStorage.getItem('p5Menu.' + type)
-    return val ? JSON.parse(val) : null
-  }
+	function _get(type, value) {
+		var val = global.localStorage.getItem('p5Menu.' + type)
+		return val ? JSON.parse(val) : null
+	}
 
-  function _setRemoteUrl(url) {
-    _url = url
-  }
+	function _setRemoteUrl(url) {
+		_url = url
+	}
 
-  function _remoteUpdate(postData) {
-    var options =
-    window.fetch(_url
-      , (!postData)
-        ? { method: 'GET',
-            headers: { 'Content-Type': 'application/json' },
-            credentials: 'same-origin',
-          }
-        : { method: 'POST',
-            headers: { 'Content-Type': 'application/json' },
-            credentials: 'same-origin',
-            body: JSON.stringify(postData)
-          }
-    ).then(function (response) {
-      return response.json()
-    }).then(function (response) {
-      if ('success' === response.type) {
-        _update(response.body)
-      } else {
-        // err...
-      }
-    })
-  }
+	function _remoteUpdate(postData) {
+		var options =
+		window.fetch(_url
+			, (!postData)
+				?	{ method: 'GET',
+						headers: { 'Content-Type': 'application/json' },
+						credentials: 'same-origin',
+					}
+				:	{ method: 'POST',
+						headers: { 'Content-Type': 'application/json' },
+						credentials: 'same-origin',
+						body: JSON.stringify(postData)
+					}
+		).then(function (response) {
+			return response.json()
+		}).then(function (response) {
+			if ('success' === response.type) {
+				_update(response.body)
+			} else {
+				// err...
+			}
+		})
+	}
 
-  function _clearCache() {
-    global.localStorage.removeItem('p5Menu.' + 'urls')
-    global.localStorage.removeItem('p5Menu.' + 'objects')
-    global.localStorage.removeItem('p5Menu.' + 'bookmarks')
-    global.localStorage.removeItem('p5Menu.' + 'idsBookmarks')
-  }
+	function _clearCache() {
+		global.localStorage.removeItem('p5Menu.' + 'urls')
+		global.localStorage.removeItem('p5Menu.' + 'objects')
+		global.localStorage.removeItem('p5Menu.' + 'bookmarks')
+		global.localStorage.removeItem('p5Menu.' + 'idsBookmarks')
+	}
 
-  return {
-    subscribe: _subscribe,
-    update: _update,
-    forceUpdate: _forceUpdate,
-    setRemoteUrl: _setRemoteUrl,
-    remoteUpdate: _remoteUpdate,
-    getData: _getData,
-    hasData: _hasData,
-    clearCache: _clearCache,
-  }
+	return {
+		subscribe: _subscribe,
+		update: _update,
+		forceUpdate: _forceUpdate,
+		setRemoteUrl: _setRemoteUrl,
+		remoteUpdate: _remoteUpdate,
+		getData: _getData,
+		hasData: _hasData,
+		clearCache: _clearCache,
+	}
 }
 global.p5UI__MenuStore = p5UI__MenuStore()

+ 163 - 163
SE/static/p5UI/userBookmarks.js

@@ -1,169 +1,169 @@
 var $ = global.jQuery
 var UserBookmarks = function() {
-  var priv = {}; //private api
-  var publ = {}; //public api
-
-  priv.options = {};
-  var defaults = {
-    url: '',  //webservice url
-    store: null, // @required
-    debug: false
-  };
-
-  var _cont; // container holding table
-  var _stateEdit = false;
-
-  /*
-   initialize the plugin.
-   */
-  priv.init = function() {
-    _cont = $(priv.options.id);
-
-    priv.options.store.subscribe(
-      (function (global, priv) {
-        return function renderUserBookmarks(data) {
-          priv.setData(data.bookmarks)
-        }
-      })(global, priv)
-    )
-
-    _cont.sortable();
-    _cont.on('sortupdate', priv.sort);
-  };
-
-  priv.setData = function(data) {
-    _cont.empty();
-    data.forEach(function(item) {
-      if (!item) return;
-      if ('type' in item) {
-        var l = $('<a></a>');
-        l.data('id', item.id);
-        l.addClass('btn');
-        l.addClass('btn-xs');
-        var label = item.name, title = '';
-        if (item.hasOwnProperty('class') && item['class'] != '') {
-          l.addClass(item.class);
-        } else {
-          l.addClass('btn-default');
-        }
-        if (item.type == 'menu') {
-          // l.attr('href', 'index.php?_route=ViewTableAjax&typeName=' + 'p5_default_db:' + item.name);
-          l.attr('href', 'index.php?_route=ViewTableAjax&namespace=' + item.namespace);
-          if ('label' in item && item.label.length > 0) {
-            label = item.label;
-            title = item.label + ' (' + item.name + ')';
-          }
-          else if ('opis' in item && item.opis.length > 0) {
-            label = item.opis;
-            title = item.opis + ' (' + item.name + ')';
-          }
-        } else if (item.type == 'url') {
-          l.attr('href', 'index.php?FUNCTION_INIT=URL_INIT&ZASOB_ID=' + item.id);
-          l.attr('target', '_blank');
-        }
-        if (label.length > 20) {
-          var pos = label.indexOf(' - ');
-          if (pos > 20 || pos < 5) {
-            pos = 20;
-            l.text(label.substring(0, pos) + ' ...');
-          } else {
-            l.text(label.substring(0, pos));
-          }
-        } else {
-          l.text(label);
-        }
-        if (title == '') title = label;
-        l.attr('title', title);
-        l.appendTo(_cont);
-
-        if (_stateEdit) {
-          priv.addEditBtns(l);
-        }
-      }
-    });
-
-    if (data.length > 0) {
-      var editBtn = $('<button class="btn btn-xs" style="float:right" title="Edit Bookmarks"><i class="glyphicon glyphicon-cog"></i></button>')
-      editBtn.on('click', priv.edit);
-      editBtn.prependTo(_cont);
-    }
-  };
-
-  priv.changed = function(e) {
-    global.p5UI__MenuStore.remoteUpdate({
-      '_postTask': 'changeBookmark',
-      '_zasobID': e.data.id,
-      btnCls: e.data.cls
-    })
-    return false;
-  };
-
-  priv.removed = function(e) {
-    global.p5UI__MenuStore.remoteUpdate({
-      '_postTask': 'removeBookmark',
-      '_zasobID': e.data.id,
-    })
-    return false;
-  };
-
-  priv.sort = function(e, ui) {
-    var idsOrder = _cont.find('a').map(function(ind, n){
-      return $(n).data('id');
-    });
-    global.p5UI__MenuStore.remoteUpdate({
-      '_postTask': 'sortBookmarks',
-      '_zasobID': 0,
-      ids: idsOrder,
-    })
-    return true;
-  };
-
-  priv.addEditBtns = function(el) {
-    var next, btn;
-    el.wrap('<div></div>');
-    next = $('<span><em> Change color:</em> </span>');
-    $.each(['btn-default', 'btn-primary', 'btn-info', 'btn-success', 'btn-warning', 'btn-danger'], function(btnInd, btnClass){
-      btn = $('<button class="btn btn-xs ' + btnClass + '"> &nbsp; </button>');
-      btn.on('click', {id: el.data('id'), cls: btnClass}, priv.changed);
-      btn.appendTo(next);
-    });
-
-    btn = $('<button class="btn btn-xs"> remove </button>');
-    btn.on('click', {id: el.data('id')}, priv.removed);
-    btn.appendTo(next);
-
-    next.insertAfter(el);
-  };
-
-  priv.edit = function(e) {
-    _stateEdit = !_stateEdit;
-    var el;
-    _cont.find('a').each(function(ind, n){
-      if (priv.options.debug) console.log(n);
-      el = $(n);
-      if (_stateEdit) {
-        priv.addEditBtns(el);
-      } else {
-        el.next().remove();
-        el.unwrap();
-      }
-    });
-  }
-
-  publ.init = function(options) {
-    if (priv.options.debug) console.log('UserBookmarks initialization...');
-    //merge supplied options with defaults
-    $.extend(priv.options, defaults, options);
-    priv.init();
-    return publ;
-  };
-  return publ;
+	var priv = {}; //private api
+	var publ = {}; //public api
+
+	priv.options = {};
+	var defaults = {
+		url: '',	//webservice url
+		store: null, // @required
+		debug: false
+	};
+
+	var _cont; // container holding table
+	var _stateEdit = false;
+
+	/*
+	 initialize the plugin.
+	 */
+	priv.init = function() {
+		_cont = $(priv.options.id);
+
+		priv.options.store.subscribe(
+			(function (global, priv) {
+				return function renderUserBookmarks(data) {
+					priv.setData(data.bookmarks)
+				}
+			})(global, priv)
+		)
+
+		_cont.sortable();
+		_cont.on('sortupdate', priv.sort);
+	};
+
+	priv.setData = function(data) {
+		_cont.empty();
+		data.forEach(function(item) {
+			if (!item) return;
+			if ('type' in item) {
+				var l = $('<a></a>');
+				l.data('id', item.id);
+				l.addClass('btn');
+				l.addClass('btn-xs');
+				var label = item.name, title = '';
+				if (item.hasOwnProperty('class') && item['class'] != '') {
+					l.addClass(item.class);
+				} else {
+					l.addClass('btn-default');
+				}
+				if (item.type == 'menu') {
+					// l.attr('href', 'index.php?_route=ViewTableAjax&typeName=' + 'p5_default_db:' + item.name);
+					l.attr('href', 'index.php?_route=ViewTableAjax&namespace=' + item.namespace);
+					if ('label' in item && item.label.length > 0) {
+						label = item.label;
+						title = item.label + ' (' + item.name + ')';
+					}
+					else if ('opis' in item && item.opis.length > 0) {
+						label = item.opis;
+						title = item.opis + ' (' + item.name + ')';
+					}
+				} else if (item.type == 'url') {
+					l.attr('href', 'index.php?FUNCTION_INIT=URL_INIT&ZASOB_ID=' + item.id);
+					l.attr('target', '_blank');
+				}
+				if (label.length > 20) {
+					var pos = label.indexOf(' - ');
+					if (pos > 20 || pos < 5) {
+						pos = 20;
+						l.text(label.substring(0, pos) + ' ...');
+					} else {
+						l.text(label.substring(0, pos));
+					}
+				} else {
+					l.text(label);
+				}
+				if (title == '') title = label;
+				l.attr('title', title);
+				l.appendTo(_cont);
+
+				if (_stateEdit) {
+					priv.addEditBtns(l);
+				}
+			}
+		});
+
+		if (data.length > 0) {
+			var editBtn = $('<button class="btn btn-xs" style="float:right" title="Edit Bookmarks"><i class="glyphicon glyphicon-cog"></i></button>')
+			editBtn.on('click', priv.edit);
+			editBtn.prependTo(_cont);
+		}
+	};
+
+	priv.changed = function(e) {
+		global.p5UI__MenuStore.remoteUpdate({
+			'_postTask': 'changeBookmark',
+			'_zasobID': e.data.id,
+			btnCls: e.data.cls
+		})
+		return false;
+	};
+
+	priv.removed = function(e) {
+		global.p5UI__MenuStore.remoteUpdate({
+			'_postTask': 'removeBookmark',
+			'_zasobID': e.data.id,
+		})
+		return false;
+	};
+
+	priv.sort = function(e, ui) {
+		var idsOrder = _cont.find('a').map(function(ind, n){
+			return $(n).data('id');
+		});
+		global.p5UI__MenuStore.remoteUpdate({
+			'_postTask': 'sortBookmarks',
+			'_zasobID': 0,
+			ids: idsOrder,
+		})
+		return true;
+	};
+
+	priv.addEditBtns = function(el) {
+		var next, btn;
+		el.wrap('<div></div>');
+		next = $('<span><em> Change color:</em> </span>');
+		$.each(['btn-default', 'btn-primary', 'btn-info', 'btn-success', 'btn-warning', 'btn-danger'], function(btnInd, btnClass){
+			btn = $('<button class="btn btn-xs ' + btnClass + '"> &nbsp; </button>');
+			btn.on('click', {id: el.data('id'), cls: btnClass}, priv.changed);
+			btn.appendTo(next);
+		});
+
+		btn = $('<button class="btn btn-xs"> remove </button>');
+		btn.on('click', {id: el.data('id')}, priv.removed);
+		btn.appendTo(next);
+
+		next.insertAfter(el);
+	};
+
+	priv.edit = function(e) {
+		_stateEdit = !_stateEdit;
+		var el;
+		_cont.find('a').each(function(ind, n){
+			if (priv.options.debug) console.log(n);
+			el = $(n);
+			if (_stateEdit) {
+				priv.addEditBtns(el);
+			} else {
+				el.next().remove();
+				el.unwrap();
+			}
+		});
+	}
+
+	publ.init = function(options) {
+		if (priv.options.debug) console.log('UserBookmarks initialization...');
+		//merge supplied options with defaults
+		$.extend(priv.options, defaults, options);
+		priv.init();
+		return publ;
+	};
+	return publ;
 };
 
 $.fn.UserBookmarks = function(options) {
-  options = options || {};
-  return this.each(function() {
-    options.id = this;
-    $(this).data('UserBookmarks', new UserBookmarks().init(options));
-  });
+	options = options || {};
+	return this.each(function() {
+		options.id = this;
+		$(this).data('UserBookmarks', new UserBookmarks().init(options));
+	});
 };